mirror of
https://github.com/logos-messaging/lab.waku.org.git
synced 2026-01-03 22:33:09 +00:00
52 lines
861 KiB
JavaScript
52 lines
861 KiB
JavaScript
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[948],{4699:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return(r+n)*3/4-n},t.toByteArray=function(e){var t,r,s=l(e),o=s[0],a=s[1],c=new i((o+a)*3/4-a),u=0,h=a>0?o-4:o;for(r=0;r<h;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===a&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[u++]=255&t),1===a&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],o=0,a=n-i;o<a;o+=16383)s.push(function(e,t,n){for(var i,s=[],o=t;o<n;o+=3)s.push(r[(i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]))>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}(e,o,o+16383>a?a:o+16383));return 1===i?s.push(r[(t=e[n-1])>>2]+r[t<<4&63]+"=="):2===i&&s.push(r[(t=(e[n-2]<<8)+e[n-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=s.length;o<a;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},7133:function(e,t,r){"use strict";/*!
|
|
* The buffer module from node.js, for the browser.
|
|
*
|
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
* @license MIT
|
|
*/let n=r(4699),i=r(9087),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function o(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,a.prototype),t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!a.isEncoding(t))throw TypeError("Unknown encoding: "+t);let r=0|f(e,t),n=o(r),i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(e,Uint8Array)){let t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');let n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return a.from(n,t,r);let i=function(e){var t;if(a.isBuffer(e)){let t=0|p(e.length),r=o(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||(t=e.length)!=t?o(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),o(e<0?0:0|p(e))}function h(e){let t=e.length<0?0:0|p(e.length),r=o(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function d(e,t,r){let n;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),a.prototype),n}function p(e){if(e>=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function f(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);let r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return x(e).length;default:if(i)return n?-1:L(e).length;t=(""+t).toLowerCase(),i=!0}}function g(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){let n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=U[e[n]];return i}(this,t,r);case"utf8":case"utf-8":return w(this,t,r);case"ascii":return function(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}(this,t,r);case"latin1":case"binary":return function(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}(this,t,r);case"base64":var s,o;return s=t,o=r,0===s&&o===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(s,o));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){let n=e.slice(t,r),i="";for(let e=0;e<n.length-1;e+=2)i+=String.fromCharCode(n[e]+256*n[e+1]);return i}(this,t,r);default:if(i)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function y(e,t,r){let n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){var s;if(0===e.length)return -1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),(s=r=+r)!=s&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return -1;r=e.length-1}else if(r<0){if(!i)return -1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let s,o=1,a=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return -1;o=2,a/=2,l/=2,r/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let n=-1;for(s=r;s<a;s++)if(c(e,s)===c(t,-1===n?0:s-n)){if(-1===n&&(n=s),s-n+1===l)return n*o}else -1!==n&&(s-=s-n),n=-1}else for(r+l>a&&(r=a-l),s=r;s>=0;s--){let r=!0;for(let n=0;n<l;n++)if(c(e,s+n)!==c(t,n)){r=!1;break}if(r)return s}return -1}function w(e,t,r){r=Math.min(e.length,r);let n=[],i=t;for(;i<r;){let t=e[i],s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=r){let r,n,a,l;switch(o){case 1:t<128&&(s=t);break;case 2:(192&(r=e[i+1]))==128&&(l=(31&t)<<6|63&r)>127&&(s=l);break;case 3:r=e[i+1],n=e[i+2],(192&r)==128&&(192&n)==128&&(l=(15&t)<<12|(63&r)<<6|63&n)>2047&&(l<55296||l>57343)&&(s=l);break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],(192&r)==128&&(192&n)==128&&(192&a)==128&&(l=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a)>65535&&l<1114112&&(s=l)}}null===s?(s=65533,o=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=o}return function(e){let t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=4096));return r}(n)}function v(e,t,r){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>r)throw RangeError("Trying to access beyond buffer length")}function E(e,t,r,n,i,s){if(!a.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw RangeError('"value" argument is out of bounds');if(r+n>e.length)throw RangeError("Index out of range")}function S(e,t,r,n,i){B(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,r}function A(e,t,r,n,i){B(t,n,i,e,r,7);let s=Number(t&BigInt(4294967295));e[r+7]=s,s>>=8,e[r+6]=s,s>>=8,e[r+5]=s,s>>=8,e[r+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=o,o>>=8,e[r+2]=o,o>>=8,e[r+1]=o,o>>=8,e[r]=o,r+8}function I(e,t,r,n,i,s){if(r+n>e.length||r<0)throw RangeError("Index out of range")}function T(e,t,r,n,s){return t=+t,r>>>=0,s||I(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,n,23,4),r+4}function _(e,t,r,n,s){return t=+t,r>>>=0,s||I(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,n,52,8),r+8}t.lW=a,t.h2=50,a.TYPED_ARRAY_SUPPORT=function(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),a.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}}),a.poolSize=8192,a.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array),a.alloc=function(e,t,r){return(c(e),e<=0)?o(e):void 0!==t?"string"==typeof r?o(e).fill(t,r):o(e).fill(t):o(e)},a.allocUnsafe=function(e){return u(e)},a.allocUnsafeSlow=function(e){return u(e)},a.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==a.prototype},a.compare=function(e,t){if(M(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=a.from(t,t.offset,t.byteLength)),!a.isBuffer(e)||!a.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},a.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(e,t){let r;if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);if(void 0===t)for(r=0,t=0;r<e.length;++r)t+=e[r].length;let n=a.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){let t=e[r];if(M(t,Uint8Array))i+t.length>n.length?(a.isBuffer(t)||(t=a.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else if(a.isBuffer(t))t.copy(n,i);else throw TypeError('"list" argument must be an Array of Buffers');i+=t.length}return n},a.byteLength=f,a.prototype._isBuffer=!0,a.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},a.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},a.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},a.prototype.toString=function(){let e=this.length;return 0===e?"":0==arguments.length?w(this,0,e):g.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(e){if(!a.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function(){let e="",r=t.h2;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(a.prototype[s]=a.prototype.inspect),a.prototype.compare=function(e,t,r,n,i){if(M(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;let s=i-n,o=r-t,l=Math.min(s,o),c=this.slice(n,i),u=e.slice(t,r);for(let e=0;e<l;++e)if(c[e]!==u[e]){s=c[e],o=u[e];break}return s<o?-1:o<s?1:0},a.prototype.includes=function(e,t,r){return -1!==this.indexOf(e,t,r)},a.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},a.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)},a.prototype.write=function(e,t,r,n){var i,s,o,a,l,c,u,h;if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let p=!1;for(;;)switch(n){case"hex":return function(e,t,r,n){let i;r=Number(r)||0;let s=e.length-r;n?(n=Number(n))>s&&(n=s):n=s;let o=t.length;for(n>o/2&&(n=o/2),i=0;i<n;++i){let n=parseInt(t.substr(2*i,2),16);if(n!=n)break;e[r+i]=n}return i}(this,e,t,r);case"utf8":case"utf-8":return i=t,s=r,O(L(e,this.length-i),this,i,s);case"ascii":case"latin1":case"binary":return o=t,a=r,O(function(e){let t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(e),this,o,a);case"base64":return l=t,c=r,O(x(e),this,l,c);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u=t,h=r,O(function(e,t){let r,n;let i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=(r=e.charCodeAt(s))>>8,i.push(r%256),i.push(n);return i}(e,this.length-u),this,u,h);default:if(p)throw TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),p=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},a.prototype.slice=function(e,t){let r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);let n=this.subarray(e,t);return Object.setPrototypeOf(n,a.prototype),n},a.prototype.readUintLE=a.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||v(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n},a.prototype.readUintBE=a.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||v(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUint8=a.prototype.readUInt8=function(e,t){return e>>>=0,t||v(e,1,this.length),this[e]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||v(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||v(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||v(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||v(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readBigUInt64LE=F(function(e){P(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&D(e,this.length-8);let n=t+256*this[++e]+65536*this[++e]+16777216*this[++e],i=this[++e]+256*this[++e]+65536*this[++e]+16777216*r;return BigInt(n)+(BigInt(i)<<BigInt(32))}),a.prototype.readBigUInt64BE=F(function(e){P(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&D(e,this.length-8);let n=16777216*t+65536*this[++e]+256*this[++e]+this[++e],i=16777216*this[++e]+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),a.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||v(e,t,this.length);let n=this[e],i=1,s=0;for(;++s<t&&(i*=256);)n+=this[e+s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||v(e,t,this.length);let n=t,i=1,s=this[e+--n];for(;n>0&&(i*=256);)s+=this[e+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},a.prototype.readInt8=function(e,t){return(e>>>=0,t||v(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||v(e,2,this.length);let r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){e>>>=0,t||v(e,2,this.length);let r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||v(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||v(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readBigInt64LE=F(function(e){P(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&D(e,this.length-8);let n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+16777216*this[++e])}),a.prototype.readBigInt64BE=F(function(e){P(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&D(e,this.length-8);let n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(16777216*this[++e]+65536*this[++e]+256*this[++e]+r)}),a.prototype.readFloatLE=function(e,t){return e>>>=0,t||v(e,4,this.length),i.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||v(e,4,this.length),i.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||v(e,8,this.length),i.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||v(e,8,this.length),i.read(this,e,!1,52,8)},a.prototype.writeUintLE=a.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){let n=Math.pow(2,8*r)-1;E(this,e,t,r,n,0)}let i=1,s=0;for(this[t]=255&e;++s<r&&(i*=256);)this[t+s]=e/i&255;return t+r},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){let n=Math.pow(2,8*r)-1;E(this,e,t,r,n,0)}let i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},a.prototype.writeUint8=a.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeBigUInt64LE=F(function(e,t=0){return S(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=F(function(e,t=0){return A(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){let n=Math.pow(2,8*r-1);E(this,e,t,r,n-1,-n)}let i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){let n=Math.pow(2,8*r-1);E(this,e,t,r,n-1,-n)}let i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||E(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeBigInt64LE=F(function(e,t=0){return S(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=F(function(e,t=0){return A(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeFloatLE=function(e,t,r){return T(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return T(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return _(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return _(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(!a.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw RangeError("Index out of range");if(n<0)throw RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);let i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},a.prototype.fill=function(e,t,r,n){let i;if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw TypeError("Unknown encoding: "+n);if(1===e.length){let t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw RangeError("Out of range index");if(r<=t)return this;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{let s=a.isBuffer(e)?e:a.from(e,n),o=s.length;if(0===o)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};let R={};function C(e,t,r){R[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function k(e){let t="",r=e.length,n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function B(e,t,r,n,i,s){if(e>r||e<t){let n;let i="bigint"==typeof t?"n":"";throw n=s>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${(s+1)*8}${i}`:`>= -(2${i} ** ${(s+1)*8-1}${i}) and < 2 ** ${(s+1)*8-1}${i}`:`>= ${t}${i} and <= ${r}${i}`,new R.ERR_OUT_OF_RANGE("value",n,e)}P(i,"offset"),(void 0===n[i]||void 0===n[i+s])&&D(i,n.length-(s+1))}function P(e,t){if("number"!=typeof e)throw new R.ERR_INVALID_ARG_TYPE(t,"number",e)}function D(e,t,r){if(Math.floor(e)!==e)throw P(e,r),new R.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new R.ERR_BUFFER_OUT_OF_BOUNDS;throw new R.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}C("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),C("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),C("ERR_OUT_OF_RANGE",function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>4294967296?i=k(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=k(i)),i+="n"),n+=` It must be ${t}. Received ${i}`},RangeError);let N=/[^+/0-9A-Za-z-_]/g;function L(e,t){let r;t=t||1/0;let n=e.length,i=null,s=[];for(let o=0;o<n;++o){if((r=e.charCodeAt(o))>55295&&r<57344){if(!i){if(r>56319||o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return s}function x(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function M(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}let U=function(){let e="0123456789abcdef",t=Array(256);for(let r=0;r<16;++r){let n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function F(e){return"undefined"==typeof BigInt?K:e}function K(){throw Error("BigInt not supported")}},4461:function(e,t,r){let n;var i=r(2601);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==i&&"env"in i&&(e=i.env.DEBUG),e},t.useColors=function(){return"undefined"!=typeof window&&!!window.process&&("renderer"===window.process.type||!!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(n=!1,()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}),t.colors=["#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"],t.log=console.debug||console.log||(()=>{}),e.exports=r(4239)(t);let{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},4239:function(e,t,r){e.exports=function(e){function t(e){let r,i,s;let o=null;function a(...e){if(!a.enabled)return;let n=Number(new Date),i=n-(r||n);a.diff=i,a.prev=r,a.curr=n,r=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,n)=>{if("%%"===r)return"%";s++;let i=t.formatters[n];if("function"==typeof i){let t=e[s];r=i.call(a,t),e.splice(s,1),s--}return r}),t.formatArgs.call(a,e);let o=a.log||t.log;o.apply(a,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){let n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){let e=[...t.names.map(i),...t.skips.map(i).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];let n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.slice(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){let r,n;if("*"===e[e.length-1])return!0;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=r(438),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},2185:function(e){"use strict";function t(e,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=[,,,,])}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r)&&!(t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.unshift=function(e){if(0==arguments.length)return this.size();var t=this._list.length;return(this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail)?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(0==arguments.length)return this.size();var t=this._tail;return(this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail)?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},t.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t,r=e;if(r===(0|r)&&this._head!==this._tail){var n=this.size(),i=this._list.length;if(!(r>=n)&&!(r<-n)){r<0&&(r+=n),r=this._head+r&this._capacityMask;var s=this._list[r];if(e<n/2){for(t=e;t>0;t--)this._list[r]=this._list[r=r-1+i&this._capacityMask];this._list[r]=void 0,this._head=this._head+1+i&this._capacityMask}else{for(t=n-1-e;t>0;t--)this._list[r]=this._list[r=r+1+i&this._capacityMask];this._list[r]=void 0,this._tail=this._tail-1+i&this._capacityMask}return s}}},t.prototype.remove=function(e,t){var r,n,i=e,s=t;if(i===(0|i)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(i>=o)&&!(i<-o)&&!(t<1)){if(i<0&&(i+=o),1===t||!t)return(r=[,])[0]=this.removeOne(i),r;if(0===i&&i+t>=o)return r=this.toArray(),this.clear(),r;for(i+t>o&&(t=o-i),r=Array(t),n=0;n<t;n++)r[n]=this._list[this._head+i+n&this._capacityMask];if(i=this._head+i&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,n=t;n>0;n--)this._list[i=i+1+a&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+a&this._capacityMask,n=t-1;n>0;n--)this._list[i=i+1+a&this._capacityMask]=void 0;return r}if(i<o/2){for(this._head=this._head+e+t+a&this._capacityMask,n=e;n>0;n--)this.unshift(this._list[i=i-1+a&this._capacityMask]);for(i=this._head-1+a&this._capacityMask;s>0;)this._list[i=i-1+a&this._capacityMask]=void 0,s--;e<0&&(this._tail=i)}else{for(this._tail=i,i=i+t+a&this._capacityMask,n=o-(t+e);n>0;n--)this.push(this._list[i++]);for(i=this._tail;s>0;)this._list[i=i+1+a&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(!(arguments.length>2))return this.remove(r,t);var i,s,o,a=arguments.length,l=this._list.length,c=2;if(!n||r<n/2){for(i=0,s=Array(r);i<r;i++)s[i]=this._list[this._head+i&this._capacityMask];for(0===t?(o=[],r>0&&(this._head=this._head+r+l&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+l&this._capacityMask);a>c;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(s[i-1])}else{var u=(s=Array(n-(r+t))).length;for(i=0;i<u;i++)s[i]=this._list[this._head+r+t+i&this._capacityMask];for(0===t?(o=[],r!=n&&(this._tail=this._head+r+l&this._capacityMask)):(o=this.remove(r,t),this._tail=this._tail-u+l&this._capacityMask);c<a;)this.push(arguments[c++]);for(i=0;i<u;i++)this.push(s[i])}return o}}},t.prototype.clear=function(){this._list=Array(this._list.length),this._head=0,this._tail=0},t.prototype.isEmpty=function(){return this._head===this._tail},t.prototype.toArray=function(){return this._copyArray(!1)},t.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]},t.prototype._copyArray=function(e,t){var r,n=this._list,i=n.length,s=this.length;if((t|=s)==s&&this._head<this._tail)return this._list.slice(this._head,this._tail);var o=Array(t),a=0;if(e||this._head>this._tail){for(r=this._head;r<i;r++)o[a++]=n[r];for(r=0;r<this._tail;r++)o[a++]=n[r]}else for(r=this._head;r<this._tail;r++)o[a++]=n[r];return o},t.prototype._growArray=function(){if(0!=this._head){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1},t.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){return Math.max(1<<Math.log(e)/Math.log(2)+1,4)},e.exports=t},2594:function(e){"use strict";function t(e,t){for(let r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"==typeof e)throw TypeError("Please pass an Error to err-code");n||(n={}),"object"==typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(s){n.message=e.message,n.stack=e.stack;let r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));let i=t(new r,n);return i}}},5986:function(e,t,r){"use strict";let n=r(9831);t.zN=n.EventIterator,n.EventIterator},9831:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){for(let e of(this.isStopped=!0,this.remove(),this.pullQueue))e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped){if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.pullQueue.push({resolve:e,reject:t})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},8729:function(e){"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!=typeof n)throw TypeError("The listener must be a function");var a=new i(n,s||e,o),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=Array(s);i<s;i++)o[i]=n[i].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,i,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var l,c,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,s),!0;case 6:return u.fn.call(u.context,t,n,i,s,o),!0}for(c=1,l=Array(h-1);c<h;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var d,p=u.length;for(c=0;c<p;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),h){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,i);break;default:if(!l)for(d=1,l=Array(h-1);d<h;d++)l[d-1]=arguments[d];u[c].fn.apply(u[c].context,l)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,i){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||n&&a.context!==n||o(this,s);else{for(var l=0,c=[],u=a.length;l<u;l++)(a[l].fn!==t||i&&!a[l].once||n&&a[l].context!==n)&&c.push(a[l]);c.length?this._events[s]=1===c.length?c[0]:c:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},3746:function(e){e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},7935:function(e,t,r){var n,i,s,o,a,l,c,u,h,d,p,f,g,y,m,b=r(2601);!(n="object"==typeof window?window:{}).HI_BASE32_NO_NODE_JS&&"object"==typeof b&&b.versions&&b.versions.node&&(n=r.g),i=!n.HI_BASE32_NO_COMMON_JS&&e.exports,s=r.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},l=[0,0,0,0,0,0,0,0],c=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){for(var t,r,n="",i=e.length,s=0,o=0;s<i;){if((t=e[s++])<=127){n+=String.fromCharCode(t);continue}t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):c(s,n);for(var a=0;a<o;++a)((t=e[s++])<128||t>191)&&c(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&c(s,n),r>1114111&&c(s,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode((r>>10)+55296)+String.fromCharCode((1023&r)+56320))}return n},h=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");e=e.replace(/=/g,"");for(var t,r,n,i,s,o,l,c,u=[],h=0,d=e.length,p=0,f=d>>3<<3;p<f;)t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],l=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255,u[h++]=(s<<7|o<<2|l>>>3)&255,u[h++]=(l<<5|c)&255;var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],i=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],l=a[e.charAt(p++)],u[h++]=(t<<3|r>>>2)&255,u[h++]=(r<<6|n<<1|i>>>4)&255,u[h++]=(i<<4|s>>>1)&255,u[h++]=(s<<7|o<<2|l>>>3)&255),u},d=function(e){for(var t,r,n,i,s,a="",l=e.length,c=0,u=5*parseInt(l/5);c<u;)t=e.charCodeAt(c++),r=e.charCodeAt(c++),n=e.charCodeAt(c++),i=e.charCodeAt(c++),s=e.charCodeAt(c++),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s];var h=l-u;return 1===h?a+=o[(t=e.charCodeAt(c))>>>3]+o[t<<2&31]+"======":2===h?(t=e.charCodeAt(c++),r=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(c++),r=e.charCodeAt(c++),n=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(c++),r=e.charCodeAt(c++),n=e.charCodeAt(c++),i=e.charCodeAt(c),a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"="),a},p=function(e){var t,r,n,i,s,a,c,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(l[0]=l[5],l[1]=l[6],l[2]=l[7],c=p;d<f&&c<5;++d)(a=e.charCodeAt(d))<128?l[c++]=a:(a<2048?l[c++]=192|a>>6:(a<55296||a>=57344?l[c++]=224|a>>12:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),l[c++]=240|a>>18,l[c++]=128|a>>12&63),l[c++]=128|a>>6&63),l[c++]=128|63&a);p=c-5,d===f&&++d,d>f&&c<6&&(u=!0),t=l[0],c>4?(r=l[1],n=l[2],i=l[3],s=l[4],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s]):1===c?h+=o[t>>>3]+o[t<<2&31]+"======":2===c?(r=l[1],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===c?(r=l[1],n=l[2],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):(r=l[1],n=l[2],i=l[3],h+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"=")}while(!u);return h},f=function(e){for(var t,r,n,i,s,a="",l=e.length,c=0,u=5*parseInt(l/5);c<u;)t=e[c++],r=e[c++],n=e[c++],i=e[c++],s=e[c++],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[(i<<3|s>>>5)&31]+o[31&s];var h=l-u;return 1===h?a+=o[(t=e[c])>>>3]+o[t<<2&31]+"======":2===h?(t=e[c++],r=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[c++],r=e[c++],n=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[n<<1&31]+"==="):4===h&&(t=e[c++],r=e[c++],n=e[c++],i=e[c],a+=o[t>>>3]+o[(t<<2|r>>>6)&31]+o[r>>>1&31]+o[(r<<4|n>>>4)&31]+o[(n<<1|i>>>7)&31]+o[i>>>2&31]+o[i<<3&31]+"="),a},y={encode:function(e,t){var r="string"!=typeof e;return(r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r)?f(e):t?d(e):p(e)},decode:g=function(e,t){if(!t)return u(h(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,i,s,o,l,c,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,y=f>>3<<3;g<y;)r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],l=a[e.charAt(g++)],c=a[e.charAt(g++)],d=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)+String.fromCharCode((o<<7|l<<2|c>>>3)&255)+String.fromCharCode((c<<5|d)&255);var m=f-y;return 2===m?p+=String.fromCharCode(((r=a[e.charAt(g++)])<<3|(n=a[e.charAt(g++)])>>>2)&255):4===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],i=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],l=a[e.charAt(g++)],c=a[e.charAt(g++)],p+=String.fromCharCode((r<<3|n>>>2)&255)+String.fromCharCode((n<<6|i<<1|s>>>4)&255)+String.fromCharCode((s<<4|o>>>1)&255)+String.fromCharCode((o<<7|l<<2|c>>>3)&255)),p}},g.asBytes=h,i?e.exports=y:(n.base32=y,s&&void 0!==(m=(function(){return y}).call(y,r,y,e))&&(e.exports=m))},9087:function(e,t){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */t.read=function(e,t,r,n,i){var s,o,a=8*i-n-1,l=(1<<a)-1,c=l>>1,u=-7,h=r?i-1:0,d=r?-1:1,p=e[t+h];for(h+=d,s=p&(1<<-u)-1,p>>=-u,u+=a;u>0;s=256*s+e[t+h],h+=d,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=n;u>0;o=256*o+e[t+h],h+=d,u-=8);if(0===s)s=1-c;else{if(s===l)return o?NaN:(p?-1:1)*(1/0);o+=Math.pow(2,n),s-=c}return(p?-1:1)*o*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var o,a,l,c=8*s-i-1,u=(1<<c)-1,h=u>>1,d=23===i?5960464477539062e-23:0,p=n?0:s-1,f=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(isNaN(t=Math.abs(t))||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+h>=1?t+=d/l:t+=d*Math.pow(2,1-h),t*l>=2&&(o++,l/=2),o+h>=u?(a=0,o=u):o+h>=1?(a=(t*l-1)*Math.pow(2,i),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[r+p]=255&a,p+=f,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;e[r+p]=255&o,p+=f,o/=256,c-=8);e[r+p-f]|=128*g}},9598:function(e,t,r){var n=r(2601);e.exports=function(){return!!("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||void 0!==n&&"object"==typeof n.versions&&n.versions.electron||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},361:function(e){"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},6398:function(e,t,r){var n,i=r(2601);!function(){"use strict";var s="input is invalid type",o="object"==typeof window,a=o?window:{};a.JS_SHA3_NO_WINDOW&&(o=!1);var l=!o&&"object"==typeof self;!a.JS_SHA3_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node?a=r.g:l&&(a=self);for(var c=!a.JS_SHA3_NO_COMMON_JS&&e.exports,u=r.amdO,h=!a.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,d="0123456789abcdef".split(""),p=[4,1024,262144,67108864],f=[0,8,16,24],g=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],y=[224,256,384,512],m=[128,256],b=["hex","buffer","arrayBuffer","array","digest"],w={128:168,256:136},v=a.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,E=h&&(a.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)?function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer}:ArrayBuffer.isView,S=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw Error(s);if(h&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!v(e)&&!E(e))throw Error(s);return[e,!1]},A=function(e){return 0===S(e)[0].length},I=function(e){for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},T=function(e,t,r){return function(n){return new K(e,t,e).update(n)[r]()}},_=function(e,t,r){return function(n,i){return new K(e,t,i).update(n)[r]()}},R=function(e,t,r){return function(t,n,i,s){return D["cshake"+e].update(t,n,i,s)[r]()}},C=function(e,t,r){return function(t,n,i,s){return D["kmac"+e].update(t,n,i,s)[r]()}},k=function(e,t,r,n){for(var i=0;i<b.length;++i){var s=b[i];e[s]=t(r,n,s)}return e},B=function(e,t){var r=T(e,t,"hex");return r.create=function(){return new K(e,t,e)},r.update=function(e){return r.create().update(e)},k(r,T,e,t)},P=[{name:"keccak",padding:[1,256,65536,16777216],bits:y,createMethod:B},{name:"sha3",padding:[6,1536,393216,100663296],bits:y,createMethod:B},{name:"shake",padding:[31,7936,2031616,520093696],bits:m,createMethod:function(e,t){var r=_(e,t,"hex");return r.create=function(r){return new K(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},k(r,_,e,t)}},{name:"cshake",padding:p,bits:m,createMethod:function(e,t){var r=w[e],n=R(e,t,"hex");return n.create=function(n,i,s){return A(i)&&A(s)?D["shake"+e].create(n):new K(e,t,n).bytepad([i,s],r)},n.update=function(e,t,r,i){return n.create(t,r,i).update(e)},k(n,R,e,t)}},{name:"kmac",padding:p,bits:m,createMethod:function(e,t){var r=w[e],n=C(e,t,"hex");return n.create=function(n,i,s){return new V(e,t,i).bytepad(["KMAC",s],r).bytepad([n],r)},n.update=function(e,t,r,i){return n.create(e,r,i).update(t)},k(n,C,e,t)}}],D={},N=[],L=0;L<P.length;++L)for(var x=P[L],O=x.bits,M=0;M<O.length;++M){var U=x.name+"_"+O[M];if(N.push(U),D[U]=x.createMethod(O[M],x.padding),"sha3"!==x.name){var F=x.name+O[M];N.push(F),D[F]=D[U]}}function K(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function V(e,t,r){K.call(this,e,t,r)}K.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=S(e);e=t[0];for(var r,n,i=t[1],s=this.blocks,o=this.byteCount,a=e.length,l=this.blockCount,c=0,u=this.s;c<a;){if(this.reset)for(r=1,this.reset=!1,s[0]=this.block;r<l+1;++r)s[r]=0;if(i)for(r=this.start;c<a&&r<o;++c)(n=e.charCodeAt(c))<128?s[r>>2]|=n<<f[3&r++]:(n<2048?s[r>>2]|=(192|n>>6)<<f[3&r++]:(n<55296||n>=57344?s[r>>2]|=(224|n>>12)<<f[3&r++]:(n=65536+((1023&n)<<10|1023&e.charCodeAt(++c)),s[r>>2]|=(240|n>>18)<<f[3&r++],s[r>>2]|=(128|n>>12&63)<<f[3&r++]),s[r>>2]|=(128|n>>6&63)<<f[3&r++]),s[r>>2]|=(128|63&n)<<f[3&r++]);else for(r=this.start;c<a&&r<o;++c)s[r>>2]|=e[c]<<f[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=s[l],r=0;r<l;++r)u[r]^=s[r];H(u),this.reset=!0}else this.start=r}return this},K.prototype.encode=function(e,t){var r=255&e,n=1,i=[r];for(e>>=8,r=255&e;r>0;)i.unshift(r),e>>=8,r=255&e,++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},K.prototype.encodeString=function(e){var t=S(e);e=t[0];var r=t[1],n=0,i=e.length;if(r)for(var s=0;s<e.length;++s){var o=e.charCodeAt(s);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=i;return n+=this.encode(8*n),this.update(e),n},K.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var i=(t-r%t)%t,s=[];return s.length=i,this.update(s),this},K.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(t=1,e[0]=e[r];t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];H(n)}},K.prototype.toString=K.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a="";o<n;){for(s=0;s<t&&o<n;++s,++o)a+=d[(e=r[s])>>4&15]+d[15&e]+d[e>>12&15]+d[e>>8&15]+d[e>>20&15]+d[e>>16&15]+d[e>>28&15]+d[e>>24&15];o%t==0&&(H(r=I(r)),s=0)}return i&&(a+=d[(e=r[s])>>4&15]+d[15&e],i>1&&(a+=d[e>>12&15]+d[e>>8&15]),i>2&&(a+=d[e>>20&15]+d[e>>16&15])),a},K.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=new ArrayBuffer(i?n+1<<2:a);for(var l=new Uint32Array(e);o<n;){for(s=0;s<t&&o<n;++s,++o)l[o]=r[s];o%t==0&&H(r=I(r))}return i&&(l[o]=r[s],e=e.slice(0,a)),e},K.prototype.buffer=K.prototype.arrayBuffer,K.prototype.digest=K.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,i=this.outputBlocks,s=this.extraBytes,o=0,a=0,l=[];a<i;){for(o=0;o<r&&a<i;++o,++a)e=a<<2,t=n[o],l[e]=255&t,l[e+1]=t>>8&255,l[e+2]=t>>16&255,l[e+3]=t>>24&255;a%r==0&&H(n=I(n))}return s&&(e=a<<2,t=n[o],l[e]=255&t,s>1&&(l[e+1]=t>>8&255),s>2&&(l[e+2]=t>>16&255)),l},V.prototype=new K,V.prototype.finalize=function(){return this.encode(this.outputBits,!0),K.prototype.finalize.call(this)};var H=function(e){var t,r,n,i,s,o,a,l,c,u,h,d,p,f,y,m,b,w,v,E,S,A,I,T,_,R,C,k,B,P,D,N,L,x,O,M,U,F,K,V,H,$,q,z,G,j,W,Y,Q,X,J,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],l=e[4]^e[14]^e[24]^e[34]^e[44],c=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],d=e[8]^e[18]^e[28]^e[38]^e[48],p=e[9]^e[19]^e[29]^e[39]^e[49],t=d^(o<<1|a>>>31),r=p^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(l<<1|c>>>31),r=s^(c<<1|l>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=l^(d<<1|p>>>31),r=c^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,f=e[0],y=e[1],j=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,k=e[20]<<3|e[21]>>>29,B=e[21]<<3|e[20]>>>29,ea=e[31]<<9|e[30]>>>23,el=e[30]<<9|e[31]>>>23,$=e[40]<<18|e[41]>>>14,q=e[41]<<18|e[40]>>>14,x=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,Q=e[23]<<10|e[22]>>>22,P=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,ec=e[42]<<2|e[43]>>>30,eu=e[43]<<2|e[42]>>>30,et=e[5]<<30|e[4]>>>2,er=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,J=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,L=e[44]<<29|e[45]>>>3,T=e[6]<<28|e[7]>>>4,_=e[7]<<28|e[6]>>>4,en=e[17]<<23|e[16]>>>9,ei=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,K=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,R=e[18]<<20|e[19]>>>12,C=e[19]<<20|e[18]>>>12,es=e[29]<<7|e[28]>>>25,eo=e[28]<<7|e[29]>>>25,V=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=f^~m&w,e[1]=y^~b&v,e[10]=T^~R&k,e[11]=_^~C&B,e[20]=x^~M&F,e[21]=O^~U&K,e[30]=z^~j&Y,e[31]=G^~W&Q,e[40]=et^~en&es,e[41]=er^~ei&eo,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~k&P,e[13]=C^~B&D,e[22]=M^~F&V,e[23]=U^~K&H,e[32]=j^~Y&X,e[33]=W^~Q&J,e[42]=en^~es&ea,e[43]=ei^~eo&el,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=k^~P&N,e[15]=B^~D&L,e[24]=F^~V&$,e[25]=K^~H&q,e[34]=Y^~X&Z,e[35]=Q^~J&ee,e[44]=es^~ea&ec,e[45]=eo^~el&eu,e[6]=E^~A&f,e[7]=S^~I&y,e[16]=P^~N&T,e[17]=D^~L&_,e[26]=V^~$&x,e[27]=H^~q&O,e[36]=X^~Z&z,e[37]=J^~ee&G,e[46]=ea^~ec&et,e[47]=el^~eu&er,e[8]=A^~f&m,e[9]=I^~y&b,e[18]=N^~T&R,e[19]=L^~_&C,e[28]=$^~x&M,e[29]=q^~O&U,e[38]=Z^~z&j,e[39]=ee^~G&W,e[48]=ec^~et&en,e[49]=eu^~er&ei,e[0]^=g[n],e[1]^=g[n+1]};if(c)e.exports=D;else{for(L=0;L<N.length;++L)a[N[L]]=D[N[L]];u&&void 0!==(n=(function(){return D}).call(t,r,t,e))&&(e.exports=n)}}()},3498:function(e,t,r){"use strict";let n=r(361),{hasOwnProperty:i}=Object.prototype,{propertyIsEnumerable:s}=Object,o=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,l={concatArrays:!1,ignoreUndefined:!1},c=e=>{let t=[];for(let r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(e);for(let n of r)s.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){let t=e.slice(0,0);return c(e).forEach(r=>{o(t,r,u(e[r]))}),t}(e):n(e)?function(e){let t=null===Object.getPrototypeOf(e)?Object.create(null):{};return c(e).forEach(r=>{o(t,r,u(e[r]))}),t}(e):e}let h=(e,t,r,n)=>(r.forEach(r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?o(e,r,p(e[r],t[r],n)):o(e,r,u(t[r])))}),e),d=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach(t=>{let a=[];for(let r=0;r<t.length;r++)i.call(t,r)&&(a.push(String(r)),t===e?o(n,s++,t[r]):o(n,s++,u(t[r])));n=h(n,t,c(t).filter(e=>!a.includes(e)),r)}),n};function p(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,c(t),r):u(t)}e.exports=function(...e){let t=p(u(l),this!==a&&this||{},l),r={_:{}};for(let i of e)if(void 0!==i){if(!n(i))throw TypeError("`"+i+"` is not an Option Object");r=p(r,{_:i},t)}return r._}},438:function(e){function t(e,t,r,n){return Math.round(e/r)+" "+n+(t>=1.5*r?"s":"")}e.exports=function(e,r){r=r||{};var n,i,s=typeof e;if("string"===s&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return 864e5*r;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*r;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*r;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}(e);if("number"===s&&isFinite(e))return r.long?(n=Math.abs(e))>=864e5?t(e,n,864e5,"day"):n>=36e5?t(e,n,36e5,"hour"):n>=6e4?t(e,n,6e4,"minute"):n>=1e3?t(e,n,1e3,"second"):e+" ms":(i=Math.abs(e))>=864e5?Math.round(e/864e5)+"d":i>=36e5?Math.round(e/36e5)+"h":i>=6e4?Math.round(e/6e4)+"m":i>=1e3?Math.round(e/1e3)+"s":e+"ms";throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},7176:function(e,t,r){e.exports=r(9838)},9838:function(e,t){!function(r,n){"use strict";var i={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function s(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function o(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<<t|e>>>32-t}function l(e){return e^=e>>>16,e=o(e,2246822507),e^=e>>>13,e=o(e,3266489909),e^=e>>>16}function c(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function p(e,t){return[e[0]^t[0],e[1]^t[1]]}function f(e){return e=u(e=p(e,[0,e[0]>>>1]),[4283543511,3981806797]),e=u(e=p(e,[0,e[0]>>>1]),[3301882366,444984403]),e=p(e,[0,e[0]>>>1])}i.x86.hash32=function(e,t){if(!i.inputValidation||s(e)){t=t||0;for(var r=e.length%4,n=e.length-r,c=t,u=0,h=0;h<n;h+=4)u=a(u=o(u=e[h]|e[h+1]<<8|e[h+2]<<16|e[h+3]<<24,3432918353),15),c^=u=o(u,461845907),c=o(c=a(c,13),5)+3864292196;switch(u=0,r){case 3:u^=e[h+2]<<16;case 2:u^=e[h+1]<<8;case 1:u^=e[h],u=a(u=o(u,3432918353),15),c^=u=o(u,461845907)}return c^=e.length,(c=l(c))>>>0}},i.x86.hash128=function(e,t){if(!i.inputValidation||s(e)){t=t||0;for(var r=e.length%16,n=e.length-r,c=t,u=t,h=t,d=t,p=0,f=0,g=0,y=0,m=0;m<n;m+=16)p=e[m]|e[m+1]<<8|e[m+2]<<16|e[m+3]<<24,f=e[m+4]|e[m+5]<<8|e[m+6]<<16|e[m+7]<<24,g=e[m+8]|e[m+9]<<8|e[m+10]<<16|e[m+11]<<24,y=e[m+12]|e[m+13]<<8|e[m+14]<<16|e[m+15]<<24,p=a(p=o(p,597399067),15),c^=p=o(p,2869860233),c=o(c=a(c,19)+u,5)+1444728091,f=a(f=o(f,2869860233),16),u^=f=o(f,951274213),u=o(u=a(u,17)+h,5)+197830471,g=a(g=o(g,951274213),17),h^=g=o(g,2716044179),h=o(h=a(h,15)+d,5)+2530024501,y=a(y=o(y,2716044179),18),d^=y=o(y,597399067),d=o(d=a(d,13)+c,5)+850148119;switch(p=0,f=0,g=0,y=0,r){case 15:y^=e[m+14]<<16;case 14:y^=e[m+13]<<8;case 13:y^=e[m+12],y=a(y=o(y,2716044179),18),d^=y=o(y,597399067);case 12:g^=e[m+11]<<24;case 11:g^=e[m+10]<<16;case 10:g^=e[m+9]<<8;case 9:g^=e[m+8],g=a(g=o(g,951274213),17),h^=g=o(g,2716044179);case 8:f^=e[m+7]<<24;case 7:f^=e[m+6]<<16;case 6:f^=e[m+5]<<8;case 5:f^=e[m+4],f=a(f=o(f,2869860233),16),u^=f=o(f,951274213);case 4:p^=e[m+3]<<24;case 3:p^=e[m+2]<<16;case 2:p^=e[m+1]<<8;case 1:p^=e[m],p=a(p=o(p,597399067),15),c^=p=o(p,2869860233)}return c^=e.length,u^=e.length,h^=e.length,d^=e.length,c+=u+h+d,u+=c,h+=c,d+=c,c=l(c),u=l(u),c+=u+(h=l(h))+(d=l(d)),u+=c,h+=c,d+=c,("00000000"+(c>>>0).toString(16)).slice(-8)+("00000000"+(u>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)}},i.x64.hash128=function(e,t){if(!i.inputValidation||s(e)){t=t||0;for(var r=e.length%16,n=e.length-r,o=[0,t],a=[0,t],l=[0,0],g=[0,0],y=[2277735313,289559509],m=[1291169091,658871167],b=0;b<n;b+=16)l=[e[b+4]|e[b+5]<<8|e[b+6]<<16|e[b+7]<<24,e[b]|e[b+1]<<8|e[b+2]<<16|e[b+3]<<24],g=[e[b+12]|e[b+13]<<8|e[b+14]<<16|e[b+15]<<24,e[b+8]|e[b+9]<<8|e[b+10]<<16|e[b+11]<<24],l=h(l=u(l,y),31),o=c(o=h(o=p(o,l=u(l,m)),27),a),o=c(u(o,[0,5]),[0,1390208809]),g=h(g=u(g,m),33),a=c(a=h(a=p(a,g=u(g,y)),31),o),a=c(u(a,[0,5]),[0,944331445]);switch(l=[0,0],g=[0,0],r){case 15:g=p(g,d([0,e[b+14]],48));case 14:g=p(g,d([0,e[b+13]],40));case 13:g=p(g,d([0,e[b+12]],32));case 12:g=p(g,d([0,e[b+11]],24));case 11:g=p(g,d([0,e[b+10]],16));case 10:g=p(g,d([0,e[b+9]],8));case 9:g=h(g=u(g=p(g,[0,e[b+8]]),m),33),a=p(a,g=u(g,y));case 8:l=p(l,d([0,e[b+7]],56));case 7:l=p(l,d([0,e[b+6]],48));case 6:l=p(l,d([0,e[b+5]],40));case 5:l=p(l,d([0,e[b+4]],32));case 4:l=p(l,d([0,e[b+3]],24));case 3:l=p(l,d([0,e[b+2]],16));case 2:l=p(l,d([0,e[b+1]],8));case 1:l=h(l=u(l=p(l,[0,e[b]]),y),31),o=p(o,l=u(l,m))}return o=c(o=p(o,[0,e.length]),a=p(a,[0,e.length])),a=c(a,o),o=c(o=f(o),a=f(a)),a=c(a,o),("00000000"+(o[0]>>>0).toString(16)).slice(-8)+("00000000"+(o[1]>>>0).toString(16)).slice(-8)+("00000000"+(a[0]>>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)}},e.exports&&(t=e.exports=i),t.murmurHash3=i}(0)},5194:function(e,t){(function(){var e,r,n,i,s,o,a,l;l=function(e){return[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,s,o,a;for(t=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),s=n("A"),r=function(e){var t,r,a,l,c;for(l=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),c=a;a<e.length;){if("0"<=e[a]&&e[a]<=r)l=l*t+(n(e[a])-i)>>>0;else if(16===t){if("a"<=e[a]&&e[a]<="f")l=l*t+(10+n(e[a])-o)>>>0;else if("A"<=e[a]&&e[a]<="F")l=l*t+(10+n(e[a])-s)>>>0;else break}else break;if(l>4294967295)throw Error("too large");a++}if(a===c)throw Error("empty octet");return[l,a]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(e=(i=e.split("/",2))[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else if(t||0===t)this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw Error("Invalid mask: empty");try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=l(this.netLong),this.mask=l(this.maskLong),this.hostmask=l(~this.maskLong),this.first=this.bitmask<=30?l(this.netLong+1):this.base,this.last=this.bitmask<=30?l(this.netLong+this.size-2):l(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?l(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return("string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e)?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(l(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(l(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=l,t.Netmask=e}).call(this)},2601:function(e,t,r){"use strict";var n,i;e.exports=(null==(n=r.g.process)?void 0:n.env)&&"object"==typeof(null==(i=r.g.process)?void 0:i.env)?r.g.process:r(8960)},8960:function(e){!function(){var t={229:function(e){var t,r,n,i=e.exports={};function s(){throw Error("setTimeout has not been defined")}function o(){throw Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var l=[],c=!1,u=-1;function h(){c&&n&&(c=!1,n.length?l=n.concat(l):u=-1,l.length&&d())}function d(){if(!c){var e=a(h);c=!0;for(var t=l.length;t;){for(n=l,l=[];++u<t;)n&&n[u].run();u=-1,t=l.length}n=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===o||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function f(){}i.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new p(e,t)),1!==l.length||c||a(d)},p.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=f,i.addListener=f,i.once=f,i.off=f,i.removeListener=f,i.removeAllListeners=f,i.emit=f,i.prependListener=f,i.prependOnceListener=f,i.listeners=function(e){return[]},i.binding=function(e){throw Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw Error("process.chdir is not supported")},i.umask=function(){return 0}}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var s=r[e]={exports:{}},o=!0;try{t[e](s,s.exports,n),o=!1}finally{o&&delete r[e]}return s.exports}n.ab="//";var i=n(229);e.exports=i}()},622:function(e,t,r){"use strict";var n=r(2265),i=Symbol.for("react.element"),s=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(e,t,r){var n,s={},c=null,u=null;for(n in void 0!==r&&(c=""+r),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(u=t.ref),t)o.call(t,n)&&!l.hasOwnProperty(n)&&(s[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===s[n]&&(s[n]=t[n]);return{$$typeof:i,type:e,key:c,ref:u,props:s,_owner:a.current}}t.Fragment=s,t.jsx=c,t.jsxs=c},7437:function(e,t,r){"use strict";e.exports=r(622)},1250:function(e,t,r){var n,i,s,o,a,l=r(2595);function c(e,t){l.cipher.registerAlgorithm(e,function(){return new l.aes.Algorithm(e,t)})}r(6823),r(3195),r(2366),e.exports=l.aes=l.aes||{},l.aes.startEncrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},l.aes.createEncryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!1,mode:t})},l.aes.startDecrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},l.aes.createDecryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!0,mode:t})},l.aes.Algorithm=function(e,t){u||h();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return p(r._w,e,t,!1)},decrypt:function(e,t){return p(r._w,e,t,!0)}}}),r._init=!1},l.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"==typeof r&&(16===r.length||24===r.length||32===r.length))r=l.util.createBuffer(r);else if(l.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=l.util.createBuffer();for(var n=0;n<t.length;++n)r.putByte(t[n])}if(!l.util.isArray(r)){t=r,r=[];var i=t.length();if(16===i||24===i||32===i){i>>>=2;for(var n=0;n<i;++n)r.push(t.getInt32())}}if(!l.util.isArray(r)||!(4===r.length||6===r.length||8===r.length))throw Error("Invalid key parameter.");var s=-1!==["CFB","OFB","CTR","GCM"].indexOf(this.mode.name);this._w=d(r,e.decrypt&&!s),this._init=!0}},l.aes._expandKey=function(e,t){return u||h(),d(e,t)},l.aes._updateBlock=p,c("AES-ECB",l.cipher.modes.ecb),c("AES-CBC",l.cipher.modes.cbc),c("AES-CFB",l.cipher.modes.cfb),c("AES-OFB",l.cipher.modes.ofb),c("AES-CTR",l.cipher.modes.ctr),c("AES-GCM",l.cipher.modes.gcm);var u=!1;function h(){u=!0,s=[0,1,2,4,8,16,32,64,128,27,54];for(var e=Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;n=Array(256),i=Array(256),o=[,,,,],a=[,,,,];for(var t=0;t<4;++t)o[t]=Array(256),a[t]=Array(256);for(var r,l,c,h,d,p,f,g=0,y=0,t=0;t<256;++t){h=(h=y^y<<1^y<<2^y<<3^y<<4)>>8^255&h^99,n[g]=h,i[h]=g,d=e[h],r=e[g],l=e[r],c=e[l],p=d<<24^h<<16^h<<8^(h^d),f=(r^l^c)<<24^(g^c)<<16^(g^l^c)<<8^(g^r^c);for(var m=0;m<4;++m)o[m][g]=p,a[m][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=y=1:(g=r^e[e[e[r^c]]],y^=e[e[y]])}}function d(e,t){for(var r,i=e.slice(0),o=1,l=i.length,c=4*(l+6+1),u=l;u<c;++u)r=i[u-1],u%l==0?(r=n[r>>>16&255]<<24^n[r>>>8&255]<<16^n[255&r]<<8^n[r>>>24]^s[o]<<24,o++):l>6&&u%l==4&&(r=n[r>>>24]<<24^n[r>>>16&255]<<16^n[r>>>8&255]<<8^n[255&r]),i[u]=i[u-l]^r;if(t){var h,d=a[0],p=a[1],f=a[2],g=a[3],y=i.slice(0);c=i.length;for(var u=0,m=c-4;u<c;u+=4,m-=4)if(0===u||u===c-4)y[u]=i[m],y[u+1]=i[m+3],y[u+2]=i[m+2],y[u+3]=i[m+1];else for(var b=0;b<4;++b)h=i[m+b],y[u+(3&-b)]=d[n[h>>>24]]^p[n[h>>>16&255]]^f[n[h>>>8&255]]^g[n[255&h]];i=y}return i}function p(e,t,r,s){var l,c,u,h,d,p,f,g,y,m,b,w,v=e.length/4-1;s?(l=a[0],c=a[1],u=a[2],h=a[3],d=i):(l=o[0],c=o[1],u=o[2],h=o[3],d=n),p=t[0]^e[0],f=t[s?3:1]^e[1],g=t[2]^e[2],y=t[s?1:3]^e[3];for(var E=3,S=1;S<v;++S)m=l[p>>>24]^c[f>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],b=l[f>>>24]^c[g>>>16&255]^u[y>>>8&255]^h[255&p]^e[++E],w=l[g>>>24]^c[y>>>16&255]^u[p>>>8&255]^h[255&f]^e[++E],y=l[y>>>24]^c[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++E],p=m,f=b,g=w;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[s?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&p]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++E],r[s?1:3]=d[y>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++E]}function f(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?l.cipher.createDecipher(r,e.key):l.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof l.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,n.call(t,r)},t}},9642:function(e,t,r){var n=r(2595);r(2366),r(552);var i=e.exports=n.asn1=n.asn1||{};function s(e,t,r){if(r>t){var n=Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,s,o){if(n.util.isArray(s)){for(var a=[],l=0;l<s.length;++l)void 0!==s[l]&&a.push(s[l]);s=a}var c={tagClass:e,type:t,constructed:r,composed:r||n.util.isArray(s),value:s};return o&&"bitStringContents"in o&&(c.bitStringContents=o.bitStringContents,c.original=i.copy(c)),c},i.copy=function(e,t){var r;if(n.util.isArray(e)){r=[];for(var s=0;s<e.length;++s)r.push(i.copy(e[s],t));return r}return"string"==typeof e?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:i.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)},i.equals=function(e,t,r){if(n.util.isArray(e)){if(!n.util.isArray(t)||e.length!==t.length)return!1;for(var s=0;s<e.length;++s)if(!i.equals(e[s],t[s]))return!1;return!0}if(typeof e!=typeof t)return!1;if("string"==typeof e)return e===t;var o=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&i.equals(e.value,t.value);return r&&r.includeBitStringContents&&(o=o&&e.bitStringContents===t.bitStringContents),o},i.getBerValueLength=function(e){var t=e.getByte();if(128!==t)return 128&t?e.getInt((127&t)<<3):t};var o=function(e,t){var r,n=e.getByte();if(t--,128!==n){if(128&n){var i=127&n;s(e,t,i),r=e.getInt(i<<3)}else r=n;if(r<0)throw Error("Negative length: "+r);return r}};i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"==typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.length(),a=function e(t,r,n,a){s(t,r,2);var l,c,u,h=t.getByte();r--;var d=192&h,p=31&h;l=t.length();var f=o(t,r);if(r-=l-t.length(),void 0!==f&&f>r){if(a.strict){var g=Error("Too few bytes to read ASN.1 value.");throw g.available=t.length(),g.remaining=r,g.requested=f,g}f=r}var y=(32&h)==32;if(y){if(c=[],void 0===f)for(;;){if(s(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}l=t.length(),c.push(e(t,r,n+1,a)),r-=l-t.length()}else for(;f>0;)l=t.length(),c.push(e(t,f,n+1,a)),r-=l-t.length(),f-=l-t.length()}if(void 0===c&&d===i.Class.UNIVERSAL&&p===i.Type.BITSTRING&&(u=t.bytes(f)),void 0===c&&a.decodeBitStrings&&d===i.Class.UNIVERSAL&&p===i.Type.BITSTRING&&f>1){var m=t.read,b=r,w=0;if(p===i.Type.BITSTRING&&(s(t,r,1),w=t.getByte(),r--),0===w)try{l=t.length();var v=e(t,r,n+1,{strict:!0,decodeBitStrings:!0}),E=l-t.length();r-=E,p==i.Type.BITSTRING&&E++;var S=v.tagClass;E===f&&(S===i.Class.UNIVERSAL||S===i.Class.CONTEXT_SPECIFIC)&&(c=[v])}catch(e){}void 0===c&&(t.read=m,r=b)}if(void 0===c){if(void 0===f){if(a.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");f=r}if(p===i.Type.BMPSTRING)for(c="";f>0;f-=2)s(t,r,2),c+=String.fromCharCode(t.getInt16()),r-=2;else c=t.getBytes(f),r-=f}var A=void 0===u?null:{bitStringContents:u};return i.create(d,p,y,c,A)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var l=Error("Unparsed DER bytes remain after ASN.1 parsing.");throw l.byteCount=r,l.remaining=e.length(),l}return a},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,s=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=i.equals(e,e.original))),o)s.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:s.putByte(0);for(var a=0;a<e.value.length;++a)void 0!==e.value[a]&&s.putBuffer(i.toDer(e.value[a]))}else if(e.type===i.Type.BMPSTRING)for(var a=0;a<e.value.length;++a)s.putInt16(e.value.charCodeAt(a));else e.type===i.Type.INTEGER&&e.value.length>1&&(0===e.value.charCodeAt(0)&&(128&e.value.charCodeAt(1))==0||255===e.value.charCodeAt(0)&&(128&e.value.charCodeAt(1))==128)?s.putBytes(e.value.substr(1)):s.putBytes(e.value);if(t.putByte(r),127>=s.length())t.putByte(127&s.length());else{var l=s.length(),c="";do c+=String.fromCharCode(255&l),l>>>=8;while(l>0);t.putByte(128|c.length);for(var a=c.length-1;a>=0;--a)t.putByte(c.charCodeAt(a))}return t.putBuffer(s),t},i.oidToDer=function(e){var t,r,i,s,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var l=2;l<o.length;++l){t=!0,r=[],i=parseInt(o[l],10);do s=127&i,i>>>=7,t||(s|=128),r.push(s),t=!1;while(i>0);for(var c=r.length-1;c>=0;--c)a.putByte(r[c])}return a},i.derToOid=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t,r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)r=e.getByte(),i<<=7,128&r?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var l=e.charAt(10),c=10;"+"!==l&&"-"!==l&&(a=parseInt(e.substr(10,2),10),c+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,0),c&&("+"===(l=e.charAt(c))||"-"===l)){var u=60*parseInt(e.substr(c+1,2),10)+parseInt(e.substr(c+4,2),10);u*=6e4,"+"===l?t.setTime(+t-u):t.setTime(+t+u)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);return("+"===d||"-"===d)&&(c=(60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10))*6e4,"+"===d&&(c*=-1),u=!0),"."===e.charAt(14)&&(l=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,l),t.setTime(+t+c)):(t.setFullYear(r,n,i),t.setHours(s,o,a,l)),t},i.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+"Z"},i.dateToGeneralizedTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+"Z"},i.integerToDer=function(e){var t=n.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,s){var o=!1;if((e.tagClass===t.tagClass||void 0===t.tagClass)&&(e.type===t.type||void 0===t.type)){if(e.constructed===t.constructed||void 0===t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,l=0;o&&l<t.value.length;++l)o=t.value[l].optional||!1,e.value[a]&&((o=i.validate(e.value[a],t.value[l],r,s))?++a:t.value[l].optional&&(o=!0)),!o&&s&&s.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(o&&r&&(t.capture&&(r[t.capture]=e.value),t.captureAsn1&&(r[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(r[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e)){if(e.bitStringContents.length<2)r[t.captureBitStringValue]="";else{if(0!==e.bitStringContents.charCodeAt(0))throw Error("captureBitStringValue only supported for zero unused bits");r[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}else s&&s.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"')}else s&&(e.tagClass!==t.tagClass&&s.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&s.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return o};var a=/[^\\u0000-\\u00ff]/;i.prettyPrint=function(e,t,r){var s="";r=r||2,(t=t||0)>0&&(s+="\n");for(var o="",l=0;l<t*r;++l)o+=" ";switch(s+=o+"Tag: ",e.tagClass){case i.Class.UNIVERSAL:s+="Universal:";break;case i.Class.APPLICATION:s+="Application:";break;case i.Class.CONTEXT_SPECIFIC:s+="Context-Specific:";break;case i.Class.PRIVATE:s+="Private:"}if(e.tagClass===i.Class.UNIVERSAL)switch(s+=e.type,e.type){case i.Type.NONE:s+=" (None)";break;case i.Type.BOOLEAN:s+=" (Boolean)";break;case i.Type.INTEGER:s+=" (Integer)";break;case i.Type.BITSTRING:s+=" (Bit string)";break;case i.Type.OCTETSTRING:s+=" (Octet string)";break;case i.Type.NULL:s+=" (Null)";break;case i.Type.OID:s+=" (Object Identifier)";break;case i.Type.ODESC:s+=" (Object Descriptor)";break;case i.Type.EXTERNAL:s+=" (External or Instance of)";break;case i.Type.REAL:s+=" (Real)";break;case i.Type.ENUMERATED:s+=" (Enumerated)";break;case i.Type.EMBEDDED:s+=" (Embedded PDV)";break;case i.Type.UTF8:s+=" (UTF8)";break;case i.Type.ROID:s+=" (Relative Object Identifier)";break;case i.Type.SEQUENCE:s+=" (Sequence)";break;case i.Type.SET:s+=" (Set)";break;case i.Type.PRINTABLESTRING:s+=" (Printable String)";break;case i.Type.IA5String:s+=" (IA5String (ASCII))";break;case i.Type.UTCTIME:s+=" (UTC time)";break;case i.Type.GENERALIZEDTIME:s+=" (Generalized time)";break;case i.Type.BMPSTRING:s+=" (BMP String)"}else s+=e.type;if(s+="\n"+(o+"Constructed: ")+e.constructed+"\n",e.composed){for(var c=0,u="",l=0;l<e.value.length;++l)void 0!==e.value[l]&&(c+=1,u+=i.prettyPrint(e.value[l],t+1,r),l+1<e.value.length&&(u+=","));s+=o+"Sub values: "+c+u}else{if(s+=o+"Value: ",e.type===i.Type.OID){var h=i.derToOid(e.value);s+=h,n.pki&&n.pki.oids&&h in n.pki.oids&&(s+=" ("+n.pki.oids[h]+") ")}if(e.type===i.Type.INTEGER)try{s+=i.derToInteger(e.value)}catch(t){s+="0x"+n.util.bytesToHex(e.value)}else if(e.type===i.Type.BITSTRING){if(e.value.length>1?s+="0x"+n.util.bytesToHex(e.value.slice(1)):s+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?s+=" (1 unused bit shown)":d>1&&(s+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(s+="("+e.value+") "),s+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{s+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"===t.message)s+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)";else throw t}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?s+=e.value:a.test(e.value)?s+="0x"+n.util.bytesToHex(e.value):0===e.value.length?s+="[null]":s+=e.value}return s}},4446:function(e,t,r){var n=r(2678).Buffer,i={};e.exports=i;var s={};i.encode=function(e,t,r){if("string"!=typeof t)throw TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),a=[0];for(i=0;i<e.length;++i){for(var l=0,c=e[i];l<a.length;++l)c+=a[l]<<8,a[l]=c%s,c=c/s|0;for(;c>0;)a.push(c%s),c=c/s|0}for(i=0;0===e[i]&&i<e.length-1;++i)n+=o;for(i=a.length-1;i>=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),s=[0];for(r=0;r<e.length();++r){for(var o=0,a=e.at(r);o<s.length;++o)a+=s[o]<<8,s[o]=a%n,a=a/n|0;for(;a>0;)s.push(a%n),a=a/n|0}var l="";for(r=0;0===e.at(r)&&r<e.length()-1;++r)l+=i;for(r=s.length-1;r>=0;--r)l+=t[s[r]];return l}(e,t);if(r){var u=RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},i.decode=function(e,t){if("string"!=typeof e)throw TypeError('"input" must be a string.');if("string"!=typeof t)throw TypeError('"alphabet" must be a string.');var r=s[t];if(!r){r=s[t]=[];for(var i=0;i<t.length;++i)r[t.charCodeAt(i)]=i}e=e.replace(/\s/g,"");for(var o=t.length,a=t.charAt(0),l=[0],i=0;i<e.length;i++){var c=r[e.charCodeAt(i)];if(void 0===c)return;for(var u=0,h=c;u<l.length;++u)h+=l[u]*o,l[u]=255&h,h>>=8;for(;h>0;)l.push(255&h),h>>=8}for(var d=0;e[d]===a&&d<e.length-1;++d)l.push(0);return void 0!==n?n.from(l.reverse()):new Uint8Array(l.reverse())}},6823:function(e,t,r){var n=r(2595);r(2366),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"==typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"==typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){var t={};for(var r in e=e||{})t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){e&&("ECB"===this.mode.name||"CBC"===this.mode.name)&&(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!!(this._decrypt||!this.mode.pad||this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),(!this._decrypt||!this.mode.unpad||!!this.mode.unpad(this.output,t))&&(!this.mode.afterFinish||!!this.mode.afterFinish(this.output,t)))}},3195:function(e,t,r){var n=r(2595);r(2366),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function s(e,t){if("string"==typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i<r.length;++i)e.putByte(r[i])}if(e.length()<t)throw Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!n.util.isArray(e)){for(var s=[],o=t/4,i=0;i<o;++i)s.push(e.getInt32());e=s}return e}function o(e){e[e.length-1]=e[e.length-1]+1&4294967295}function a(e){return[e/4294967296|0,4294967295&e]}i.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)},i.ecb.prototype.start=function(e){},i.ecb.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])},i.ecb.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n])},i.ecb.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0},i.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=s(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw Error("Invalid IV parameter.")},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=this._prev[n]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]);this._prev=this._outBlock},i.cbc.prototype.decrypt=function(e,t,r){if(e.length()<this.blockSize&&!(r&&e.length()>0))return!0;for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._prev[n]^this._outBlock[n]);this._prev=this._inBlock.slice(0)},i.cbc.prototype.pad=function(e,t){var r=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(r,r),!0},i.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i<this._ints;++i)this._inBlock[i]=e.getInt32()^this._outBlock[i],t.putInt32(this._inBlock[i]);return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32()^this._outBlock[i],this._partialOutput.putInt32(this._partialBlock[i]);if(s>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i<this._ints;++i)this._inBlock[i]=e.getInt32(),t.putInt32(this._inBlock[i]^this._outBlock[i]);return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[i]^this._outBlock[i]);if(s>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i<this._ints;++i)t.putInt32(e.getInt32()^this._outBlock[i]),this._inBlock[i]=this._outBlock[i];return}var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._outBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i<this._ints;++i)t.putInt32(e.getInt32()^this._outBlock[i]);else{var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw Error("Authentication tag does not match tag length.");this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var s=t.length()%this.blockSize;for(s&&t.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i<this._ints;++i)t.putInt32(this._outBlock[i]^=e.getInt32());this._cipherLength+=this.blockSize}else{var s=(this.blockSize-n)%this.blockSize;s>0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s<=0||r){if(r){var a=n%this.blockSize;this._cipherLength+=a,this._partialOutput.truncate(this.blockSize-a)}else this._cipherLength+=this.blockSize;for(var i=0;i<this._ints;++i)this._outBlock[i]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n<this.blockSize&&!(r&&n>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i<this._ints;++i)t.putInt32(this._outBlock[i]^this._hashBlock[i]);n<this.blockSize?this._cipherLength+=n%this.blockSize:this._cipherLength+=this.blockSize},i.gcm.prototype.afterFinish=function(e,t){var r=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=n.util.createBuffer();var i=this._aDataLength.concat(a(8*this._cipherLength));this._s=this.ghash(this._hashSubkey,this._s,i);var s=[];this.cipher.encrypt(this._j0,s);for(var o=0;o<this._ints;++o)this.tag.putInt32(this._s[o]^s[o]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(r=!1),r},i.gcm.prototype.multiply=function(e,t){for(var r=[0,0,0,0],n=t.slice(0),i=0;i<128;++i)e[i/32|0]&1<<31-i%32&&(r[0]^=n[0],r[1]^=n[1],r[2]^=n[2],r[3]^=n[3]),this.pow(n,n);return r},i.gcm.prototype.pow=function(e,t){for(var r=1&e[3],n=3;n>0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>(7-r%8)*4&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,s=Array(i),o=0;o<i;++o){var a=[0,0,0,0],l=o/n|0,c=(n-1-o%n)*t;a[l]=1<<t-1<<c,s[o]=this.generateSubHashTable(this.multiply(a,e),t)}return s},i.gcm.prototype.generateSubHashTable=function(e,t){var r=1<<t,n=r>>>1,i=Array(r);i[n]=e.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s<n;){for(var o=1;o<s;++o){var a=i[s],l=i[o];i[s+o]=[a[0]^l[0],a[1]^l[1],a[2]^l[2],a[3]^l[3]]}s*=2}for(i[0]=[0,0,0,0],s=n+1;s<r;++s){var c=i[s^n];i[s]=[e[0]^c[0],e[1]^c[1],e[2]^c[2],e[3]^c[3]]}return i}},2906:function(e,t,r){var n=r(2595);function i(e,t){n.cipher.registerAlgorithm(e,function(){return new n.des.Algorithm(e,t)})}r(6823),r(3195),r(2366),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=f({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return f({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return p(r._keys,e,t,!1)},decrypt:function(e,t){return p(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],l=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,v=0;v<y;v++){var E=e.getInt32(),S=e.getInt32();t=(E>>>4^S)&252645135,S^=t,E^=t<<4,t=(S>>>-16^E)&65535,E^=t,S^=t<<-16,t=(E>>>2^S)&858993459,S^=t,E^=t<<2,t=(S>>>-16^E)&65535,E^=t,S^=t<<-16,t=(E>>>1^S)&1431655765,S^=t,E^=t<<1,t=(S>>>8^E)&16711935,E^=t,S^=t<<8,t=(E>>>1^S)&1431655765,S^=t,E^=t<<1,t=E<<8|S>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var A=0;A<b.length;++A){b[A]?(E=E<<2|E>>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15;var I=r[(E&=-15)>>>28]|n[E>>>24&15]|i[E>>>20&15]|s[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|l[E>>>4&15],T=c[S>>>28]|u[S>>>24&15]|h[S>>>20&15]|d[S>>>16&15]|p[S>>>12&15]|f[S>>>8&15]|g[S>>>4&15];t=(T>>>16^I)&65535,m[w++]=I^t,m[w++]=T^t<<16}}return m}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],l=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],c=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function p(e,t,r,n){var i,p,f=32===e.length?3:9;i=3===f?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];p=(g>>>4^y)&252645135,y^=p,g^=p<<4,p=(g>>>16^y)&65535,y^=p,g^=p<<16,p=(y>>>2^g)&858993459,g^=p,y^=p<<2,p=(y>>>8^g)&16711935,g^=p,y^=p<<8,p=(g>>>1^y)&1431655765,y^=p,g^=p<<1,g=g<<1|g>>>31,y=y<<1|y>>>31;for(var m=0;m<f;m+=3){for(var b=i[m+1],w=i[m+2],v=i[m];v!=b;v+=w){var E=y^e[v],S=(y>>>4|y<<28)^e[v+1];p=g,g=y,y=p^(o[E>>>24&63]|l[E>>>16&63]|u[E>>>8&63]|d[63&E]|s[S>>>24&63]|a[S>>>16&63]|c[S>>>8&63]|h[63&S])}p=g,g=y,y=p}p=((g=g>>>1|g<<31)>>>1^(y=y>>>1|y<<31))&1431655765,y^=p,g^=p<<1,p=(y>>>8^g)&16711935,g^=p,y^=p<<8,p=(y>>>2^g)&858993459,g^=p,y^=p<<2,p=(g>>>16^y)&65535,y^=p,g^=p<<16,p=(g>>>4^y)&252645135,y^=p,g^=p<<4,r[0]=g,r[1]=y}function f(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},2595:function(e){e.exports={options:{usePureJavaScript:!1}}},6888:function(e,t,r){var n=r(2595);r(2528),r(2366),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,s={};return s.start=function(s,o){if(null!==s){if("string"==typeof s){if((s=s.toLowerCase())in n.md.algorithms)t=n.md.algorithms[s].create();else throw Error('Unknown hash algorithm "'+s+'"')}else t=s}if(null===o)o=e;else{if("string"==typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var l=0;l<a.length;++l)o.putByte(a[l])}var c=o.length();c>t.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),c=o.length();for(var l=0;l<c;++l){var a=o.at(l);r.putByte(54^a),i.putByte(92^a)}if(c<t.blockLength)for(var a=t.blockLength-c,l=0;l<a;++l)r.putByte(54),i.putByte(92);e=o,r=r.bytes(),i=i.bytes()}t.start(),t.update(r)},s.update=function(e){t.update(e)},s.getMac=function(){var e=t.digest().bytes();return t.start(),t.update(i),t.update(e),t.digest()},s.digest=s.getMac,s}},4196:function(e,t,r){var n,i,s,o=r(2595);function a(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function l(){return new a(null)}function c(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var l=16383&this.data[e],c=this.data[e++]>>14,u=a*l+c*o;i=((l=o*l+((16383&u)<<14)+r.data[n]+i)>>28)+(u>>14)+a*c,r.data[n++]=268435455&l}return i}e.exports=o.jsbn=o.jsbn||{},o.jsbn.BigInteger=a,"undefined"==typeof navigator?(a.prototype.am=c,n=28):"Microsoft Internet Explorer"==navigator.appName?(a.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var l=32767&this.data[e],c=this.data[e++]>>15,u=a*l+c*o;i=((l=o*l+((32767&u)<<15)+r.data[n]+(1073741823&i))>>>30)+(u>>>15)+a*c+(i>>>30),r.data[n++]=1073741823&l}return i},n=30):"Netscape"!=navigator.appName?(a.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this.data[e++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=67108863&o}return i},n=26):(a.prototype.am=c,n=28),a.prototype.DB=n,a.prototype.DM=(1<<n)-1,a.prototype.DV=1<<n,a.prototype.FV=4503599627370496,a.prototype.F1=52-n,a.prototype.F2=2*n-52;var u=[];for(s=0,i=48;s<=9;++s)u[i++]=s;for(s=10,i=97;s<36;++s)u[i++]=s;for(s=10,i=65;s<36;++s)u[i++]=s;function h(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function d(e,t){var r=u[e.charCodeAt(t)];return null==r?-1:r}function p(e){var t=l();return t.fromInt(e),t}function f(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function m(e,t){return e&t}function b(e,t){return e|t}function w(e,t){return e^t}function v(e,t){return e&~t}function E(){}function S(e){return e}function A(e){this.r2=l(),this.q3=l(),a.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=l();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(a.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=l();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e.data[t],n=r*this.mpl+((r*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},a.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},a.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},a.prototype.fromString=function(e,t){if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else if(4==t)r=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var r,n=e.length,i=!1,s=0;--n>=0;){var o=8==r?255&e[n]:d(e,n);if(o<0){"-"==e.charAt(n)&&(i=!0);continue}i=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this.data[this.t++]=o>>this.DB-s):this.data[this.t-1]|=o<<s,(s+=r)>=this.DB&&(s-=this.DB)}8==r&&(128&e[0])!=0&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&a.ZERO.subTo(this,this)},a.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t},a.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},a.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t.data[r-e]=this.data[r];t.t=Math.max(this.t-e,0),t.s=this.s},a.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t.data[r+o+1]=this.data[r]>>i|a,a=(this.data[r]&s)<<n;for(r=o-1;r>=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},a.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t){t.t=0;return}var n=e%this.DB,i=this.DB-n,s=(1<<n)-1;t.data[0]=this.data[r]>>n;for(var o=r+1;o<this.t;++o)t.data[o-r-1]|=(this.data[o]&s)<<i,t.data[o-r]=this.data[o]>>n;n>0&&(t.data[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()},a.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this.data[r]-e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},a.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i<n.t;++i)t.data[i+r.t]=r.am(0,n.data[i],t,i,0,r.t);t.s=0,t.clamp(),this.s!=e.s&&a.ZERO.subTo(t,t)},a.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e.data[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t.data[r],e,2*r,0,1);(e.data[r+t.t]+=t.am(r+1,2*t.data[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},a.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){null!=t&&t.fromInt(0),null!=r&&this.copyTo(r);return}null==r&&(r=l());var s=l(),o=this.s,c=e.s,u=this.DB-f(n.data[n.t-1]);u>0?(n.lShiftTo(u,s),i.lShiftTo(u,r)):(n.copyTo(s),i.copyTo(r));var h=s.t,d=s.data[h-1];if(0!=d){var p=d*(1<<this.F1)+(h>1?s.data[h-2]>>this.F2:0),g=this.FV/p,y=(1<<this.F1)/p,m=1<<this.F2,b=r.t,w=b-h,v=null==t?l():t;for(s.dlShiftTo(w,v),r.compareTo(v)>=0&&(r.data[r.t++]=1,r.subTo(v,r)),a.ONE.dlShiftTo(h,v),v.subTo(s,s);s.t<h;)s.data[s.t++]=0;for(;--w>=0;){var E=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+m)*y);if((r.data[b]+=s.am(0,E,r,w,0,h))<E)for(s.dlShiftTo(w,v),r.subTo(v,r);r.data[b]<--E;)r.subTo(v,r)}null!=t&&(r.drShiftTo(h,t),o!=c&&a.ZERO.subTo(t,t)),r.t=h,r.clamp(),u>0&&r.rShiftTo(u,r),o<0&&a.ZERO.subTo(r,r)}}},a.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if((1&e)==0)return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},a.prototype.isEven=function(){return(this.t>0?1&this.data[0]:this.s)==0},a.prototype.exp=function(e,t){if(e>4294967295||e<1)return a.ONE;var r=l(),n=l(),i=t.convert(this),s=f(e)-1;for(i.copyTo(r);--s>=0;)if(t.sqrTo(r,n),(e&1<<s)>0)t.mulTo(n,i,r);else{var o=r;r=n,n=o}return t.revert(r)},a.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var t,r,n=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this.data[o]>>a)>0&&(i=!0,s=h(r));o>=0;)a<t?r=(this.data[o]&(1<<a)-1)<<t-a|this.data[--o]>>(a+=this.DB-t):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=h(r));return i?s:"0"},a.prototype.negate=function(){var e=l();return a.ZERO.subTo(this,e),e},a.prototype.abs=function(){return this.s<0?this.negate():this},a.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},a.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+f(this.data[this.t-1]^this.s&this.DM)},a.prototype.mod=function(e){var t=l();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(a.ZERO)>0&&e.subTo(t,t),t},a.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},a.ZERO=p(0),a.ONE=p(1),E.prototype.convert=S,E.prototype.revert=S,E.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},E.prototype.sqrTo=function(e,t){e.squareTo(t)},A.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(0>e.compareTo(this.m))return e;var t=l();return e.copyTo(t),this.reduce(t),t},A.prototype.revert=function(e){return e},A.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);0>e.compareTo(this.r2);)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],T=67108864/I[I.length-1];a.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},a.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=p(r),i=l(),s=l(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(e).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(e)+o},a.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,s=0,o=0,l=0;l<e.length;++l){var c=d(e,l);if(c<0){"-"==e.charAt(l)&&0==this.signum()&&(i=!0);continue}o=t*o+c,++s>=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0)}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),i&&a.ZERO.subTo(this,this)},a.prototype.fromNumber=function(e,t,r){if("number"==typeof t){if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(a.ONE.shiftLeft(e-1),b,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(a.ONE.shiftLeft(e-1),this)}else{var n=[],i=7&e;n.length=(e>>3)+1,t.nextBytes(n),i>0?n[0]&=(1<<i)-1:n[0]=0,this.fromString(n,256)}},a.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r.data[n]=t(this.data[n],e.data[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r.data[n]=t(this.data[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r.data[n]=t(i,e.data[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},a.prototype.changeBit=function(e,t){var r=a.ONE.shiftLeft(e);return this.bitwiseTo(r,t,r),r},a.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this.data[r]+e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e.data[r],t.data[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},a.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},a.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},a.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i<n;++i)r.data[i+this.t]=this.am(0,e.data[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e.data[i],r,i,0,t-i);r.clamp()},a.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r.data[this.t+n-t]=this.am(t-n,e.data[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},a.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0){if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e}return r},a.prototype.millerRabin=function(e){var t,r=this.subtract(a.ONE),n=r.getLowestSetBit();if(n<=0)return!1;for(var i=r.shiftRight(n),s={nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}},o=0;o<e;++o){do t=new a(this.bitLength(),s);while(0>=t.compareTo(a.ONE)||t.compareTo(r)>=0);var l=t.modPow(i,this);if(0!=l.compareTo(a.ONE)&&0!=l.compareTo(r)){for(var c=1;c++<n&&0!=l.compareTo(r);)if(0==(l=l.modPowInt(2,this)).compareTo(a.ONE))return!1;if(0!=l.compareTo(r))return!1}}return!0},a.prototype.clone=function(){var e=l();return this.copyTo(e),e},a.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return -1}else if(1==this.t)return this.data[0];else if(0==this.t)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]},a.prototype.byteValue=function(){return 0==this.t?this.s:this.data[0]<<24>>24},a.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},a.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},a.prototype.toByteArray=function(){var e=this.t,t=[];t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n<this.DB&&(r=this.data[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?r=(this.data[e]&(1<<n)-1)<<8-n|this.data[--e]>>(n+=this.DB-8):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),(128&r)!=0&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},a.prototype.equals=function(e){return 0==this.compareTo(e)},a.prototype.min=function(e){return 0>this.compareTo(e)?this:e},a.prototype.max=function(e){return this.compareTo(e)>0?this:e},a.prototype.and=function(e){var t=l();return this.bitwiseTo(e,m,t),t},a.prototype.or=function(e){var t=l();return this.bitwiseTo(e,b,t),t},a.prototype.xor=function(e){var t=l();return this.bitwiseTo(e,w,t),t},a.prototype.andNot=function(e){var t=l();return this.bitwiseTo(e,v,t),t},a.prototype.not=function(){for(var e=l(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e},a.prototype.shiftLeft=function(e){var t=l();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},a.prototype.shiftRight=function(e){var t=l();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},a.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this.data[e])return e*this.DB+function(e){if(0==e)return -1;var t=0;return(65535&e)==0&&(e>>=16,t+=16),(255&e)==0&&(e>>=8,t+=8),(15&e)==0&&(e>>=4,t+=4),(3&e)==0&&(e>>=2,t+=2),(1&e)==0&&++t,t}(this.data[e]);return this.s<0?this.t*this.DB:-1},a.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=function(e){for(var t=0;0!=e;)e&=e-1,++t;return t}(this.data[r]^t);return e},a.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:(this.data[t]&1<<e%this.DB)!=0},a.prototype.setBit=function(e){return this.changeBit(e,b)},a.prototype.clearBit=function(e){return this.changeBit(e,v)},a.prototype.flipBit=function(e){return this.changeBit(e,w)},a.prototype.add=function(e){var t=l();return this.addTo(e,t),t},a.prototype.subtract=function(e){var t=l();return this.subTo(e,t),t},a.prototype.multiply=function(e){var t=l();return this.multiplyTo(e,t),t},a.prototype.divide=function(e){var t=l();return this.divRemTo(e,t,null),t},a.prototype.remainder=function(e){var t=l();return this.divRemTo(e,null,t),t},a.prototype.divideAndRemainder=function(e){var t=l(),r=l();return this.divRemTo(e,t,r),[t,r]},a.prototype.modPow=function(e,t){var r,n,i=e.bitLength(),s=p(1);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new g(t):t.isEven()?new A(t):new y(t);var o=[],a=3,c=r-1,u=(1<<r)-1;if(o[1]=n.convert(this),r>1){var h=l();for(n.sqrTo(o[1],h);a<=u;)o[a]=l(),n.mulTo(h,o[a-2],o[a]),a+=2}var d,m,b=e.t-1,w=!0,v=l();for(i=f(e.data[b])-1;b>=0;){for(i>=c?d=e.data[b]>>i-c&u:(d=(e.data[b]&(1<<i+1)-1)<<c-i,b>0&&(d|=e.data[b-1]>>this.DB+i-c)),a=r;(1&d)==0;)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--b),w)o[d].copyTo(s),w=!1;else{for(;a>1;)n.sqrTo(s,v),n.sqrTo(v,s),a-=2;a>0?n.sqrTo(s,v):(m=s,s=v,v=m),n.mulTo(v,o[d],s)}for(;b>=0&&(e.data[b]&1<<i)==0;)n.sqrTo(s,v),m=s,s=v,v=m,--i<0&&(i=this.DB-1,--b)}return n.revert(s)},a.prototype.modInverse=function(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return a.ZERO;for(var r=e.clone(),n=this.clone(),i=p(1),s=p(0),o=p(0),l=p(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&s.isEven()||(i.addTo(this,i),s.subTo(e,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(e,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),t?(o.isEven()&&l.isEven()||(o.addTo(this,o),l.subTo(e,l)),o.rShiftTo(1,o)):l.isEven()||l.subTo(e,l),l.rShiftTo(1,l);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(o,i),s.subTo(l,s)):(n.subTo(r,n),t&&o.subTo(i,o),l.subTo(s,l))}return 0!=n.compareTo(a.ONE)?a.ZERO:l.compareTo(e)>=0?l.subtract(e):0>l.signum()&&(l.addTo(e,l),0>l.signum())?l.add(e):l},a.prototype.pow=function(e){return this.exp(e,new E)},a.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(0>t.compareTo(r)){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},a.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=I[I.length-1]){for(t=0;t<I.length;++t)if(r.data[0]==I[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<I.length;){for(var n=I[t],i=t+1;i<I.length&&n<T;)n*=I[i++];for(n=r.modInt(n);t<i;)if(n%I[t++]==0)return!1}return r.millerRabin(e)}},2528:function(e,t,r){var n=r(2595);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},552:function(e,t,r){var n=r(2595);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function s(e,t){i[e]=t,i[t]=e}s("1.2.840.113549.1.1.1","rsaEncryption"),s("1.2.840.113549.1.1.4","md5WithRSAEncryption"),s("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),s("1.2.840.113549.1.1.7","RSAES-OAEP"),s("1.2.840.113549.1.1.8","mgf1"),s("1.2.840.113549.1.1.9","pSpecified"),s("1.2.840.113549.1.1.10","RSASSA-PSS"),s("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),s("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),s("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),s("1.3.101.112","EdDSA25519"),s("1.2.840.10040.4.3","dsa-with-sha1"),s("1.3.14.3.2.7","desCBC"),s("1.3.14.3.2.26","sha1"),s("1.3.14.3.2.29","sha1WithRSASignature"),s("2.16.840.1.101.3.4.2.1","sha256"),s("2.16.840.1.101.3.4.2.2","sha384"),s("2.16.840.1.101.3.4.2.3","sha512"),s("2.16.840.1.101.3.4.2.4","sha224"),s("2.16.840.1.101.3.4.2.5","sha512-224"),s("2.16.840.1.101.3.4.2.6","sha512-256"),s("1.2.840.113549.2.2","md2"),s("1.2.840.113549.2.5","md5"),s("1.2.840.113549.1.7.1","data"),s("1.2.840.113549.1.7.2","signedData"),s("1.2.840.113549.1.7.3","envelopedData"),s("1.2.840.113549.1.7.4","signedAndEnvelopedData"),s("1.2.840.113549.1.7.5","digestedData"),s("1.2.840.113549.1.7.6","encryptedData"),s("1.2.840.113549.1.9.1","emailAddress"),s("1.2.840.113549.1.9.2","unstructuredName"),s("1.2.840.113549.1.9.3","contentType"),s("1.2.840.113549.1.9.4","messageDigest"),s("1.2.840.113549.1.9.5","signingTime"),s("1.2.840.113549.1.9.6","counterSignature"),s("1.2.840.113549.1.9.7","challengePassword"),s("1.2.840.113549.1.9.8","unstructuredAddress"),s("1.2.840.113549.1.9.14","extensionRequest"),s("1.2.840.113549.1.9.20","friendlyName"),s("1.2.840.113549.1.9.21","localKeyId"),s("1.2.840.113549.1.9.22.1","x509Certificate"),s("1.2.840.113549.1.12.10.1.1","keyBag"),s("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),s("1.2.840.113549.1.12.10.1.3","certBag"),s("1.2.840.113549.1.12.10.1.4","crlBag"),s("1.2.840.113549.1.12.10.1.5","secretBag"),s("1.2.840.113549.1.12.10.1.6","safeContentsBag"),s("1.2.840.113549.1.5.13","pkcs5PBES2"),s("1.2.840.113549.1.5.12","pkcs5PBKDF2"),s("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),s("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),s("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),s("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),s("1.2.840.113549.2.7","hmacWithSHA1"),s("1.2.840.113549.2.8","hmacWithSHA224"),s("1.2.840.113549.2.9","hmacWithSHA256"),s("1.2.840.113549.2.10","hmacWithSHA384"),s("1.2.840.113549.2.11","hmacWithSHA512"),s("1.2.840.113549.3.7","des-EDE3-CBC"),s("2.16.840.1.101.3.4.1.2","aes128-CBC"),s("2.16.840.1.101.3.4.1.22","aes192-CBC"),s("2.16.840.1.101.3.4.1.42","aes256-CBC"),s("2.5.4.3","commonName"),s("2.5.4.4","surname"),s("2.5.4.5","serialNumber"),s("2.5.4.6","countryName"),s("2.5.4.7","localityName"),s("2.5.4.8","stateOrProvinceName"),s("2.5.4.9","streetAddress"),s("2.5.4.10","organizationName"),s("2.5.4.11","organizationalUnitName"),s("2.5.4.12","title"),s("2.5.4.13","description"),s("2.5.4.15","businessCategory"),s("2.5.4.17","postalCode"),s("2.5.4.42","givenName"),s("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),s("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),s("2.16.840.1.113730.1.1","nsCertType"),s("2.16.840.1.113730.1.13","nsComment"),i["2.5.29.1"]="authorityKeyIdentifier",i["2.5.29.2"]="keyAttributes",i["2.5.29.3"]="certificatePolicies",i["2.5.29.4"]="keyUsageRestriction",i["2.5.29.5"]="policyMapping",i["2.5.29.6"]="subtreesConstraint",i["2.5.29.7"]="subjectAltName",i["2.5.29.8"]="issuerAltName",i["2.5.29.9"]="subjectDirectoryAttributes",i["2.5.29.10"]="basicConstraints",i["2.5.29.11"]="nameConstraints",i["2.5.29.12"]="policyConstraints",i["2.5.29.13"]="basicConstraints",s("2.5.29.14","subjectKeyIdentifier"),s("2.5.29.15","keyUsage"),i["2.5.29.16"]="privateKeyUsagePeriod",s("2.5.29.17","subjectAltName"),s("2.5.29.18","issuerAltName"),s("2.5.29.19","basicConstraints"),i["2.5.29.20"]="cRLNumber",i["2.5.29.21"]="cRLReason",i["2.5.29.22"]="expirationDate",i["2.5.29.23"]="instructionCode",i["2.5.29.24"]="invalidityDate",i["2.5.29.25"]="cRLDistributionPoints",i["2.5.29.26"]="issuingDistributionPoint",i["2.5.29.27"]="deltaCRLIndicator",i["2.5.29.28"]="issuingDistributionPoint",i["2.5.29.29"]="certificateIssuer",i["2.5.29.30"]="nameConstraints",s("2.5.29.31","cRLDistributionPoints"),s("2.5.29.32","certificatePolicies"),i["2.5.29.33"]="policyMappings",i["2.5.29.34"]="policyConstraints",s("2.5.29.35","authorityKeyIdentifier"),i["2.5.29.36"]="policyConstraints",s("2.5.29.37","extKeyUsage"),i["2.5.29.46"]="freshestCRL",i["2.5.29.54"]="inhibitAnyPolicy",s("1.3.6.1.4.1.11129.2.4.2","timestampList"),s("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),s("1.3.6.1.5.5.7.3.1","serverAuth"),s("1.3.6.1.5.5.7.3.2","clientAuth"),s("1.3.6.1.5.5.7.3.3","codeSigning"),s("1.3.6.1.5.5.7.3.4","emailProtection"),s("1.3.6.1.5.5.7.3.8","timeStamping")},6204:function(e,t,r){var n=r(2595);if(r(1250),r(9642),r(2906),r(2528),r(552),r(1953),r(8507),r(9249),r(3574),r(411),r(2366),void 0===i)var i=n.jsbn.BigInteger;var s=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,l={name:"EncryptedPrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},c={name:"PBES2Algorithms",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=o.oids[s.derToOid(e)])){var r=Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return p(t)}function p(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw Error("Unknown hash algorithm: "+e);return t[e].create()}o.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i=n.random.getBytesSync(r.saltSize),l=r.count,c=s.integerToDer(l);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){switch(r.algorithm){case"aes128":d=16,y=16,m=a["aes128-CBC"],b=n.aes.createEncryptionCipher;break;case"aes192":d=24,y=16,m=a["aes192-CBC"],b=n.aes.createEncryptionCipher;break;case"aes256":d=32,y=16,m=a["aes256-CBC"],b=n.aes.createEncryptionCipher;break;case"des":d=8,y=8,m=a.desCBC,b=n.des.createEncryptionCipher;break;default:var u,h,d,f,g,y,m,b,w=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw w.algorithm=r.algorithm,w}var v="hmacWith"+r.prfAlgorithm.toUpperCase(),E=p(v),S=n.pkcs5.pbkdf2(t,i,l,d,E),A=n.random.getBytesSync(y),I=b(S);I.start(A),I.update(s.toDer(e)),I.finish(),g=I.output.getBytes();var T=(u=d,h=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,i),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,c.getBytes())]),"hmacWithSHA1"!==v&&h.value.push(s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,n.util.hexToBytes(u.toString(16))),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(o.oids[v]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")])),h);f=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBES2).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBKDF2).getBytes()),T]),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(m).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,A)])])])}else if("3des"===r.algorithm){d=24;var _=new n.util.ByteBuffer(i),S=o.pbe.generatePkcs12Key(t,_,1,l,d),A=o.pbe.generatePkcs12Key(t,_,2,l,d),I=n.des.createEncryptionCipher(S);I.start(A),I.update(s.toDer(e)),I.finish(),g=I.output.getBytes(),f=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,i),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,c.getBytes())])])}else{var w=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw w.algorithm=r.algorithm,w}return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[f,s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,g)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!s.validate(e,l,i,a)){var c=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw c.errors=a,c}var u=s.derToOid(i.encryptionOid),h=o.pbe.getCipher(u,i.encryptionParams,t),d=n.util.createBuffer(i.encryptedData);return h.update(d),h.finish()&&(r=s.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:s.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},o.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return s.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i,a,l,c,u=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return u=o.encryptPrivateKeyInfo(u,t,r),o.encryptedPrivateKeyToPem(u)}switch(r.algorithm){case"aes128":i="AES-128-CBC",l=16,a=n.random.getBytesSync(16),c=n.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",l=24,a=n.random.getBytesSync(16),c=n.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",l=32,a=n.random.getBytesSync(16),c=n.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",l=24,a=n.random.getBytesSync(8),c=n.des.createEncryptionCipher;break;case"des":i="DES-CBC",l=8,a=n.random.getBytesSync(8),c=n.des.createEncryptionCipher;break;default:var h=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=c(n.pbe.opensslDeriveBytes(t,a.substr(0,8),l));d.start(a),d.update(s.toDer(o.privateKeyToAsn1(e))),d.finish();var p={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:n.util.bytesToHex(a).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(p)},o.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type){var a=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw a.headerType=a,a}if(i.procType&&"ENCRYPTED"===i.procType.type){switch(i.dekInfo.algorithm){case"DES-CBC":l=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":l=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":l=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":l=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":l=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":l=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":l=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":l=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l,c,a=Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".');throw a.algorithm=i.dekInfo.algorithm,a}var u=n.util.hexToBytes(i.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),l));if(h.start(u),h.update(n.util.createBuffer(i.body)),!h.finish())return r;r=h.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?o.decryptPrivateKeyInfo(s.fromDer(r),t):s.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,i,s,o){if(null==o){if(!("sha1"in n.md))throw Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var a,l,c=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!=e){for(l=0;l<e.length;l++)d.putInt16(e.charCodeAt(l));d.putInt16(0)}var p=d.length(),f=t.length(),g=new n.util.ByteBuffer;g.fillWithByte(r,u);var y=u*Math.ceil(f/u),m=new n.util.ByteBuffer;for(l=0;l<y;l++)m.putByte(t.at(l%f));var b=u*Math.ceil(p/u),w=new n.util.ByteBuffer;for(l=0;l<b;l++)w.putByte(d.at(l%p));var v=m;v.putBuffer(w);for(var E=Math.ceil(s/c),S=1;S<=E;S++){var A=new n.util.ByteBuffer;A.putBytes(g.bytes()),A.putBytes(v.bytes());for(var I=0;I<i;I++)o.start(),o.update(A.getBytes()),A=o.digest();var T=new n.util.ByteBuffer;for(l=0;l<u;l++)T.putByte(A.at(l%c));var _=Math.ceil(f/u)+Math.ceil(p/u),R=new n.util.ByteBuffer;for(a=0;a<_;a++){var C=new n.util.ByteBuffer(v.getBytes(u)),k=511;for(l=T.length()-1;l>=0;l--)k>>=8,k+=T.at(l)+C.at(l),C.setAt(l,255&k);R.putBuffer(C)}v=R,h.putBuffer(A)}return h.truncate(h.length()-s),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var i,a,l={},u=[];if(!s.validate(t,c,l,u)){var h=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw h.errors=u,h}if((e=s.derToOid(l.kdfOid))!==o.oids.pkcs5PBKDF2){var h=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw h.oid=e,h.supportedOids=["pkcs5PBKDF2"],h}if((e=s.derToOid(l.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC){var h=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw h.oid=e,h.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],h}var p=l.kdfSalt,f=n.util.createBuffer(l.kdfIterationCount);switch(f=f.getInt(f.length()<<3),o.oids[e]){case"aes128-CBC":i=16,a=n.aes.createDecryptionCipher;break;case"aes192-CBC":i=24,a=n.aes.createDecryptionCipher;break;case"aes256-CBC":i=32,a=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":i=24,a=n.des.createDecryptionCipher;break;case"desCBC":i=8,a=n.des.createDecryptionCipher}var g=d(l.prfOid),y=n.pkcs5.pbkdf2(r,p,f,i,g),m=l.encIv,b=a(y);return b.start(m),b},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var i,a,l,c={},h=[];if(!s.validate(t,u,c,h)){var p=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw p.errors=h,p}var f=n.util.createBuffer(c.salt),g=n.util.createBuffer(c.iterations);switch(g=g.getInt(g.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:i=24,a=8,l=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:i=5,a=8,l=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var p=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw p.oid=e,p}var y=d(c.prfOid),m=o.pbe.generatePkcs12Key(r,f,1,g,i,y);return y.start(),l(m,o.pbe.generatePkcs12Key(r,f,2,g,a,y))},o.pbe.opensslDeriveBytes=function(e,t,r,i){if(null==i){if(!("md5"in n.md))throw Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var s=[h(i,e+t)],o=16,a=1;o<r;++a,o+=16)s.push(h(i,s[a-1]+e+t));return s.join("").substr(0,r)}},1953:function(e,t,r){var n,i=r(2678).Buffer,s=r(2595);r(6888),r(2528),r(2366);var o=s.pkcs5=s.pkcs5||{};s.util.isNodejs&&!s.options.usePureJavaScript&&(n=r(5819)),e.exports=s.pbkdf2=o.pbkdf2=function(e,t,r,o,a,l){if("function"==typeof a&&(l=a,a=null),s.util.isNodejs&&!s.options.usePureJavaScript&&n.pbkdf2&&(null===a||"object"!=typeof a)&&(n.pbkdf2Sync.length>4||!a||"sha1"===a))return("string"!=typeof a&&(a="sha1"),e=i.from(e,"binary"),t=i.from(t,"binary"),l)?4===n.pbkdf2Sync.length?n.pbkdf2(e,t,r,o,function(e,t){if(e)return l(e);l(null,t.toString("binary"))}):n.pbkdf2(e,t,r,o,a,function(e,t){if(e)return l(e);l(null,t.toString("binary"))}):4===n.pbkdf2Sync.length?n.pbkdf2Sync(e,t,r,o).toString("binary"):n.pbkdf2Sync(e,t,r,o,a).toString("binary");if(null==a&&(a="sha1"),"string"==typeof a){if(!(a in s.md.algorithms))throw Error("Unknown hash algorithm: "+a);a=s.md[a].create()}var c=a.digestLength;if(o>4294967295*c){var u=Error("Derived key is too long.");if(l)return l(u);throw u}var h=Math.ceil(o/c),d=o-(h-1)*c,p=s.hmac.create();p.start(a,e);var f="";if(!l){for(var g=1;g<=h;++g){p.start(null,null),p.update(t),p.update(s.util.int32ToBytes(g)),m=w=p.digest().getBytes();for(var y=2;y<=r;++y)p.start(null,null),p.update(w),b=p.digest().getBytes(),m=s.util.xorBytes(m,b,c),w=b;f+=g<h?m:m.substr(0,d)}return f}var m,b,w,y,g=1;(function e(){if(g>h)return l(null,f);p.start(null,null),p.update(t),p.update(s.util.int32ToBytes(g)),m=w=p.digest().getBytes(),y=2,function t(){if(y<=r)return p.start(null,null),p.update(w),b=p.digest().getBytes(),m=s.util.xorBytes(m,b,c),w=b,++y,s.util.setImmediate(t);f+=g<h?m:m.substr(0,d),++g,e()}()})()}},8507:function(e,t,r){var n=r(2595);r(2366);var i=e.exports=n.pem=n.pem||{};function s(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i<e.values.length;++i)r.push(e.values[i].replace(/^(\S+\r\n)/,n));t+=r.join(",")+"\r\n";for(var s=0,o=-1,i=0;i<t.length;++i,++s)if(s>65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),s=i-o-1,o=-1,++i}else(" "===t[i]||" "===t[i]||","===t[i])&&(o=i);return t}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=s(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=s(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=s(r)),e.headers)for(var o=0;o<e.headers.length;++o)i+=s(e.headers[o]);return e.procType&&(i+="\r\n"),i+=n.util.encode64(e.body,t.maxline||64)+"\r\n-----END "+e.type+"-----\r\n"},i.decode=function(e){for(var t,r=[],i=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,s=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,o=/\r?\n/;t=i.exec(e);){var a=t[1];"NEW CERTIFICATE REQUEST"===a&&(a="CERTIFICATE REQUEST");var l={type:a,procType:null,contentDomain:null,dekInfo:null,headers:[],body:n.util.decode64(t[3])};if(r.push(l),t[2]){for(var c=t[2].split(o),u=0;t&&u<c.length;){for(var h=c[u].replace(/\s+$/,""),d=u+1;d<c.length;++d){var p=c[d];if(!/\s/.test(p[0]))break;h+=p,u=d}if(t=h.match(s)){for(var f={name:t[1],values:[]},g=t[2].split(","),y=0;y<g.length;++y)f.values.push(g[y].replace(/^\s+/,""));if(l.procType){if(l.contentDomain||"Content-Domain"!==f.name){if(l.dekInfo||"DEK-Info"!==f.name)l.headers.push(f);else{if(0===f.values.length)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');l.dekInfo={algorithm:g[0],parameters:g[1]||null}}}else l.contentDomain=g[0]||""}else{if("Proc-Type"!==f.name)throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(2!==f.values.length)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');l.procType={version:g[0],type:g[1]}}}++u}if("ENCRYPTED"===l.procType&&!l.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(0===r.length)throw Error("Invalid PEM formatted message.");return r}},4210:function(e,t,r){var n=r(2595);r(2366),r(9249),r(8295);var i=e.exports=n.pkcs1=n.pkcs1||{};function s(e,t,r){r||(r=n.md.sha1.create());for(var i="",s=Math.ceil(t/r.digestLength),o=0;o<s;++o){var a=String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){"string"==typeof r?(i=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(l=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),l||(l=a);var i,o,a,l,c=Math.ceil(e.n.bitLength()/8),u=c-2*a.digestLength-2;if(t.length>u){var h=Error("RSAES-OAEP input message length is too long.");throw h.length=t.length,h.maxLength=u,h}i||(i=""),a.update(i,"raw");for(var d=a.digest(),p="",f=u-t.length,g=0;g<f;g++)p+="\x00";var y=d.getBytes()+p+"\x01"+t;if(o){if(o.length!==a.digestLength){var h=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw h.seedLength=o.length,h.digestLength=a.digestLength,h}}else o=n.random.getBytes(a.digestLength);var m=s(o,c-a.digestLength-1,l),b=n.util.xorBytes(y,m,y.length),w=s(b,a.digestLength,l);return"\x00"+n.util.xorBytes(o,w,o.length)+b},i.decode_rsa_oaep=function(e,t,r){"string"==typeof r?(i=r,o=arguments[3]||void 0):r&&(i=r.label||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(a=r.mgf1.md));var i,o,a,l=Math.ceil(e.n.bitLength()/8);if(t.length!==l){var c=Error("RSAES-OAEP encoded message length is invalid.");throw c.length=t.length,c.expectedLength=l,c}if(void 0===o?o=n.md.sha1.create():o.start(),a||(a=o),l<2*o.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");i||(i=""),o.update(i,"raw");for(var u=o.digest().getBytes(),h=t.charAt(0),d=t.substring(1,o.digestLength+1),p=t.substring(1+o.digestLength),f=s(p,o.digestLength,a),g=s(n.util.xorBytes(d,f,d.length),l-o.digestLength-1,a),y=n.util.xorBytes(p,g,p.length),m=y.substring(0,o.digestLength),c="\x00"!==h,b=0;b<o.digestLength;++b)c|=u.charAt(b)!==m.charAt(b);for(var w=1,v=o.digestLength,E=o.digestLength;E<y.length;E++){var S=y.charCodeAt(E),A=1&S^1;c|=S&(w?65534:0),w&=A,v+=w}if(c||1!==y.charCodeAt(v))throw Error("Invalid RSAES-OAEP padding.");return y.substring(v+1)}},7236:function(e,t,r){var n=r(2595);r(2366),r(4196),r(9249),function(){if(n.prime){e.exports=n.prime;return}var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],s=new r(null);s.fromInt(30);var o=function(e,t){return e|t};function a(e,t,r,s){var o,a=l(e,t),c=(o=a.bitLength())<=100?27:o<=150?18:o<=200?15:o<=250?12:o<=300?9:o<=350?8:o<=400?7:o<=500?6:o<=600?5:o<=800?4:o<=1250?3:2;"millerRabinTests"in r&&(c=r.millerRabinTests);var u=10;"maxBlockTime"in r&&(u=r.maxBlockTime),function e(t,r,s,o,a,c,u){var h=+new Date;do{if(t.bitLength()>r&&(t=l(r,s)),t.isProbablePrime(a))return u(null,t);t.dAddOffset(i[o++%8],0)}while(c<0||+new Date-h<c);n.util.setImmediate(function(){e(t,r,s,o,a,c,u)})}(a,e,t,0,c,u,s)}function l(e,t){var n=new r(e,t),i=e-1;return n.testBit(i)||n.bitwiseTo(r.ONE.shiftLeft(i),o,n),n.dAddOffset(31-n.mod(s).byteValue(),0),n}t.generateProbablePrime=function(e,t,i){"function"==typeof t&&(i=t,t={});var s,o,c,u=(t=t||{}).algorithm||"PRIMEINC";"string"==typeof u&&(u={name:u}),u.options=u.options||{};var h=t.prng||n.random;if("PRIMEINC"===u.name)return s={nextBytes:function(e){for(var t=h.getBytesSync(e.length),r=0;r<e.length;++r)e[r]=t.charCodeAt(r)}},o=u.options,c=i,"workers"in o?function(e,t,i,s){if("undefined"==typeof Worker)return a(e,t,i,s);var o=l(e,t),c=i.workers,u=i.workLoad||100,h=30*u/8,d=i.workerScript||"forge/prime.worker.js";if(-1===c)return n.util.estimateCores(function(e,t){e&&(t=2),c=t-1,p()});function p(){c=Math.max(1,c);for(var n=[],i=0;i<c;++i)n[i]=new Worker(d);for(var a=c,i=0;i<c;++i)n[i].addEventListener("message",f);var p=!1;function f(i){if(!p){--a;var c=i.data;if(c.found){for(var d=0;d<n.length;++d)n[d].terminate();return p=!0,s(null,new r(c.prime,16))}o.bitLength()>e&&(o=l(e,t));var f=o.toString(16);i.target.postMessage({hex:f,workLoad:u}),o.dAddOffset(h,0)}}}p()}(e,s,o,c):a(e,s,o,c);throw Error("Invalid prime generation algorithm: "+u.name)}}()},2927:function(e,t,r){var n=r(4112),i=r(2595);r(2366);var s=null;!i.util.isNodejs||i.options.usePureJavaScript||n.versions["node-webkit"]||(s=r(5819)),(e.exports=i.prng=i.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,n=Array(32),o=0;o<32;++o)n[o]=r.create();function a(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r==0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function l(e){var t=null,r=i.util.globalScope,n=r.crypto||r.msCrypto;n&&n.getRandomValues&&(t=function(e){return n.getRandomValues(e)});var s=i.util.createBuffer();if(t)for(;s.length()<e;){var o=Math.max(1,Math.min(e-s.length(),65536)/4),a=new Uint32Array(Math.floor(o));try{t(a);for(var l=0;l<a.length;++l)s.putInt32(a[l])}catch(e){if(!("undefined"!=typeof QuotaExceededError&&e instanceof QuotaExceededError))throw e}}if(s.length()<e)for(var c,u,h,d=Math.floor(65536*Math.random());s.length()<e;){d=4294967295&(u=(2147483647&(u=16807*(65535&d)+(((32767&(c=16807*(d>>16)))<<16)+(c>>15))))+(u>>31));for(var l=0;l<3;++l)h=d>>>(l<<3)^Math.floor(256*Math.random()),s.putByte(255&h)}return s.getBytes(e)}return t.pools=n,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var n=t.plugin.cipher,s=t.plugin.increment,o=t.plugin.formatKey,l=t.plugin.formatSeed,c=i.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(c.length()>=e)return r(null,c.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return i.util.nextTick(function(){(function(e){if(t.pools[0].messageLength>=32)return a(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,function(r,n){if(r)return e(r);t.collect(n),a(),e()})})(u)});var d=n(t.key,t.seed);t.generated+=d.length,c.putBytes(d),t.key=o(n(t.key,s(t.seed))),t.seed=l(n(t.key,t.seed)),i.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,n=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var l=i.util.createBuffer();l.length()<e;){t.generated>1048575&&(t.key=null),null===t.key&&function(){if(t.pools[0].messageLength>=32)return a();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),a()}();var c=r(t.key,t.seed);t.generated+=c.length,l.putBytes(c),t.key=s(r(t.key,n(t.seed))),t.seed=o(r(t.key,t.seed))}return l.getBytes(e)},s?(t.seedFile=function(e,t){s.randomBytes(e,function(e,r){if(e)return t(e);t(null,r.toString())})},t.seedFileSync=function(e){return s.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(e){t(e)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n<r;++n)t.pools[t.pool].update(e.substr(n,1)),t.pool=31===t.pool?0:t.pool+1},t.collectInt=function(e,r){for(var n="",i=0;i<r;i+=8)n+=String.fromCharCode(e>>i&255);t.collect(n)},t.registerWorker=function(e){e===self?t.seedFile=function(e,t){self.addEventListener("message",function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))}),self.postMessage({forge:{prng:{needed:e}}})}:e.addEventListener("message",function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})})})},t}},9249:function(e,t,r){var n=r(2595);r(1250),r(9302),r(2927),r(2366),function(){if(n.random&&n.random.getBytes){e.exports=n.random;return}!function(t){var r={},i=[,,,,],s=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=[,,,,])[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=[,,,,])[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),s.putInt32(i[0]),s.putInt32(i[1]),s.putInt32(i[2]),s.putInt32(i[3]),s.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),l=null,c=n.util.globalScope,u=c.crypto||c.msCrypto;if(u&&u.getRandomValues&&(l=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!l){if("undefined"==typeof window||window.document,a.collectInt(+new Date,32),"undefined"!=typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(e){}a.collect(h),h=null}t&&(t().mousemove(function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)}),t().keypress(function(e){a.collectInt(e.charCode,8)}))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!=typeof jQuery?jQuery:null)}()},3574:function(e,t,r){var n=r(2595);r(2366);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5];e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"==typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,s=e,o=e.length(),a=t,l=Math.ceil(a/8);for(r=o;r<128;r++)s.putByte(i[s.at(r-1)+s.at(r-o)&255]);for(s.setAt(128-l,i[s.at(128-l)&255>>(7&a)]),r=127-l;r>=0;r--)s.setAt(r,i[s.at(r+1)^s.at(r+l)]);return s};var o=function(e,t,r){var i,o,a,l,c=!1,u=null,h=null,d=null,p=[];for(a=0,e=n.rc2.expandKey(e,t);a<64;a++)p.push(e.getInt16Le());r?(i=function(e){for(a=0;a<4;a++){var t,r;e[a]+=p[l]+(e[(a+3)%4]&e[(a+2)%4])+(~e[(a+3)%4]&e[(a+1)%4]),e[a]=(t=e[a])<<(r=s[a])&65535|(65535&t)>>16-r,l++}},o=function(e){for(a=0;a<4;a++)e[a]+=p[63&e[(a+3)%4]]}):(i=function(e){for(a=3;a>=0;a--){var t,r;e[a]=(65535&(t=e[a]))>>(r=s[a])|t<<16-r&65535,e[a]-=p[l]+(e[(a+3)%4]&e[(a+2)%4])+(~e[(a+3)%4]&e[(a+1)%4]),l--}},o=function(e){for(a=3;a>=0;a--)e[a]-=p[63&e[(a+3)%4]]});var f=function(e){var t=[];for(a=0;a<4;a++){var n=u.getInt16Le();null!==d&&(r?n^=d.getInt16Le():d.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var i=0;i<e.length;i++)for(var s=0;s<e[i][0];s++)e[i][1](t);for(a=0;a<4;a++)null!==d&&(r?d.putInt16Le(t[a]):t[a]^=d.getInt16Le()),h.putInt16Le(t[a])},g=null;return g={start:function(e,t){e&&"string"==typeof e&&(e=n.util.createBuffer(e)),c=!1,u=n.util.createBuffer(),h=t||new n.util.createBuffer,d=e,g.output=h},update:function(e){for(c||u.putBuffer(e);u.length()>=8;)f([[5,i],[1,o],[6,i],[1,o],[5,i]])},finish:function(e){var t=!0;if(r){if(e)t=e(8,u,!r);else{var n=8===u.length()?8:8-u.length();u.fillWithByte(n,n)}}if(t&&(c=!0,g.update()),!r&&(t=0===u.length())){if(e)t=e(8,h,!r);else{var i=h.length(),s=h.at(i-1);s>i?t=!1:h.truncate(s)}}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return o(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return o(e,t,!1)}},411:function(e,t,r){var n=r(2595);if(r(9642),r(4196),r(552),r(4210),r(7236),r(9249),r(2366),void 0===i)var i=n.jsbn.BigInteger;var s=n.util.isNodejs?r(5819):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var l=n.pki,c=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},p=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},f={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){if(e.algorithm in l.oids)t=l.oids[e.algorithm];else{var t,r=Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}var n=o.oidToDer(t).getBytes(),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);s.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),s.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),o.toDer(i).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do s=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16);while(s.compareTo(t.n)>=0||!s.gcd(t.n).equals(i.ONE));for(var s,o=(e=e.multiply(s.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);0>o.compareTo(a);)o=o.add(t.p);return o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a).multiply(s.modInverse(t.n)).mod(t.n)};function m(e,t,r){var i,s=n.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var a=Error("Message is too long for PKCS#1 v1.5 padding.");throw a.length=e.length,a.max=o-11,a}s.putByte(0),s.putByte(r);var l=o-3-e.length;if(0===r||1===r){i=0===r?0:255;for(var c=0;c<l;++c)s.putByte(i)}else for(;l>0;){for(var u=0,h=n.random.getBytes(l),c=0;c<l;++c)0===(i=h.charCodeAt(c))?++u:s.putByte(i);l=u}return s.putByte(0),s.putBytes(e),s}function b(e,t,r,i){var s=Math.ceil(t.n.bitLength()/8),o=n.util.createBuffer(e),a=o.getByte(),l=o.getByte();if(0!==a||r&&0!==l&&1!==l||!r&&2!=l||r&&0===l&&void 0===i)throw Error("Encryption block is invalid.");var c=0;if(0===l){c=s-3-i;for(var u=0;u<c;++u)if(0!==o.getByte())throw Error("Encryption block is invalid.")}else if(1===l)for(c=0;o.length()>1;){if(255!==o.getByte()){--o.read;break}++c}else if(2===l)for(c=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++c}if(0!==o.getByte()||c!==s-3-o.length())throw Error("Encryption block is invalid.");return o.getBytes()}function w(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&(128&r.charCodeAt(1))==0||255===r.charCodeAt(0)&&(128&r.charCodeAt(1))==128)?r.substr(1):r}function v(e){return n.util.isNodejs&&"function"==typeof s[e]}function E(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.crypto&&"object"==typeof a.globalScope.crypto.subtle&&"function"==typeof a.globalScope.crypto.subtle[e]}function S(e){return void 0!==a.globalScope&&"object"==typeof a.globalScope.msCrypto&&"object"==typeof a.globalScope.msCrypto.subtle&&"function"==typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i<t.length;++i)r[i]=t.charCodeAt(i);return r}l.rsa.encrypt=function(e,t,r){var s,o=r,a=Math.ceil(t.n.bitLength()/8);!1!==r&&!0!==r?(o=2===r,s=m(e,t,r)):(s=n.util.createBuffer()).putBytes(e);for(var l=y(new i(s.toHex(),16),t,o).toString(16),c=n.util.createBuffer(),u=a-Math.ceil(l.length/2);u>0;)c.putByte(0),--u;return c.putBytes(n.util.hexToBytes(l)),c.getBytes()},l.rsa.decrypt=function(e,t,r,s){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var l=new i(n.util.createBuffer(e).toHex(),16);if(l.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");for(var c=y(l,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(c.length/2);h>0;)u.putByte(0),--h;return(u.putBytes(n.util.hexToBytes(c)),!1!==s)?b(u.getBytes(),t,r):u.getBytes()},l.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var s,o=(r=r||{}).prng||n.random,a=r.algorithm||"PRIMEINC";if("PRIMEINC"===a)(s={algorithm:a,state:0,bits:e,rng:{nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r<e.length;++r)e[r]=t.charCodeAt(r)}},eInt:t||65537,e:new i(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(s.eInt);else throw Error("Invalid key generation algorithm: "+a);return s},l.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r,n=new i(null);n.fromInt(30);for(var s=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||u<t);){if(0===e.state){var h,d=null===e.p?e.pBits:e.qBits,p=d-1;0===e.pqState?(e.num=new i(d,e.rng),e.num.testBit(p)||e.num.bitwiseTo(i.ONE.shiftLeft(p),o,e.num),e.num.dAddOffset(31-e.num.mod(n).byteValue(),0),s=0,++e.pqState):1===e.pqState?e.num.bitLength()>d?e.pqState=0:e.num.isProbablePrime((h=e.num.bitLength())<=100?27:h<=150?18:h<=200?15:h<=250?12:h<=300?9:h<=350?8:h<=400?7:h<=500?6:h<=600?5:h<=800?4:h<=1250?3:2)?++e.pqState:e.num.dAddOffset(c[s++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)0>e.p.compareTo(e.q)&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)}}u+=(r=+new Date)-a,a=r}return null!==e.keys},l.rsa.generateKeyPair=function(e,t,r,c){if(1==arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(c=e,e=void 0):2==arguments.length?"number"==typeof e?"function"==typeof t?(c=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,c=t,e=void 0,t=void 0):3==arguments.length&&("number"==typeof t?"function"==typeof r&&(c=r,r=void 0):(c=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t)){if(c){if(v("generateKeyPair"))return s.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(e,t,r){if(e)return c(e);c(null,{privateKey:l.privateKeyFromPem(r),publicKey:l.publicKeyFromPem(t)})});if(E("generateKey")&&E("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)}).then(void 0,function(e){c(e)}).then(function(e){if(e){var t=l.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));c(null,{privateKey:t,publicKey:l.setRsaPublicKey(t.n,t.e)})}});if(S("generateKey")&&S("exportKey")){var u=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);u.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=l.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));c(null,{privateKey:r,publicKey:l.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){c(e)}},u.onerror=function(e){c(e)};return}}else if(v("generateKeyPairSync")){var h=s.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:l.privateKeyFromPem(h.privateKey),publicKey:l.publicKeyFromPem(h.publicKey)}}}var d=l.rsa.createKeyPairGenerationState(e,t,r);if(!c)return l.rsa.stepKeyPairGenerationState(d,0),d.keys;(function(e,t,r){"function"==typeof t&&(r=t,t={});var s={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function o(){a(e.pBits,function(t,n){return t?r(t):(e.p=n,null!==e.q)?c(t,e.q):void a(e.qBits,c)})}function a(e,t){n.prime.generateProbablePrime(e,s,t)}function c(t,n){if(t)return r(t);if(e.q=n,0>e.p.compareTo(e.q)){var s=e.p;e.p=e.q,e.q=s}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)){e.p=null,o();return}if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)){e.q=null,a(e.qBits,c);return}if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE)){e.p=e.q=null,o();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,a(e.qBits,c);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(s.prng=t.prng),o()})(d,r,c)},l.setRsaPublicKey=l.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(e,t,i){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw Error('Unsupported encryption scheme: "'+t+'".');var s=t.encode(e,r,!0);return l.rsa.encrypt(s,r,!0)},r.verify=function(e,t,i,s){"string"==typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===s&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=b(t,r,!0);var i=o.fromDer(t,{parseAllBytes:s._parseAllDigestBytes}),a={},l=[];if(!o.validate(i,f,a,l)){var c=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw c.errors=l,c}var u=o.derToOid(a.algorithmIdentifier);if(!(u===n.oids.md2||u===n.oids.md5||u===n.oids.sha1||u===n.oids.sha224||u===n.oids.sha256||u===n.oids.sha384||u===n.oids.sha512||u===n.oids["sha512-224"]||u===n.oids["sha512-256"])){var c=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw c.oid=u,c}if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:("NONE"===i||"NULL"===i||null===i)&&(i={verify:function(e,t){return e===(t=b(t,r,!0))}});var a=l.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())},r},l.setRsaPrivateKey=l.rsa.setPrivateKey=function(e,t,r,i,s,o,a,c){var u={n:e,e:t,d:r,p:i,q:s,dP:o,dQ:a,qInv:c};return u.decrypt=function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=l.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:b};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={decode:function(e){return e}};else throw Error('Unsupported encryption scheme: "'+t+'".');return t.decode(i,u,!1)},u.sign=function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):("NONE"===t||"NULL"===t||null===t)&&(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return l.rsa.encrypt(n,u,r)},u},l.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(l.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},l.privateKeyFromAsn1=function(e){var t,r,s,a,c,d,p,f,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),s=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),c=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),p=n.util.createBuffer(g.privateKeyExponent2).toHex(),f=n.util.createBuffer(g.privateKeyCoefficient).toHex(),l.setRsaPrivateKey(new i(t,16),new i(r,16),new i(s,16),new i(a,16),new i(c,16),new i(d,16),new i(p,16),new i(f,16))},l.privateKeyToAsn1=l.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.qInv))])},l.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,p,t,r)){var s=o.derToOid(t.publicKeyOid);if(s!==l.oids.rsaEncryption){var a=Error("Cannot read public key. Unknown OID.");throw a.oid=s,a}e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r)){var a=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw a.errors=r,a}var c=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return l.setRsaPublicKey(new i(c,16),new i(u,16))},l.publicKeyToAsn1=l.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(l.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[l.publicKeyToRSAPublicKey(e)])])},l.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,w(e.e))])}},8295:function(e,t,r){var n=r(2595);r(2528),r(2366);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){o||(s=String.fromCharCode(128)+n.util.fillString("\x00",64),o=!0);var e=null,t=n.util.createBuffer(),r=Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return i.start=function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s<r;++s)i.fullMessageLength.push(0);return t=n.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},i},i.start(),i.update=function(s,o){"utf8"===o&&(s=n.util.encodeUtf8(s));var l=s.length;i.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var c=i.fullMessageLength.length-1;c>=0;--c)i.fullMessageLength[c]+=l[1],l[1]=l[0]+(i.fullMessageLength[c]/4294967296>>>0),i.fullMessageLength[c]=i.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(s),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o,l=n.util.createBuffer();l.putBytes(t.bytes());var c=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;l.putBytes(s.substr(0,i.blockLength-c));for(var u=8*i.fullMessageLength[0],h=0;h<i.fullMessageLength.length-1;++h)u+=(o=8*i.fullMessageLength[h+1])/4294967296>>>0,l.putInt32(u>>>0),u=o>>>0;l.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,l);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p},i};var s=null,o=!1;function a(e,t,r){for(var n,i,s,o,a,l,c,u=r.length();u>=64;){for(c=0,i=e.h0,s=e.h1,o=e.h2,a=e.h3,l=e.h4;c<16;++c)n=r.getInt32(),t[c]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+l+1518500249+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<20;++c)n=(n=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|n>>>31,t[c]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+l+1518500249+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<32;++c)n=(n=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|n>>>31,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+1859775393+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<40;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+1859775393+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<60;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s&o|a&(s^o))+l+2400959708+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;c<80;++c)n=(n=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|n>>>30,t[c]=n,n=(i<<5|i>>>27)+(s^o^a)+l+3395469782+n,l=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+l|0,u-=64}}},9302:function(e,t,r){var n=r(2595);r(2528),r(2366);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){o||(s=String.fromCharCode(128)+n.util.fillString("\x00",64),a=[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],o=!0);var e=null,t=n.util.createBuffer(),r=Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return i.start=function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s<r;++s)i.fullMessageLength.push(0);return t=n.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},i},i.start(),i.update=function(s,o){"utf8"===o&&(s=n.util.encodeUtf8(s));var a=s.length;i.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var c=i.fullMessageLength.length-1;c>=0;--c)i.fullMessageLength[c]+=a[1],a[1]=a[0]+(i.fullMessageLength[c]/4294967296>>>0),i.fullMessageLength[c]=i.fullMessageLength[c]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),l(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o,a=n.util.createBuffer();a.putBytes(t.bytes());var c=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;a.putBytes(s.substr(0,i.blockLength-c));for(var u=8*i.fullMessageLength[0],h=0;h<i.fullMessageLength.length-1;++h)u+=(o=8*i.fullMessageLength[h+1])/4294967296>>>0,a.putInt32(u>>>0),u=o>>>0;a.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};l(d,r,a);var p=n.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p.putInt32(d.h5),p.putInt32(d.h6),p.putInt32(d.h7),p},i};var s=null,o=!1,a=null;function l(e,t,r){for(var n,i,s,o,l,c,u,h,d,p,f,g,y,m,b,w=r.length();w>=64;){for(u=0;u<16;++u)t[u]=r.getInt32();for(;u<64;++u)n=((n=t[u-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[u-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[u]=n+t[u-7]+i+t[u-16]|0;for(u=0,h=e.h0,d=e.h1,p=e.h2,f=e.h3,g=e.h4,y=e.h5,m=e.h6,b=e.h7;u<64;++u)o=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7),l=m^g&(y^m),s=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),c=h&d|p&(h^d),n=b+o+l+a[u]+t[u],i=s+c,b=m,m=y,y=g,g=f+n>>>0,f=p,p=d,d=h,h=n+i>>>0;e.h0=e.h0+h|0,e.h1=e.h1+d|0,e.h2=e.h2+p|0,e.h3=e.h3+f|0,e.h4=e.h4+g|0,e.h5=e.h5+y|0,e.h6=e.h6+m|0,e.h7=e.h7+b|0,w-=64}}},8439:function(e,t,r){var n=r(2595);r(2528),r(2366);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var s=n.sha384=n.sha512.sha384=n.sha512.sha384||{};s.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=s,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(o=String.fromCharCode(128)+n.util.fillString("\x00",128),l=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(c={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],c["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],c["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],c["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),void 0===e&&(e="SHA-512"),!(e in c))throw Error("Invalid SHA-512 algorithm: "+e);for(var t=c[e],r=null,i=n.util.createBuffer(),s=Array(80),h=0;h<80;++h)s[h]=[,,];var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var p={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16};return p.start=function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,s=0;s<e;++s)p.fullMessageLength.push(0);i=n.util.createBuffer(),r=Array(t.length);for(var s=0;s<t.length;++s)r[s]=t[s].slice(0);return p},p.start(),p.update=function(e,t){"utf8"===t&&(e=n.util.encodeUtf8(e));var o=e.length;p.messageLength+=o,o=[o/4294967296>>>0,o>>>0];for(var a=p.fullMessageLength.length-1;a>=0;--a)p.fullMessageLength[a]+=o[1],o[1]=o[0]+(p.fullMessageLength[a]/4294967296>>>0),p.fullMessageLength[a]=p.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return i.putBytes(e),u(r,s,i),(i.read>2048||0===i.length())&&i.compact(),p},p.digest=function(){var t,a,l=n.util.createBuffer();l.putBytes(i.bytes());var c=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;l.putBytes(o.substr(0,p.blockLength-c));for(var h=8*p.fullMessageLength[0],d=0;d<p.fullMessageLength.length-1;++d)h+=(t=8*p.fullMessageLength[d+1])/4294967296>>>0,l.putInt32(h>>>0),h=t>>>0;l.putInt32(h);for(var f=Array(r.length),d=0;d<r.length;++d)f[d]=r[d].slice(0);u(f,s,l);var g=n.util.createBuffer();a="SHA-512"===e?f.length:"SHA-384"===e?f.length-2:f.length-4;for(var d=0;d<a;++d)g.putInt32(f[d][0]),(d!==a-1||"SHA-512/224"!==e)&&g.putInt32(f[d][1]);return g},p};var o=null,a=!1,l=null,c=null;function u(e,t,r){for(var n,i,s,o,a,c,u,h,d,p,f,g,y,m,b,w,v,E,S,A,I,T,_,R,C,k,B,P,D,N,L,x,O,M,U,F=r.length();F>=128;){for(D=0;D<16;++D)t[D][0]=r.getInt32()>>>0,t[D][1]=r.getInt32()>>>0;for(;D<80;++D)n=(((N=(x=t[D-2])[0])>>>19|(L=x[1])<<13)^(L>>>29|N<<3)^N>>>6)>>>0,i=((N<<13|L>>>19)^(L<<3|N>>>29)^(N<<26|L>>>6))>>>0,s=(((N=(M=t[D-15])[0])>>>1|(L=M[1])<<31)^(N>>>8|L<<24)^N>>>7)>>>0,o=((N<<31|L>>>1)^(N<<24|L>>>8)^(N<<25|L>>>7))>>>0,O=t[D-7],U=t[D-16],L=i+O[1]+o+U[1],t[D][0]=n+O[0]+s+U[0]+(L/4294967296>>>0)>>>0,t[D][1]=L>>>0;for(D=0,y=e[0][0],m=e[0][1],b=e[1][0],w=e[1][1],v=e[2][0],E=e[2][1],S=e[3][0],A=e[3][1],I=e[4][0],T=e[4][1],_=e[5][0],R=e[5][1],C=e[6][0],k=e[6][1],B=e[7][0],P=e[7][1];D<80;++D)u=((I>>>14|T<<18)^(I>>>18|T<<14)^(T>>>9|I<<23))>>>0,h=((I<<18|T>>>14)^(I<<14|T>>>18)^(T<<23|I>>>9))>>>0,d=(C^I&(_^C))>>>0,p=(k^T&(R^k))>>>0,a=((y>>>28|m<<4)^(m>>>2|y<<30)^(m>>>7|y<<25))>>>0,c=((y<<4|m>>>28)^(m<<30|y>>>2)^(m<<25|y>>>7))>>>0,f=(y&b|v&(y^b))>>>0,g=(m&w|E&(m^w))>>>0,L=P+h+p+l[D][1]+t[D][1],n=B+u+d+l[D][0]+t[D][0]+(L/4294967296>>>0)>>>0,i=L>>>0,s=a+f+((L=c+g)/4294967296>>>0)>>>0,o=L>>>0,B=C,P=k,C=_,k=R,_=I,R=T,I=S+n+((L=A+i)/4294967296>>>0)>>>0,T=L>>>0,S=v,A=E,v=b,E=w,b=y,w=m,y=n+s+((L=i+o)/4294967296>>>0)>>>0,m=L>>>0;L=e[0][1]+m,e[0][0]=e[0][0]+y+(L/4294967296>>>0)>>>0,e[0][1]=L>>>0,L=e[1][1]+w,e[1][0]=e[1][0]+b+(L/4294967296>>>0)>>>0,e[1][1]=L>>>0,L=e[2][1]+E,e[2][0]=e[2][0]+v+(L/4294967296>>>0)>>>0,e[2][1]=L>>>0,L=e[3][1]+A,e[3][0]=e[3][0]+S+(L/4294967296>>>0)>>>0,e[3][1]=L>>>0,L=e[4][1]+T,e[4][0]=e[4][0]+I+(L/4294967296>>>0)>>>0,e[4][1]=L>>>0,L=e[5][1]+R,e[5][0]=e[5][0]+_+(L/4294967296>>>0)>>>0,e[5][1]=L>>>0,L=e[6][1]+k,e[6][0]=e[6][0]+C+(L/4294967296>>>0)>>>0,e[6][1]=L>>>0,L=e[7][1]+P,e[7][0]=e[7][0]+B+(L/4294967296>>>0)>>>0,e[7][1]=L>>>0,F-=128}}},2366:function(e,t,r){var n=r(4112),i=r(2678).Buffer,s=r(2595),o=r(4446),a=e.exports=s.util=s.util||{};function l(e){if(!(8===e||16===e||24===e||32===e))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}function c(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(a.isArrayBuffer(e)||a.isArrayBufferView(e)){if(void 0!==i&&e instanceof i)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r<t.length;++r)this.putByte(t[r])}}}else(e instanceof c||"object"==typeof e&&"string"==typeof e.data&&"number"==typeof e.read)&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}!function(){if(void 0!==n&&n.nextTick,"function"==typeof setImmediate){a.setImmediate=function(){return setImmediate.apply(void 0,arguments)},a.nextTick=function(e){return setImmediate(e)};return}if(a.setImmediate=function(e){setTimeout(e,0)},"undefined"!=typeof window&&"function"==typeof window.postMessage){var e="forge.setImmediate",t=[];a.setImmediate=function(r){t.push(r),1===t.length&&window.postMessage(e,"*")},window.addEventListener("message",function(r){if(r.source===window&&r.data===e){r.stopPropagation();var n=t.slice();t.length=0,n.forEach(function(e){e()})}},!0)}if("undefined"!=typeof MutationObserver){var r=Date.now(),i=!0,s=document.createElement("div"),t=[];new MutationObserver(function(){var e=t.slice();t.length=0,e.forEach(function(e){e()})}).observe(s,{attributes:!0});var o=a.setImmediate;a.setImmediate=function(e){Date.now()-r>15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&s.setAttribute("a",i=!i))}}a.nextTick=a.setImmediate}(),a.isNodejs=void 0!==n&&n.versions&&n.versions.node,a.globalScope=a.isNodejs?r.g:"undefined"==typeof self?window:self,a.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},a.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},a.isArrayBufferView=function(e){return e&&a.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},a.ByteBuffer=c,a.ByteStringBuffer=c,a.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},a.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},a.ByteStringBuffer.prototype.isEmpty=function(){return 0>=this.length()},a.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},a.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},a.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},a.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(a.encodeUtf8(e))},a.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},a.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},a.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},a.ByteStringBuffer.prototype.putInt=function(e,t){l(t);var r="";do t-=8,r+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(r)},a.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)},a.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())},a.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},a.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e},a.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e},a.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},a.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e},a.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e},a.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e},a.ByteStringBuffer.prototype.getInt=function(e){l(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t},a.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},a.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},a.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},a.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},a.ByteStringBuffer.prototype.copy=function(){var e=a.createBuffer(this.data);return e.read=this.read,e},a.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},a.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},a.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},a.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e},a.ByteStringBuffer.prototype.toString=function(){return a.decodeUtf8(this.bytes())},a.DataBuffer=function(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=a.isArrayBuffer(e),n=a.isArrayBufferView(e);if(r||n){r?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,null!=e&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)},a.DataBuffer.prototype.length=function(){return this.write-this.read},a.DataBuffer.prototype.isEmpty=function(){return 0>=this.length()},a.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},a.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},a.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this},a.DataBuffer.prototype.putBytes=function(e,t){if(a.isArrayBufferView(e)){var r,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=n.byteLength-n.byteOffset;this.accommodate(i);var s=new Uint8Array(this.data.buffer,this.write);return s.set(n),this.write+=i,this}if(a.isArrayBuffer(e)){var n=new Uint8Array(e);this.accommodate(n.byteLength);var s=new Uint8Array(this.data.buffer);return s.set(n,this.write),this.write+=n.byteLength,this}if(e instanceof a.DataBuffer||"object"==typeof e&&"number"==typeof e.read&&"number"==typeof e.write&&a.isArrayBufferView(e.data)){var n=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(n.byteLength);var s=new Uint8Array(e.data.byteLength,this.write);return s.set(n),this.write+=n.byteLength,this}if(e instanceof a.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary","string"==typeof e){if("hex"===t)return this.accommodate(Math.ceil(e.length/2)),r=new Uint8Array(this.data.buffer,this.write),this.write+=a.binary.hex.decode(e,r,this.write),this;if("base64"===t)return this.accommodate(3*Math.ceil(e.length/4)),r=new Uint8Array(this.data.buffer,this.write),this.write+=a.binary.base64.decode(e,r,this.write),this;if("utf8"===t&&(e=a.encodeUtf8(e),t="binary"),"binary"===t||"raw"===t)return this.accommodate(e.length),r=new Uint8Array(this.data.buffer,this.write),this.write+=a.binary.raw.decode(r),this;if("utf16"===t)return this.accommodate(2*e.length),r=new Uint16Array(this.data.buffer,this.write),this.write+=a.text.utf16.encode(r),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)},a.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this},a.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")},a.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this},a.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},a.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},a.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},a.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},a.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},a.DataBuffer.prototype.putInt=function(e,t){l(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this},a.DataBuffer.prototype.putSignedInt=function(e,t){return l(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)},a.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},a.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e},a.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e},a.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e},a.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e},a.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e},a.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e},a.DataBuffer.prototype.getInt=function(e){l(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t},a.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},a.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},a.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},a.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},a.DataBuffer.prototype.copy=function(){return new a.DataBuffer(this)},a.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},a.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},a.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},a.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e},a.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if("binary"===(e=e||"utf8")||"raw"===e)return a.binary.raw.encode(t);if("hex"===e)return a.binary.hex.encode(t);if("base64"===e)return a.binary.base64.encode(t);if("utf8"===e)return a.text.utf8.decode(t);if("utf16"===e)return a.text.utf16.decode(t);throw Error("Invalid encoding: "+e)},a.createBuffer=function(e,t){return t=t||"raw",void 0!==e&&"utf8"===t&&(e=a.encodeUtf8(e)),new a.ByteBuffer(e)},a.fillString=function(e,t){for(var r="";t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},a.xorBytes=function(e,t,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+s},a.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t},a.bytesToHex=function(e){return a.createBuffer(e).toHex()},a.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],d="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";a.encode64=function(e,t){for(var r,n,i,s="",o="",a=0;a<e.length;)r=e.charCodeAt(a++),n=e.charCodeAt(a++),i=e.charCodeAt(a++),s+=u.charAt(r>>2)+u.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":s+=u.charAt((15&n)<<2|i>>6)+(isNaN(i)?"=":u.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+s},a.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,s="",o=0;o<e.length;)t=h[e.charCodeAt(o++)-43],r=h[e.charCodeAt(o++)-43],n=h[e.charCodeAt(o++)-43],i=h[e.charCodeAt(o++)-43],s+=String.fromCharCode(t<<2|r>>4),64!==n&&(s+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(s+=String.fromCharCode((3&n)<<6|i)));return s},a.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},a.decodeUtf8=function(e){return decodeURIComponent(escape(e))},a.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:o.encode,decode:o.decode}},a.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},a.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s<e.length;++s)n[i++]=e.charCodeAt(s);return t?i-r:n},a.binary.hex.encode=a.bytesToHex,a.binary.hex.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/2)));var i=0,s=r=r||0;for(1&e.length&&(i=1,n[s++]=parseInt(e[0],16));i<e.length;i+=2)n[s++]=parseInt(e.substr(i,2),16);return t?s-r:n},a.binary.base64.encode=function(e,t){for(var r,n,i,s="",o="",a=0;a<e.byteLength;)r=e[a++],n=e[a++],i=e[a++],s+=u.charAt(r>>2)+u.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":s+=u.charAt((15&n)<<2|i>>6)+(isNaN(i)?"=":u.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+s},a.binary.base64.decode=function(e,t,r){var n,i,s,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var l=0,c=r=r||0;l<e.length;)n=h[e.charCodeAt(l++)-43],i=h[e.charCodeAt(l++)-43],s=h[e.charCodeAt(l++)-43],o=h[e.charCodeAt(l++)-43],a[c++]=n<<2|i>>4,64!==s&&(a[c++]=(15&i)<<4|s>>2,64!==o&&(a[c++]=(3&s)<<6|o));return t?c-r:a.subarray(0,c)},a.binary.base58.encode=function(e,t){return a.binary.baseN.encode(e,d,t)},a.binary.base58.decode=function(e,t){return a.binary.baseN.decode(e,d,t)},a.text={utf8:{},utf16:{}},a.text.utf8.encode=function(e,t,r){e=a.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s<e.length;++s)n[i++]=e.charCodeAt(s);return t?i-r:n},a.text.utf8.decode=function(e){return a.decodeUtf8(String.fromCharCode.apply(null,e))},a.text.utf16.encode=function(e,t,r){var n=t;n||(n=new Uint8Array(2*e.length));for(var i=new Uint16Array(n.buffer),s=r=r||0,o=r,a=0;a<e.length;++a)i[o++]=e.charCodeAt(a),s+=2;return t?s-r:n},a.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))},a.deflate=function(e,t,r){if(t=a.decode64(e.deflate(a.encode64(t)).rval),r){var n=2;32&t.charCodeAt(1)&&(n=6),t=t.substring(n,t.length-4)}return t},a.inflate=function(e,t,r){var n=e.inflate(a.encode64(t)).rval;return null===n?null:a.decode64(n)};var p=function(e,t,r){if(!e)throw Error("WebStorage not available.");if(null===r?n=e.removeItem(t):(r=a.encode64(JSON.stringify(r)),n=e.setItem(t,r)),void 0!==n&&!0!==n.rval){var n,i=Error(n.error.message);throw i.id=n.error.id,i.name=n.error.name,i}},f=function(e,t){if(!e)throw Error("WebStorage not available.");var r=e.getItem(t);if(e.init){if(null===r.rval){if(r.error){var n=Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}r=null}else r=r.rval}return null!==r&&(r=JSON.parse(a.decode64(r))),r},g=function(e,t,r,n){var i=f(e,t);null===i&&(i={}),i[r]=n,p(e,t,i)},y=function(e,t,r){var n=f(e,t);return null!==n&&(n=r in n?n[r]:null),n},m=function(e,t,r){var n=f(e,t);if(null!==n&&r in n){delete n[r];var i=!0;for(var s in n){i=!1;break}i&&(n=null),p(e,t,n)}},b=function(e,t){p(e,t,null)},w=function(e,t,r){var n,i=null;void 0===r&&(r=["web","flash"]);var s=!1,o=null;for(var a in r){n=r[a];try{if("flash"===n||"both"===n){if(null===t[0])throw Error("Flash local storage not available.");i=e.apply(this,t),s="flash"===n}("web"===n||"both"===n)&&(t[0]=localStorage,i=e.apply(this,t),s=!0)}catch(e){o=e}if(s)break}if(!s)throw o;return i};a.setItem=function(e,t,r,n,i){w(g,arguments,i)},a.getItem=function(e,t,r,n){return w(y,arguments,n)},a.removeItem=function(e,t,r,n){w(m,arguments,n)},a.clearItems=function(e,t,r){w(b,arguments,r)},a.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},a.format=function(e){for(var t,r,n=/%./g,i=0,s=[],o=0;t=n.exec(e);){(r=e.substring(o,n.lastIndex-2)).length>0&&s.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i<arguments.length?s.push(arguments[i+++1]):s.push("<?>");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(e.substring(o)),s.join("")},a.formatNumber=function(e,t,r,n){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=void 0===n?".":n,a=i<0?"-":"",l=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",c=l.length>3?l.length%3:0;return a+(c?l.substr(0,c)+o:"")+l.substr(c).replace(/(\d{3})(?=\d)/g,"$1"+o)+(s?(void 0===r?",":r)+Math.abs(i-l).toFixed(s).slice(2):"")},a.formatSize=function(e){return e=e>=1073741824?a.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?a.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?a.formatNumber(e/1024,0)+" KiB":a.formatNumber(e,0)+" bytes"},a.bytesFromIP=function(e){return -1!==e.indexOf(".")?a.bytesFromIPv4(e):-1!==e.indexOf(":")?a.bytesFromIPv6(e):null},a.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=a.createBuffer(),r=0;r<e.length;++r){var n=parseInt(e[r],10);if(isNaN(n))return null;t.putByte(n)}return t.getBytes()},a.bytesFromIPv6=function(e){for(var t=0,r=(8-(e=e.split(":").filter(function(e){return 0===e.length&&++t,!0})).length+t)*2,n=a.createBuffer(),i=0;i<8;++i){if(!e[i]||0===e[i].length){n.fillWithByte(0,r),r=0;continue}var s=a.hexToBytes(e[i]);s.length<2&&n.putByte(0),n.putBytes(s)}return n.getBytes()},a.bytesToIP=function(e){return 4===e.length?a.bytesToIPv4(e):16===e.length?a.bytesToIPv6(e):null},a.bytesToIPv4=function(e){if(4!==e.length)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")},a.bytesToIPv6=function(e){if(16!==e.length)return null;for(var t=[],r=[],n=0,i=0;i<e.length;i+=2){for(var s=a.bytesToHex(e[i]+e[i+1]);"0"===s[0]&&"0"!==s;)s=s.substr(1);if("0"===s){var o=r[r.length-1],l=t.length;o&&l===o.end+1?(o.end=l,o.end-o.start>r[n].end-r[n].start&&(n=r.length-1)):r.push({start:l,end:l})}t.push(s)}if(r.length>0){var c=r[n];c.end-c.start>0&&(t.splice(c.start,c.end-c.start+1,""),0===c.start&&t.unshift(""),7===c.end&&t.push(""))}return t.join(":")},a.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in a&&!e.update)return t(null,a.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return a.cores=navigator.hardwareConcurrency,t(null,a.cores);if("undefined"==typeof Worker)return a.cores=1,t(null,a.cores);if("undefined"==typeof Blob)return a.cores=2,t(null,a.cores);var r=URL.createObjectURL(new Blob(["(",(function(){self.addEventListener("message",function(e){for(var t=Date.now(),r=t+4;Date.now()<r;);self.postMessage({st:t,et:r})})}).toString(),")()"],{type:"application/javascript"}));(function e(n,i,s){if(0===i){var o=Math.floor(n.reduce(function(e,t){return e+t},0)/n.length);return a.cores=Math.max(1,o),URL.revokeObjectURL(r),t(null,a.cores)}(function(e,t){for(var n=[],i=[],s=0;s<e;++s){var o=new Worker(r);o.addEventListener("message",function(r){if(i.push(r.data),i.length===e){for(var s=0;s<e;++s)n[s].terminate();t(null,i)}}),n.push(o)}for(var s=0;s<e;++s)n[s].postMessage(s)})(s,function(t,r){n.push(function(e,t){for(var r=[],n=0;n<e;++n)for(var i=t[n],s=r[n]=[],o=0;o<e;++o)if(n!==o){var a=t[o];(i.st>a.st&&i.st<a.et||a.st>i.st&&a.st<i.et)&&s.push(o)}return r.reduce(function(e,t){return Math.max(e,t.length)},0)}(s,r)),e(n,i-1,s)})})([],5,16)}},3033:function(e,t,r){"use strict";var n=r(7133).lW;class i{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&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 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 r=i.toUint8Array(e),n=i.toUint8Array(t);if(r.length!==n.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(let e of t)r+=e.byteLength;let n=new Uint8Array(r),i=0;for(let e of t){let t=this.toUint8Array(e);n.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}}let s="string",o=/^[0-9a-f]+$/i,a=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,l=/^[a-zA-Z0-9-_]+$/;class c{static fromString(e){let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){let t=i.toUint8Array(e),r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);let n=decodeURIComponent(escape(r));return n}}class u{static toString(e,t=!1){let r=i.toArrayBuffer(e),n=new DataView(r),s="";for(let e=0;e<r.byteLength;e+=2){let r=n.getUint16(e,t);s+=String.fromCharCode(r)}return s}static fromString(e,t=!1){let r=new ArrayBuffer(2*e.length),n=new DataView(r);for(let r=0;r<e.length;r++)n.setUint16(2*r,e.charCodeAt(r),t);return r}}class h{static isHex(e){return typeof e===s&&o.test(e)}static isBase64(e){return typeof e===s&&a.test(e)}static isBase64Url(e){return typeof e===s&&l.test(e)}static ToString(e,t="utf8"){let r=i.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return u.toString(r,!0);case"utf16":case"utf16be":return u.toString(r);default:throw 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 u.fromString(e,!0);case"utf16":case"utf16be":return u.fromString(e);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=i.toUint8Array(e);if("undefined"==typeof btoa)return n.from(t).toString("base64");{let e=this.ToString(t,"binary");return btoa(e)}}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!h.isBase64(t))throw TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(n.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!h.isBase64Url(t))throw 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=h.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return c.fromString(e);case"utf16":case"utf16be":return u.fromString(e);case"utf16le":case"usc2":return u.fromString(e,!0);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=h.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return c.toString(e);case"utf16":case"utf16be":return u.toString(e);case"utf16le":case"usc2":return u.toString(e,!0);default:throw Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(e){let t=i.toUint8Array(e),r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){let t=i.toUint8Array(e),r="",n=t.length;for(let e=0;e<n;e++){let n=t[e];n<16&&(r+="0"),r+=n.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!h.isHex(t))throw TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){let n=t.slice(e,e+2);r[e/2]=parseInt(n,16)}return r.buffer}static ToUtf16String(e,t=!1){return u.toString(e,t)}static FromUtf16String(e,t=!1){return u.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}h.DEFAULT_UTF8_ENCODING="utf8",t.vJ=i,t.ep=h},5493:function(e,t,r){"use strict";function n(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, not ${e}`)}function i(e,...t){if(!(e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function s(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.wrapConstructor");n(e.outputLen),n(e.blockLen)}function o(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function a(e,t){i(e);let r=t.outputLen;if(e.length<r)throw Error(`digestInto() expects output buffer of length at least ${r}`)}r.d(t,{Gg:function(){return o},J8:function(){return a},Rx:function(){return n},aI:function(){return i},vp:function(){return s}})},8289:function(e,t,r){"use strict";r.d(t,{VR:function(){return a},bc:function(){return s},l3:function(){return o}});var n=r(5493),i=r(2305);let s=(e,t,r)=>e&t^~e&r,o=(e,t,r)=>e&t^e&r^t&r;class a extends i.kb{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=(0,i.GL)(this.buffer)}update(e){(0,n.Gg)(this);let{view:t,buffer:r,blockLen:s}=this;e=(0,i.O0)(e);let o=e.length;for(let n=0;n<o;){let a=Math.min(s-this.pos,o-n);if(a===s){let t=(0,i.GL)(e);for(;s<=o-n;n+=s)this.process(t,n);continue}r.set(e.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,n.Gg)(this),(0,n.J8)(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let e=a;e<s;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),l=n?4:0,c=n?0:4;e.setUint32(t+l,o,n),e.setUint32(t+c,a,n)}(r,s-8,BigInt(8*this.length),o),this.process(r,0);let l=(0,i.GL)(e),c=this.outputLen;if(c%4)throw Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,h=this.get();if(u>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)l.setUint32(4*e,h[e],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:s,pos:o}=this;return e.length=n,e.pos=o,e.finished=i,e.destroyed=s,n%t&&e.buffer.set(r),e}}},9802:function(e,t,r){"use strict";r.d(t,{J:function(){return c}});var n=r(8289),i=r(2305);let s=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]),o=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);class l extends n.VR{constructor(){super(64,32,8,!1),this.A=0|o[0],this.B=0|o[1],this.C=0|o[2],this.D=0|o[3],this.E=0|o[4],this.F=0|o[5],this.G=0|o[6],this.H=0|o[7]}get(){let{A:e,B:t,C:r,D:n,E:i,F:s,G:o,H:a}=this;return[e,t,r,n,i,s,o,a]}set(e,t,r,n,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)a[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=a[e-15],r=a[e-2],n=(0,i.np)(t,7)^(0,i.np)(t,18)^t>>>3,s=(0,i.np)(r,17)^(0,i.np)(r,19)^r>>>10;a[e]=s+a[e-7]+n+a[e-16]|0}let{A:r,B:o,C:l,D:c,E:u,F:h,G:d,H:p}=this;for(let e=0;e<64;e++){let t=(0,i.np)(u,6)^(0,i.np)(u,11)^(0,i.np)(u,25),f=p+t+(0,n.bc)(u,h,d)+s[e]+a[e]|0,g=(0,i.np)(r,2)^(0,i.np)(r,13)^(0,i.np)(r,22),y=g+(0,n.l3)(r,o,l)|0;p=d,d=h,h=u,u=c+f|0,c=l,l=o,o=r,r=f+y|0}r=r+this.A|0,o=o+this.B|0,l=l+this.C|0,c=c+this.D|0,u=u+this.E|0,h=h+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(r,o,l,c,u,h,d,p)}roundClean(){a.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}let c=(0,i.hE)(()=>new l)},2305:function(e,t,r){"use strict";r.d(t,{kb:function(){return d},oY:function(){return l},U5:function(){return f},eV:function(){return h},GL:function(){return s},O6:function(){return y},np:function(){return o},O0:function(){return u},iY:function(){return c},hE:function(){return g}});let n="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;var i=r(5493);let s=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),o=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];let a=async()=>{};async function l(e,t,r){let n=Date.now();for(let i=0;i<e;i++){r(i);let e=Date.now()-n;e>=0&&e<t||(await a(),n+=e)}}function c(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function u(e){return"string"==typeof e&&(e=c(e)),(0,i.aI)(e),e}function h(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];(0,i.aI)(n),t+=n.length}let r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}class d{clone(){return this._cloneInto()}}let p={}.toString;function f(e,t){if(void 0!==t&&"[object Object]"!==p.call(t))throw Error("Options should be object or undefined");let r=Object.assign(e,t);return r}function g(e){let t=t=>e().update(u(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function y(e=32){if(n&&"function"==typeof n.getRandomValues)return n.getRandomValues(new Uint8Array(e));throw Error("crypto.getRandomValues must be defined")}},4755:function(e,t,r){"use strict";let n,i;r.d(t,{$3:function(){return j},E9:function(){return S},LO:function(){return W},P6:function(){return et},Pc:function(){return T},T:function(){return J},Xx:function(){return Q}});var s,o=r(5856);/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */let a=BigInt(0),l=BigInt(1),c=BigInt(2),u=BigInt(3),h=BigInt(8),d=Object.freeze({a:a,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:l,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),p=(e,t)=>(e+t/c)/t,f={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){let{n:t}=d,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-l*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=BigInt("0x100000000000000000000000000000000"),o=p(r*e,t),a=p(-n*e,t),c=U(e-o*r-a*i,t),u=U(-o*n-a*r,t),h=c>s,f=u>s;if(h&&(c=t-c),f&&(u=t-u),c>s||u>s)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:c,k2neg:f,k2:u}}};function g(e){let{a:t,b:r}=d,n=U(e*e),i=U(n*e);return U(i+t*e+r)}let y=d.a===a;class m extends Error{constructor(e){super(e)}}function b(e){if(!(e instanceof w))throw TypeError("JacobianPoint expected")}class w{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof S))throw TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(S.ZERO)?w.ZERO:new w(e.x,e.y,l)}static toAffineBatch(e){let t=function(e,t=d.P){let r=Array(e.length),n=e.reduce((e,n,i)=>n===a?e:(r[i]=e,U(e*n,t)),l),i=K(n,t);return e.reduceRight((e,n,i)=>n===a?e:(r[i]=U(e*r[i],t),U(e*n,t)),i),r}(e.map(e=>e.z));return e.map((e,r)=>e.toAffine(t[r]))}static normalizeZ(e){return w.toAffineBatch(e).map(w.fromAffine)}equals(e){b(e);let{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e,a=U(n*n),l=U(o*o),c=U(t*l),u=U(i*a),h=U(U(r*o)*l),d=U(U(s*n)*a);return c===u&&h===d}negate(){return new w(this.x,U(-this.y),this.z)}double(){let{x:e,y:t,z:r}=this,n=U(e*e),i=U(t*t),s=U(i*i),o=e+i,a=U(c*(U(o*o)-n-s)),l=U(u*n),d=U(l*l),p=U(d-c*a),f=U(l*(a-p)-h*s),g=U(c*t*r);return new w(p,f,g)}add(e){b(e);let{x:t,y:r,z:n}=this,{x:i,y:s,z:o}=e;if(i===a||s===a)return this;if(t===a||r===a)return e;let l=U(n*n),u=U(o*o),h=U(t*u),d=U(i*l),p=U(U(r*o)*u),f=U(U(s*n)*l),g=U(d-h),y=U(f-p);if(g===a)return y===a?this.double():w.ZERO;let m=U(g*g),v=U(g*m),E=U(h*m),S=U(y*y-v-c*E),A=U(y*(E-S)-p*v),I=U(n*o*g);return new w(S,A,I)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let t=w.ZERO;if("bigint"==typeof e&&e===a)return t;let r=M(e);if(r===l)return this;if(!y){let e=t,n=this;for(;r>a;)r&l&&(e=e.add(n)),n=n.double(),r>>=l;return e}let{k1neg:n,k1:i,k2neg:s,k2:o}=f.splitScalar(r),c=t,u=t,h=this;for(;i>a||o>a;)i&l&&(c=c.add(h)),o&l&&(u=u.add(h)),h=h.double(),i>>=l,o>>=l;return n&&(c=c.negate()),s&&(u=u.negate()),u=new w(U(u.x*f.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let t=y?128/e+1:256/e+1,r=[],n=this,i=n;for(let s=0;s<t;s++){i=n,r.push(i);for(let t=1;t<2**(e-1);t++)i=i.add(n),r.push(i);n=i.double()}return r}wNAF(e,t){!t&&this.equals(w.BASE)&&(t=S.BASE);let r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&E.get(t);!n&&(n=this.precomputeWindow(r),t&&1!==r&&(n=w.normalizeZ(n),E.set(t,n)));let i=w.ZERO,s=w.BASE,o=1+(y?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),u=2**r,h=BigInt(r);for(let t=0;t<o;t++){let r=t*a,o=Number(e&c);e>>=h,o>a&&(o-=u,e+=l);let d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?s=s.add(v(p,n[r])):i=i.add(v(f,n[d]))}return{p:i,f:s}}multiply(e,t){let r,n,i=M(e);if(y){let{k1neg:e,k1:s,k2neg:o,k2:a}=f.splitScalar(i),{p:l,f:c}=this.wNAF(s,t),{p:u,f:h}=this.wNAF(a,t);l=v(e,l),u=new w(U((u=v(o,u)).x*f.beta),u.y,u.z),r=l.add(u),n=c.add(h)}else{let{p:e,f:s}=this.wNAF(i,t);r=e,n=s}return w.normalizeZ([r,n])[0]}toAffine(e){let{x:t,y:r,z:n}=this,i=this.equals(w.ZERO);null==e&&(e=i?h:K(n));let s=e,o=U(s*s),a=U(o*s),c=U(t*o),u=U(r*a),d=U(n*s);if(i)return S.ZERO;if(d!==l)throw Error("invZ was invalid");return new S(c,u)}}function v(e,t){let r=t.negate();return e?r:t}w.BASE=new w(d.Gx,d.Gy,l),w.ZERO=new w(a,l,a);let E=new WeakMap;class S{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,E.delete(this)}hasEvenY(){return this.y%c===a}static fromCompressedHex(e){let t=32===e.length,r=x(t?e:e.subarray(1));if(!q(r))throw Error("Point is not on curve");let n=g(r),i=function(e){let{P:t}=d,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=e*e*e%t,h=l*l*e%t,p=F(h,u)*h%t,f=F(p,u)*h%t,g=F(f,c)*l%t,y=F(g,n)*g%t,m=F(y,i)*y%t,b=F(m,o)*m%t,w=F(b,a)*b%t,v=F(w,o)*m%t,E=F(v,u)*h%t,S=F(E,s)*y%t,A=F(S,r)*l%t,I=F(A,c);if(I*I%t!==e)throw Error("Cannot find square root");return I}(n),s=(i&l)===l;if(t)s&&(i=U(-i));else{let t=(1&e[0])==1;t!==s&&(i=U(-i))}let o=new S(r,i);return o.assertValidity(),o}static fromUncompressedHex(e){let t=x(e.subarray(1,33)),r=x(e.subarray(33,65)),n=new S(t,r);return n.assertValidity(),n}static fromHex(e){let t=O(e),r=t.length,n=t[0];if(32===r||33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return S.BASE.multiply(z(e))}static fromSignature(e,t,r){let{r:n,s:i}=G(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");let s=V(O(e)),{n:o}=d,a=2===r||3===r?n+o:n,l=K(a,o),c=U(-s*l,o),u=U(i*l,o),h=1&r?"03":"02",p=S.fromHex(h+B(a)),f=S.BASE.multiplyAndAddUnsafe(p,c,u);if(!f)throw Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(e=!1){return L(this.toHex(e))}toHex(e=!1){let t=B(this.x);if(!e)return`04${t}${B(this.y)}`;{let e=this.hasEvenY()?"02":"03";return`${e}${t}`}}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:t,y:r}=this;if(!q(t)||!q(r))throw Error(e);let n=U(r*r),i=g(t);if(U(n-i)!==a)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new S(this.x,U(-this.y))}double(){return w.fromAffine(this).double().toAffine()}add(e){return w.fromAffine(this).add(w.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return w.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){let n=w.fromAffine(this),i=t===a||t===l||this!==S.BASE?n.multiplyUnsafe(t):n.multiply(t),s=w.fromAffine(e).multiplyUnsafe(r),o=i.add(s);return o.equals(w.ZERO)?void 0:o.toAffine()}}function A(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function I(e){if(e.length<2||2!==e[0])throw Error(`Invalid signature integer tag: ${C(e)}`);let t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:x(r),left:e.subarray(t+2)}}S.BASE=new S(d.Gx,d.Gy),S.ZERO=new S(a,a);class T{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){let t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw TypeError(`${r}: Expected string or Uint8Array`);let n=t?C(e):e;if(128!==n.length)throw Error(`${r}: Expected 64-byte hex`);return new T(N(n.slice(0,64)),N(n.slice(64,128)))}static fromDER(e){let t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw TypeError("Signature.fromDER: Expected string or Uint8Array");let{r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error(`Invalid signature tag: ${C(e)}`);if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");let{data:t,left:r}=I(e.subarray(2)),{data:n,left:i}=I(r);if(i.length)throw Error(`Invalid signature: left bytes after parsing: ${C(i)}`);return{r:t,s:n}}(t?e:L(e));return new T(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:t}=this;if(!$(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!$(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=d.n>>l;return this.s>e}normalizeS(){return this.hasHighS()?new T(this.r,U(-this.s,d.n)):this}toDERRawBytes(){return L(this.toDERHex())}toDERHex(){let e=A(D(this.s)),t=A(D(this.r)),r=e.length/2,n=t.length/2,i=D(r),s=D(n),o=D(n+r+4);return`30${o}02${s}${t}02${i}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return L(this.toCompactHex())}toCompactHex(){return B(this.r)+B(this.s)}}function _(...e){if(!e.every(e=>e instanceof Uint8Array))throw Error("Uint8Array list expected");if(1===e.length)return e[0];let t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}let R=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function C(e){if(!(e instanceof Uint8Array))throw Error("Expected Uint8Array");let t="";for(let r=0;r<e.length;r++)t+=R[e[r]];return t}let k=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function B(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(a<=e&&e<k))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function P(e){let t=L(B(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function D(e){let t=e.toString(16);return 1&t.length?`0${t}`:t}function N(e){if("string"!=typeof e)throw TypeError("hexToNumber: expected string, got "+typeof e);return BigInt(`0x${e}`)}function L(e){if("string"!=typeof e)throw TypeError("hexToBytes: expected string, got "+typeof e);if(e.length%2)throw Error("hexToBytes: received invalid unpadded hex"+e.length);let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++){let n=2*r,i=e.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw Error("Invalid byte sequence");t[r]=s}return t}function x(e){return N(C(e))}function O(e){return e instanceof Uint8Array?Uint8Array.from(e):L(e)}function M(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&$(e))return e;throw TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function U(e,t=d.P){let r=e%t;return r>=a?r:t+r}function F(e,t){let{P:r}=d,n=e;for(;t-- >a;)n*=n,n%=r;return n}function K(e,t=d.P){if(e===a||t<=a)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=U(e,t),n=t,i=a,s=l,o=l,c=a;for(;r!==a;){let e=n/r,t=n%r,a=i-o*e,l=s-c*e;n=r,r=t,i=o,s=c,o=a,c=l}let u=n;if(u!==l)throw Error("invert: does not exist");return U(i,t)}function V(e,t=!1){let r=function(e){let t=8*e.length-256,r=x(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;let{n}=d;return r>=n?r-n:r}class H{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return et.hmacSha256(this.k,...e)}hmacSync(...e){return i(this.k,...e)}checkSync(){if("function"!=typeof i)throw new m("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let r=this.v.slice();t.push(r),e+=this.v.length}return _(...t)}generateSync(){this.checkSync(),this.incr();let e=0,t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let r=this.v.slice();t.push(r),e+=this.v.length}return _(...t)}}function $(e){return a<e&&e<d.n}function q(e){return a<e&&e<d.P}function z(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=N(e)}else if(e instanceof Uint8Array){if(32!==e.length)throw Error("Expected 32 bytes of private key");t=x(e)}else throw TypeError("Expected valid private key");if(!$(t))throw Error("Expected private key: 0 < key < n");return t}function G(e){if(e instanceof T)return e.assertValidity(),e;try{return T.fromDER(e)}catch(t){return T.fromCompact(e)}}function j(e,t=!1){return S.fromPrivateKey(e).toRawBytes(t)}function W(e,t,r,n=!1){return S.fromSignature(e,t,r).toRawBytes(n)}function Y(e){let t=e.length>32?e.slice(0,32):e;return x(t)}async function Q(e,t,r={}){let n;let{seed:i,m:s,d:o}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);let n=O(e),i=z(t),s=[P(i),function(e){var t;let r=Y(e),n=U(r,d.n);return P(n<a?r:n)}(n)];if(null!=r){!0===r&&(r=et.randomBytes(32));let e=O(r);if(32!==e.length)throw Error("sign: Expected 32 bytes of extra data");s.push(e)}let o=_(...s),l=Y(n);return{seed:o,m:l,d:i}}(e,t,r.extraEntropy),c=new H(32,32);for(await c.reseed(i);!(n=function(e,t,r,n=!0){let{n:i}=d,s=V(e,!0);if(!$(s))return;let o=K(s,i),c=S.BASE.multiply(s),u=U(c.x,i);if(u===a)return;let h=U(o*U(t+r*u,i),i);if(h===a)return;let p=new T(u,h),f=(c.x===p.r?0:2)|Number(c.y&l);return n&&p.hasHighS()&&(p=p.normalizeS(),f^=1),{sig:p,recovery:f}}(await c.generate(),s,o,r.canonical));)await c.reseed();return function(e,t){let{sig:r,recovery:n}=e,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},t),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}(n,r)}let X={strict:!0};function J(e,t,r,n=X){let i,s;try{i=G(e),t=O(t)}catch(e){return!1}let{r:o,s:a}=i;if(n.strict&&i.hasHighS())return!1;let l=V(t);try{s=r instanceof S?(r.assertValidity(),r):S.fromHex(r)}catch(e){return!1}let{n:c}=d,u=K(a,c),h=U(l*u,c),p=U(o*u,c),f=S.BASE.multiplyAndAddUnsafe(s,h,p);if(!f)return!1;let g=U(f.x,c);return g===o}S.BASE._setWindowSize(8);let Z={node:s||(s=r.t(o,2)),web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},ee={},et={bytesToHex:C,hexToBytes:L,concatBytes:_,mod:U,invert:K,isValidPrivateKey(e){try{return z(e),!0}catch(e){return!1}},_bigintTo32Bytes:P,_normalizePrivateKey:z,hashToPrivateKey:e=>{if((e=O(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");let t=U(x(e),d.n-l)+l;return P(t)},randomBytes:(e=32)=>{if(Z.web)return Z.web.getRandomValues(new Uint8Array(e));if(Z.node){let{randomBytes:t}=Z.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>et.hashToPrivateKey(et.randomBytes(40)),precompute(e=8,t=S.BASE){let r=t===S.BASE?t:new S(t.x,t.y);return r._setWindowSize(e),r.multiply(u),r},sha256:async(...e)=>{if(Z.web){let t=await Z.web.subtle.digest("SHA-256",_(...e));return new Uint8Array(t)}if(Z.node){let{createHash:t}=Z.node,r=t("sha256");return e.forEach(e=>r.update(e)),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(Z.web){let r=await Z.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=_(...t),i=await Z.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}if(Z.node){let{createHmac:r}=Z.node,n=r("sha256",e);return t.forEach(e=>n.update(e)),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=ee[e];if(void 0===r){let t=await et.sha256(Uint8Array.from(e,e=>e.charCodeAt(0)));r=_(t,t),ee[e]=r}return et.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof n)throw new m("sha256Sync is undefined, you need to set it");let r=ee[e];if(void 0===r){let t=n(Uint8Array.from(e,e=>e.charCodeAt(0)));r=_(t,t),ee[e]=r}return n(r,...t)},_JacobianPoint:w};Object.defineProperties(et,{sha256Sync:{configurable:!1,get:()=>n,set(e){n||(n=e)}},hmacSha256Sync:{configurable:!1,get:()=>i,set(e){i||(i=e)}}})},9746:function(e,t,r){"use strict";r.d(t,{Mf:function(){return c},UF:function(){return h},h:function(){return u},lY:function(){return a}});var n=r(5210),i=r(9527);let s=new i.Yd("message:version-0"),o=BigInt(1e6);class a{pubsubTopic;proto;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get _rawTimestamp(){return this.proto.timestamp}get timestamp(){try{if(this.proto.timestamp){let e=this.proto.timestamp/o;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}class l{contentTopic;ephemeral;pubsubTopic;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.pubsubTopic=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}async toWire(e){return n.u.H.encode(await this.toProtoObj(e))}async toProtoObj(e){let t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*o,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){let e=this.metaSetter(r);return{...r,meta:e}}return r}}function c({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:s}){return new l(r,n,(0,i.IY)(r,e??t),s)}class u{pubsubTopic;contentTopic;constructor(e,t){if(this.pubsubTopic=e,this.contentTopic=t,!t||""===t)throw Error("Content topic must be specified")}fromWireToProtoObj(e){let t=n.u.H.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(s.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new a(e,t)}}function h(e,t){return new u((0,i.IY)(e,t),e)}},5867:function(e,t,r){"use strict";var n,i,s,o,a,l,c,u,h,d,p;r.d(t,{eZ:function(){return g},nf:function(){return f},wh:function(){return l},Wq:function(){return a},$Q:function(){return s},K1:function(){return i},Uw:function(){return n},$G:function(){return o}}),(c=n||(n={})).Relay="relay",c.Store="store",c.LightPush="lightpush",c.Filter="filter",(u=i||(i={})).GENERIC_FAIL="Generic error",u.ENCODE_FAILED="Failed to encode",u.DECODE_FAILED="Failed to decode",u.EMPTY_PAYLOAD="Payload is empty",u.SIZE_TOO_BIG="Size is too big",u.TOPIC_NOT_CONFIGURED="Topic not configured",u.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",u.NO_PEER_AVAILABLE="No peer available",u.NO_STREAM_AVAILABLE="No stream available",u.REMOTE_PEER_FAULT="Remote peer fault",u.REMOTE_PEER_REJECTED="Remote peer rejected",u.REQUEST_TIMEOUT="Request timeout",(h=s||(s={})).BACKWARD="backward",h.FORWARD="forward",(d=o||(o={})).BOOTSTRAP="bootstrap",d.PEER_EXCHANGE="peer-exchange",d.LOCAL="local-peer-cache",(p=a||(a={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",p.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",p.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",p.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(l||(l={})).CONNECTION_STATUS="waku:connection";let f="/waku/2/default-waku/proto",g=1},5210:function(e,t,r){"use strict";let n,i,s,o,a,l,c,u,h,d,p,f,g,y,m,b,w,v,E,S,A,I,T,_,R,C,k,B,P,D,N,L,x,O,M,U,F,K;r.d(t,{aF:function(){return eN},HE:function(){return eD},kB:function(){return e6},WS:function(){return e5},u:function(){return e4},fi:function(){return e7},_G:function(){return e9},eW:function(){return e8}});var V,H,$,q,z,G,j,W,Y,Q,X,J,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu,eh,ed,ep,ef,eg,ey,em,eb,ew,ev,eE,eS,eA,eI,eT,e_,eR,eC,ek,eB,eP,eD,eN,eL,ex,eO,eM,eU,eF,eK,eV,eH,e$,eq,ez,eG,ej,eW,eY,eQ,eX,eJ,eZ,e0,e1,e2,e3,e4={};r.r(e4),r.d(e4,{H:function(){return eR}});var e6={};r.r(e6),r.d(e6,{ep:function(){return eL},hO:function(){return ex},$p:function(){return eO}});var e5={};r.r(e5),r.d(e5,{xx:function(){return eV}});var e8={};r.r(e8),r.d(e8,{TA:function(){return eW},e9:function(){return eY},BI:function(){return ez}});var e9={};r.r(e9),r.d(e9,{Zj:function(){return e1}});var e7={};r.r(e7),r.d(e7,{v:function(){return e2},_:function(){return e3}});var te=r(6995),tt=r(9425);(V=e_||(e_={})).codec=()=>(null==n&&(n=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),n),V.encode=e=>(0,te.LE)(e,V.codec()),V.decode=(e,t)=>(0,te.C6)(e,V.codec(),t),(H=eR||(eR={})).codec=()=>(null==i&&(i=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),e_.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=e_.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),i),H.encode=e=>(0,te.LE)(e,H.codec()),H.decode=(e,t)=>(0,te.C6)(e,H.codec(),t),(q=($=eC||(eC={})).ContentFilter||($.ContentFilter={})).codec=()=>(null==o&&(o=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n})),o),q.encode=e=>(0,te.LE)(e,q.codec()),q.decode=(e,t)=>(0,te.C6)(e,q.codec(),t),$.codec=()=>(null==s&&(s=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.subscribe&&!1!==e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&""!==e.topic&&(t.uint32(18),t.string(e.topic)),null!=e.contentFilters)for(let r of e.contentFilters)t.uint32(26),$.ContentFilter.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={subscribe:!1,topic:"",contentFilters:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;case 3:if(r.limits?.contentFilters!=null&&n.contentFilters.length===r.limits.contentFilters)throw new te.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push($.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&t)}}return n})),s),$.encode=e=>(0,te.LE)(e,$.codec()),$.decode=(e,t)=>(0,te.C6)(e,$.codec(),t),(z=ek||(ek={})).codec=()=>(null==a&&(a=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(10),eD.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();if(t>>>3==1){if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new te.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(eD.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),a),z.encode=e=>(0,te.LE)(e,z.codec()),z.decode=(e,t)=>(0,te.C6)(e,z.codec(),t),(G=eB||(eB={})).codec=()=>(null==l&&(l=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),eC.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),ek.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=eC.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=ek.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),l),G.encode=e=>(0,te.LE)(e,G.codec()),G.decode=(e,t)=>(0,te.C6)(e,G.codec(),t),(j=eP||(eP={})).codec=()=>(null==c&&(c=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),c),j.encode=e=>(0,te.LE)(e,j.codec()),j.decode=(e,t)=>(0,te.C6)(e,j.codec(),t),(W=eD||(eD={})).codec=()=>(null==u&&(u=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eP.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eP.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),u),W.encode=e=>(0,te.LE)(e,W.codec()),W.decode=(e,t)=>(0,te.C6)(e,W.codec(),t),(Y=eN||(eN={})).codec=()=>(null==h&&(h=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n})),h),Y.encode=e=>(0,te.LE)(e,Y.codec()),Y.decode=(e,t)=>(0,te.C6)(e,Y.codec(),t),(X=d=(Q=eL||(eL={})).FilterSubscribeType||(Q.FilterSubscribeType={})).SUBSCRIBER_PING="SUBSCRIBER_PING",X.SUBSCRIBE="SUBSCRIBE",X.UNSUBSCRIBE="UNSUBSCRIBE",X.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL",(J=p||(p={}))[J.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",J[J.SUBSCRIBE=1]="SUBSCRIBE",J[J.UNSUBSCRIBE=2]="UNSUBSCRIBE",J[J.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL",(d=Q.FilterSubscribeType||(Q.FilterSubscribeType={})).codec=()=>(0,te.Ji)(p),Q.codec=()=>(null==f&&(f=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.filterSubscribeType&&0!==p[e.filterSubscribeType]&&(t.uint32(16),Q.FilterSubscribeType.codec().encode(e.filterSubscribeType,t)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(let r of e.contentTopics)t.uint32(90),t.string(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:"",filterSubscribeType:d.SUBSCRIBER_PING,contentTopics:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.filterSubscribeType=Q.FilterSubscribeType.codec().decode(e);break;case 10:n.pubsubTopic=e.string();break;case 11:if(r.limits?.contentTopics!=null&&n.contentTopics.length===r.limits.contentTopics)throw new te.sv('decode error - map field "contentTopics" had too many elements',"ERR_MAX_LENGTH");n.contentTopics.push(e.string());break;default:e.skipType(7&t)}}return n})),f),Q.encode=e=>(0,te.LE)(e,Q.codec()),Q.decode=(e,t)=>(0,te.C6)(e,Q.codec(),t),(Z=ex||(ex={})).codec=()=>(null==g&&(g=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:"",statusCode:0},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;default:e.skipType(7&t)}}return n})),g),Z.encode=e=>(0,te.LE)(e,Z.codec()),Z.decode=(e,t)=>(0,te.C6)(e,Z.codec(),t),(ee=eO||(eO={})).codec=()=>(null==y&&(y=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),eU.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=eU.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),y),ee.encode=e=>(0,te.LE)(e,ee.codec()),ee.decode=(e,t)=>(0,te.C6)(e,ee.codec(),t),(et=eM||(eM={})).codec=()=>(null==m&&(m=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),m),et.encode=e=>(0,te.LE)(e,et.codec()),et.decode=(e,t)=>(0,te.C6)(e,et.codec(),t),(er=eU||(eU={})).codec=()=>(null==b&&(b=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eM.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eM.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),b),er.encode=e=>(0,te.LE)(e,er.codec()),er.decode=(e,t)=>(0,te.C6)(e,er.codec(),t),(en=eF||(eF={})).codec=()=>(null==w&&(w=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),e$.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={pubsubTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=e$.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),w),en.encode=e=>(0,te.LE)(e,en.codec()),en.decode=(e,t)=>(0,te.C6)(e,en.codec(),t),(ei=eK||(eK={})).codec=()=>(null==v&&(v=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={isSuccess:!1},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n})),v),ei.encode=e=>(0,te.LE)(e,ei.codec()),ei.decode=(e,t)=>(0,te.C6)(e,ei.codec(),t),(es=eV||(eV={})).codec=()=>(null==E&&(E=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),eF.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),eK.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=eF.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=eK.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),E),es.encode=e=>(0,te.LE)(e,es.codec()),es.decode=(e,t)=>(0,te.C6)(e,es.codec(),t),(eo=eH||(eH={})).codec=()=>(null==S&&(S=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),S),eo.encode=e=>(0,te.LE)(e,eo.codec()),eo.decode=(e,t)=>(0,te.C6)(e,eo.codec(),t),(ea=e$||(e$={})).codec=()=>(null==A&&(A=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eH.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eH.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),A),ea.encode=e=>(0,te.LE)(e,ea.codec()),ea.decode=(e,t)=>(0,te.C6)(e,ea.codec(),t),(el=eq||(eq={})).codec=()=>(null==I&&(I=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.digest&&e.digest.byteLength>0&&(t.uint32(10),t.bytes(e.digest)),null!=e.receiverTime&&0n!==e.receiverTime&&(t.uint32(16),t.sint64(e.receiverTime)),null!=e.senderTime&&0n!==e.senderTime&&(t.uint32(24),t.sint64(e.senderTime)),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(34),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={digest:(0,tt.u)(0),receiverTime:0n,senderTime:0n,pubsubTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.digest=e.bytes();break;case 2:n.receiverTime=e.sint64();break;case 3:n.senderTime=e.sint64();break;case 4:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),I),el.encode=e=>(0,te.LE)(e,el.codec()),el.decode=(e,t)=>(0,te.C6)(e,el.codec(),t),(eu=(ec=ez||(ez={})).Direction||(ec.Direction={})).BACKWARD="BACKWARD",eu.FORWARD="FORWARD",(eh=T||(T={}))[eh.BACKWARD=0]="BACKWARD",eh[eh.FORWARD=1]="FORWARD",(ec.Direction||(ec.Direction={})).codec=()=>(0,te.Ji)(T),ec.codec=()=>(null==_&&(_=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pageSize&&(t.uint32(8),t.uint64(e.pageSize)),null!=e.cursor&&(t.uint32(18),eq.codec().encode(e.cursor,t)),null!=e.direction&&(t.uint32(24),ec.Direction.codec().encode(e.direction,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.pageSize=e.uint64();break;case 2:n.cursor=eq.codec().decode(e,e.uint32(),{limits:r.limits?.cursor});break;case 3:n.direction=ec.Direction.codec().decode(e);break;default:e.skipType(7&t)}}return n})),_),ec.encode=e=>(0,te.LE)(e,ec.codec()),ec.decode=(e,t)=>(0,te.C6)(e,ec.codec(),t),(ed=eG||(eG={})).codec=()=>(null==R&&(R=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n})),R),ed.encode=e=>(0,te.LE)(e,ed.codec()),ed.decode=(e,t)=>(0,te.C6)(e,ed.codec(),t),(ep=ej||(ej={})).codec=()=>(null==C&&(C=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),null!=e.contentFilters)for(let r of e.contentFilters)t.uint32(26),eG.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),ez.codec().encode(e.pagingInfo,t)),null!=e.startTime&&(t.uint32(40),t.sint64(e.startTime)),null!=e.endTime&&(t.uint32(48),t.sint64(e.endTime)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={contentFilters:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 2:n.pubsubTopic=e.string();break;case 3:if(r.limits?.contentFilters!=null&&n.contentFilters.length===r.limits.contentFilters)throw new te.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(eG.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=ez.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 5:n.startTime=e.sint64();break;case 6:n.endTime=e.sint64();break;default:e.skipType(7&t)}}return n})),C),ep.encode=e=>(0,te.LE)(e,ep.codec()),ep.decode=(e,t)=>(0,te.C6)(e,ep.codec(),t),(eg=k=(ef=eW||(eW={})).HistoryError||(ef.HistoryError={})).NONE="NONE",eg.INVALID_CURSOR="INVALID_CURSOR",eg.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",eg.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",(ey=B||(B={}))[ey.NONE=0]="NONE",ey[ey.INVALID_CURSOR=1]="INVALID_CURSOR",ey[ey.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",ey[ey.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",(k=ef.HistoryError||(ef.HistoryError={})).codec=()=>(0,te.Ji)(B),ef.codec=()=>(null==P&&(P=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(18),eX.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(26),ez.codec().encode(e.pagingInfo,t)),null!=e.error&&0!==B[e.error]&&(t.uint32(32),ef.HistoryError.codec().encode(e.error,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[],error:k.NONE},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 2:if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new te.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(eX.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 3:n.pagingInfo=ez.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 4:n.error=ef.HistoryError.codec().decode(e);break;default:e.skipType(7&t)}}return n})),P),ef.encode=e=>(0,te.LE)(e,ef.codec()),ef.decode=(e,t)=>(0,te.C6)(e,ef.codec(),t),(em=eY||(eY={})).codec=()=>(null==D&&(D=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.query&&(t.uint32(18),ej.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),eW.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={requestId:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.query=ej.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=eW.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),D),em.encode=e=>(0,te.LE)(e,em.codec()),em.decode=(e,t)=>(0,te.C6)(e,em.codec(),t),(eb=eQ||(eQ={})).codec=()=>(null==N&&(N=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={proof:(0,tt.u)(0),merkleRoot:(0,tt.u)(0),epoch:(0,tt.u)(0),shareX:(0,tt.u)(0),shareY:(0,tt.u)(0),nullifier:(0,tt.u)(0),rlnIdentifier:(0,tt.u)(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),N),eb.encode=e=>(0,te.LE)(e,eb.codec()),eb.decode=(e,t)=>(0,te.C6)(e,eb.codec(),t),(ew=eX||(eX={})).codec=()=>(null==L&&(L=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),eQ.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={payload:(0,tt.u)(0),contentTopic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=eQ.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),L),ew.encode=e=>(0,te.LE)(e,ew.codec()),ew.decode=(e,t)=>(0,te.C6)(e,ew.codec(),t),(ev=eJ||(eJ={})).codec=()=>(null==x&&(x=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n})),x),ev.encode=e=>(0,te.LE)(e,ev.codec()),ev.decode=(e,t)=>(0,te.C6)(e,ev.codec(),t),(eE=eZ||(eZ={})).codec=()=>(null==O&&(O=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n})),O),eE.encode=e=>(0,te.LE)(e,eE.codec()),eE.decode=(e,t)=>(0,te.C6)(e,eE.codec(),t),(eS=e0||(e0={})).codec=()=>(null==M&&(M=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(let r of e.peerInfos)t.uint32(10),eJ.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={peerInfos:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();if(t>>>3==1){if(r.limits?.peerInfos!=null&&n.peerInfos.length===r.limits.peerInfos)throw new te.sv('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(eJ.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),M),eS.encode=e=>(0,te.LE)(e,eS.codec()),eS.decode=(e,t)=>(0,te.C6)(e,eS.codec(),t),(eA=e1||(e1={})).codec=()=>(null==U&&(U=(0,te.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),eZ.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),e0.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.query=eZ.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=e0.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),U),eA.encode=e=>(0,te.LE)(e,eA.codec()),eA.decode=(e,t)=>(0,te.C6)(e,eA.codec(),t),(eI=e2||(e2={})).codec=()=>(null==F&&(F=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(let r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(r.limits?.shards!=null&&n.shards.length===r.limits.shards)throw new te.sv('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),F),eI.encode=e=>(0,te.LE)(e,eI.codec()),eI.decode=(e,t)=>(0,te.C6)(e,eI.codec(),t),(eT=e3||(e3={})).codec=()=>(null==K&&(K=(0,te.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(let r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={shards:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(r.limits?.shards!=null&&n.shards.length===r.limits.shards)throw new te.sv('decode error - map field "shards" had too many elements',"ERR_MAX_LENGTH");n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),K),eT.encode=e=>(0,te.LE)(e,eT.codec()),eT.decode=(e,t)=>(0,te.C6)(e,eT.codec(),t)},8089:function(e,t,r){"use strict";let n,i,s,o,a,l,c,u,h,d,p,f,g,y,m,b,w,v,E,S,A,I,T,_,R,C,k;r.d(t,{Uw:function(){return tb.Uw},Md:function(){return tj.Md},pq:function(){return pP},iY:function(){return tj.iY},gT:function(){return rb}});var B,P,D,N,L,x,O,M,U,F,K,V,H,$,q,z,G,j,W,Y,Q,X,J,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu,eh,ed,ep,ef,eg,ey,em,eb,ew,ev,eE,eS,eA,eI,eT,e_,eR,eC,ek,eB,eP,eD,eN,eL,ex,eO,eM,eU,eF,eK,eV,eH,e$,eq,ez,eG,ej,eW,eY,eQ,eX,eJ,eZ,e0,e1,e2,e3,e4,e6,e5,e8,e9,e7,te,tt,tr,tn,ti,ts,to,ta,tl,tc,tu={};r.r(tu),r.d(tu,{gk:function(){return nR},dQ:function(){return nK},ci:function(){return nk},bytesToNumberBE:function(){return nL},ty:function(){return nx},eV:function(){return nF},n$:function(){return n$},ql:function(){return nU},hexToBytes:function(){return nN},_t:function(){return n_},tL:function(){return nO},S5:function(){return nM},FF:function(){return nz}});var th={};r.r(th),r.d(th,{Ed25519PrivateKey:function(){return sa},Ed25519PublicKey:function(){return so},generateKeyPair:function(){return su},generateKeyPairFromSeed:function(){return sh},unmarshalEd25519PrivateKey:function(){return sl},unmarshalEd25519PublicKey:function(){return sc}});var td={};r.r(td),r.d(td,{MAX_KEY_SIZE:function(){return sS},RsaPrivateKey:function(){return sI},RsaPublicKey:function(){return sA},fromJwk:function(){return sR},generateKeyPair:function(){return sC},unmarshalRsaPrivateKey:function(){return sT},unmarshalRsaPublicKey:function(){return s_}});var tp={};r.r(tp),r.d(tp,{Secp256k1PrivateKey:function(){return sq},Secp256k1PublicKey:function(){return s$},generateKeyPair:function(){return sj},unmarshalSecp256k1PrivateKey:function(){return sz},unmarshalSecp256k1PublicKey:function(){return sG}});var tf={};r.r(tf),r.d(tf,{Ed25519PrivateKey:function(){return aI},Ed25519PublicKey:function(){return aA},generateKeyPair:function(){return aR},generateKeyPairFromSeed:function(){return aC},unmarshalEd25519PrivateKey:function(){return aT},unmarshalEd25519PublicKey:function(){return a_}});var tg={};r.r(tg),r.d(tg,{MAX_RSA_KEY_SIZE:function(){return l1},RsaPrivateKey:function(){return l3},RsaPublicKey:function(){return l2},fromJwk:function(){return l5},generateKeyPair:function(){return l8},unmarshalRsaPrivateKey:function(){return l4},unmarshalRsaPublicKey:function(){return l6}});var ty={};r.r(ty),r.d(ty,{Secp256k1PrivateKey:function(){return ce},Secp256k1PublicKey:function(){return l7},generateKeyPair:function(){return cn},unmarshalSecp256k1PrivateKey:function(){return ct},unmarshalSecp256k1PublicKey:function(){return cr}});var tm=r(9746),tb=r(5867),tw=r(9527),tv=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{let t=[];for await(let r of e)t.push(r);return t})();let t=[];for(let r of e)t.push(r);return t},tE=r(7383),tS=r(9425);function tA(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));let r=(0,tS.E)(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}var tI=r(1363);let tT=Symbol.for("@achingbrain/uint8arraylist");function t_(e,t){if(null==t||t<0)throw RangeError("index is out of bounds");let r=0;for(let n of e){let e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw RangeError("index is out of bounds")}function tR(e){return!!e?.[tT]}class tC{bufs;length;[tT]=!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 r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(tR(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw 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 r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(tR(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=t_(this.bufs,e);return t.buf[t.index]}set(e,t){let r=t_(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(tR(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));else throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(!Number.isNaN(e=Math.trunc(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:r,length:n}=this._subList(e,t);return tA(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:tA(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new tC;return i.length=n,i.bufs=[...r],i}_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 RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],o=n,a=o+s.byteLength;if(n=a,e>=a)continue;let l=e>=o&&e<a,c=t>o&&t<=a;if(l&&c){if(e===o&&t===a){r.push(s);break}let n=e-o;r.push(s.subarray(n,n+(t-e)));break}if(l){if(0===e){r.push(s);continue}r.push(s.subarray(e-o));continue}if(c){if(t===a){r.push(s);break}r.push(s.subarray(0,t-o));break}r.push(s)}return{bufs:r,length:t-e}}indexOf(e,t=0){let r;if(!tR(e)&&!(e instanceof Uint8Array))throw TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;let i=n.byteLength;if(0===i)throw TypeError("search must be at least 1 byte long");let s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<i;e++)s[n[e]]=e;let o=this.byteLength-n.byteLength,a=n.byteLength-1;for(let e=t;e<=o;e+=r){r=0;for(let t=a;t>=0;t--){let i=this.get(e+t);if(n[t]!==i){r=Math.max(1,t-s[i]);break}}if(0===r)return e}return -1}getInt8(e){let t=this.subarray(e,e+1),r=new DataView(t.buffer,t.byteOffset,t.byteLength);return r.getInt8(0)}setInt8(e,t){let r=(0,tS.E)(1),n=new DataView(r.buffer,r.byteOffset,r.byteLength);n.setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getInt16(0,t)}setInt16(e,t,r){let n=(0,tS.u)(2),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getInt32(0,t)}setInt32(e,t,r){let n=(0,tS.u)(4),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getBigInt64(0,t)}setBigInt64(e,t,r){let n=(0,tS.u)(8),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1),r=new DataView(t.buffer,t.byteOffset,t.byteLength);return r.getUint8(0)}setUint8(e,t){let r=(0,tS.E)(1),n=new DataView(r.buffer,r.byteOffset,r.byteLength);n.setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getUint16(0,t)}setUint16(e,t,r){let n=(0,tS.u)(2),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getUint32(0,t)}setUint32(e,t,r){let n=(0,tS.u)(4),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getBigUint64(0,t)}setBigUint64(e,t,r){let n=(0,tS.u)(8),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getFloat32(0,t)}setFloat32(e,t,r){let n=(0,tS.u)(4),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8),n=new DataView(r.buffer,r.byteOffset,r.byteLength);return n.getFloat64(0,t)}setFloat64(e,t,r){let n=(0,tS.u)(8),i=new DataView(n.buffer,n.byteOffset,n.byteLength);i.setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e||!(e instanceof tC)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!(0,tI.f)(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new tC;return r.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),r.length=t,r}}function tk(e){return null!=e[Symbol.asyncIterator]}let tB=e=>{let t=tE.P$(e),r=(0,tS.E)(t);return tE.cv(e,r),tB.bytes=t,r};function tP(e,t){t=t??{};let r=t.lengthEncoder??tB;function*n(e){let t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return tk(e)?async function*(){for await(let t of e)yield*n(t)}():function*(){for(let t of e)yield*n(t)}()}tB.bytes=0,tP.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??tB;return new tC(r(e.byteLength),e)};var tD=r(2594);(B=eP||(eP={}))[B.LENGTH=0]="LENGTH",B[B.DATA=1]="DATA";let tN=e=>{let t=tE.Jx(e);return tN.bytes=tE.P$(t),t};function tL(e,t){let r=new tC,n=eP.LENGTH,i=-1,s=t?.lengthDecoder??tN,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*l(){for(;r.byteLength>0;){if(n===eP.LENGTH)try{if((i=s(r))<0)throw tD(Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw tD(Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let e=s.bytes;r.consume(e),t?.onLength!=null&&t.onLength(i),n=eP.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw tD(Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===eP.DATA){if(r.byteLength<i)break;let e=r.sublist(0,i);r.consume(i),t?.onData!=null&&t.onData(e),yield e,n=eP.LENGTH}}}return tk(e)?async function*(){for await(let t of e)r.append(t),yield*l();if(r.byteLength>0)throw tD(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let t of e)r.append(t),yield*l();if(r.byteLength>0)throw tD(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}function tx(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}tN.bytes=0,tL.fromReader=(e,t)=>{let r=1,n=async function*(){for(;;)try{let{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}();return tL(n,{...t??{},onLength:e=>{r=e}})};class tO{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!=0)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class tM{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new tO(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 tO(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){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()}}class tU extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function tF(e={}){return function(e,t){let r,n,i;let s=(t=t??{}).onEnd,o=new tM,a=tx(),l=async()=>{try{if(!o.isEmpty())return e(o);if(i)return{done:!0};return await new Promise((t,i)=>{n=s=>{n=null,o.push(s);try{t(e(o))}catch(e){i(e)}return r}})}finally{o.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=tx()})}},c=e=>null!=n?n(e):(o.push(e),r),u=e=>(o=new tM,null!=n)?n({error:e}):(o.push({error:e}),r),h=e=>{if(i)return r;if(t?.objectMode!==!0&&e?.byteLength==null)throw Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},d=e=>i?r:(i=!0,null!=e?u(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:l,return:()=>(o=new tM,d(),{done:!0}),throw:e=>(d(e),{done:!0}),push:h,end:d,get readableLength(){return o.size},onEmpty:async e=>{let t,r;let n=e?.signal;if(n?.throwIfAborted(),!o.isEmpty()){null!=n&&(t=new Promise((e,t)=>{r=()=>{t(new tU)},n.addEventListener("abort",r)}));try{await Promise.race([a.promise,t])}finally{null!=r&&null!=n&&n?.removeEventListener("abort",r)}}}},null==s)return r;let p=r;return r={[Symbol.asyncIterator](){return this},next:()=>p.next(),throw:e=>(p.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(p.return(),null!=s&&(s(),s=void 0),{done:!0}),push:h,end:e=>(p.end(e),null!=s&&(s(e),s=void 0),r),get readableLength(){return p.readableLength},onEmpty:e=>p.onEmpty(e)}}(e=>{let t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}},e)}var tK=function(...e){let t=[];for(let r of e)null!=r[Symbol.asyncIterator]||t.push(r);return t.length===e.length?function*(){for(let e of t)yield*e}():async function*(){let t=tF({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async e=>{for await(let r of e)t.push(r)})),t.end()}catch(e){t.end(e)}}),yield*t}()};function tV(e,...t){if(null==e)throw Error("Empty pipeline");if(tz(e)){let t=e;e=()=>t.source}else if(tq(e)||t$(e)){let t=e;e=()=>t}let r=[e,...t];if(r.length>1&&tz(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)tz(r[e])&&(r[e]=tG(r[e]));return tH(...r)}let tH=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},t$=e=>e?.[Symbol.asyncIterator]!=null,tq=e=>e?.[Symbol.iterator]!=null,tz=e=>null!=e&&null!=e.sink&&null!=e.source,tG=e=>t=>{let r=e.sink(t);if(r?.then!=null){let t;let n=tF({objectMode:!0});r.then(()=>{n.end()},e=>{n.end(e)});let i=e.source;if(t$(i))t=async function*(){yield*i,n.end()};else if(tq(i))t=function*(){yield*i,n.end()};else throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");return tK(n,t())}return e.source};var tj=r(9710),tW=r(5758);async function tY(e,t){if(0===t.length)return[];let r=await Promise.all(t.map(async t=>{try{let r=(await e.get(t.id)).metadata.get("ping");if(!r)return{peer:t,ping:1/0};let n=Number((0,tj.Md)(r));return{peer:t,ping:n}}catch(e){return{peer:t,ping:1/0}}})),n=r.filter(e=>null!==e);return n.sort((e,t)=>e.ping-t.ping).map(e=>e.peer)}async function tQ(e,t){let r=[];return await e.forEach(e=>{for(let n=0;n<t.length;n++)if(e.protocols.includes(t[n])){r.push(e);break}}),r}async function tX(e,t,r,n){let i=e.filter(e=>"open"===e.status),s=i.map(async e=>{let i=await t.get(e.remotePeer),s=r.some(e=>i.protocols.includes(e));if(s){if(!n)return i;{let e=i.metadata.get("shardInfo"),t=e&&(0,tW.I)(e);if(t&&n.clusterId===t.clusterId)return i}}return null}),o=await Promise.all(s);return o.filter(e=>null!==e)}class tJ{multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new tw.Yd(`stream-manager:${e}`),this.streamPool=new Map,this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){let t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.createStream(e);this.streamPool.delete(t),this.prepareStream(e);try{let e=await r;if(e&&"closed"!==e.status)return e}catch(e){this.log.warn(`Failed to get stream for ${t} -- `,e),this.log.warn("Attempting to create a new stream for the peer")}return this.createStream(e)}async createStream(e,t=0){let r=this.getConnections(e.id),n=function(e){let t;if(e.length)return 1===e.length?e[0]:(e.forEach(e=>{"open"===e.status&&(t?e.timeline.open>t.timeline.open&&(t=e):t=e)}),t)}(r);if(!n)throw Error("Failed to get a connection to the peer");try{return await n.newStream(this.multicodec)}catch(r){if(t<3){let r=1e3*Math.pow(2,t);return await new Promise(e=>setTimeout(e,r)),this.createStream(e,t+1)}throw Error(`Failed to create a new stream for ${e.id.toString()} -- `+r)}}prepareStream(e){let t=new Promise(e=>setTimeout(e,5e3)),r=Promise.race([this.createStream(e),t.then(()=>{throw Error("Connection timeout")})]).catch(t=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()} -- `,t)});this.streamPool.set(e.id.toString(),r)}handlePeerUpdateStreamPool=e=>{let{peer:t}=e.detail;if(t.protocols.includes(this.multicodec)){let e=this.isConnectedTo(t.id);if(e)this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareStream(t);else{let e=t.id.toString();this.streamPool.delete(e),this.log.info(`Removed pending stream for disconnected peer ${e}`)}}};isConnectedTo(e){let t=this.getConnections(e);return t.some(e=>"open"===e.status)}}class tZ{multicodec;components;log;pubsubTopics;options;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n,i){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.options=i,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new tJ(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}get peerStore(){return this.components.peerStore}async allPeers(){return tQ(this.peerStore,[this.multicodec])}async connectedPeers(){let e=await this.allPeers();return e.filter(e=>this.components.connectionManager.getConnections(e.id).length>0)}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:1,numPeers:0}){let r=await tX(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?(0,tw.Ao)(this.options.shardInfo).shardInfo:void 0),n=function(e,t,r){let n=e.filter(e=>e.tags.has(tb.$G.BOOTSTRAP)).slice(0,r);t>0&&t<n.length&&(n=n.slice(0,t));let i=e.filter(e=>!e.tags.has(tb.$G.BOOTSTRAP));if(0===t)return[...n,...i];let s=[...n];for(;s.length<t&&i.length>0;){let e=Math.floor(Math.random()*i.length),t=i.splice(e,1)[0];s.push(t)}return s}(r,e,t),i=await tY(this.peerStore,n);return 0===i.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),i.length<e&&this.log.warn(`Only ${i.length} peers found. Requested ${e}.`),i}}var t0=r(5210);let t1="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var t2={randomUUID:t1};let t3=new Uint8Array(16),t4=[];for(let e=0;e<256;++e)t4.push((e+256).toString(16).slice(1));var t6=function(e,t,r){if(t2.randomUUID&&!t&&!e)return t2.randomUUID();e=e||{};let i=e.random||(e.rng||function(){if(!n&&!(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(t3)})();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return t4[e[t+0]]+t4[e[t+1]]+t4[e[t+2]]+t4[e[t+3]]+"-"+t4[e[t+4]]+t4[e[t+5]]+"-"+t4[e[t+6]]+t4[e[t+7]]+"-"+t4[e[t+8]]+t4[e[t+9]]+"-"+t4[e[t+10]]+t4[e[t+11]]+t4[e[t+12]]+t4[e[t+13]]+t4[e[t+14]]+t4[e[t+15]]}(i)};class t5{proto;constructor(e){this.proto=e}static decode(e){let t=t0.kB.$p.decode(e);return new t5(t)}encode(){return t0.kB.$p.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class t8{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new t8({requestId:t6(),filterSubscribeType:t0.kB.ep.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new t8({requestId:t6(),filterSubscribeType:t0.kB.ep.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new t8({requestId:t6(),filterSubscribeType:t0.kB.ep.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new t8({requestId:t6(),filterSubscribeType:t0.kB.ep.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){let t=t0.kB.ep.decode(e);return new t8(t)}encode(){return t0.kB.ep.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class t9{proto;constructor(e){this.proto=e}static decode(e){let t=t0.kB.hO.decode(e);return new t9(t)}encode(){return t0.kB.hO.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}let t7=new tw.Yd("filter:v2"),re={SUBSCRIBE:"/vac/waku/filter-subscribe/2.0.0-beta1",PUSH:"/vac/waku/filter-push/2.0.0-beta1"};class rt extends tZ{handleIncomingMessage;constructor(e,t,r){super(re.SUBSCRIBE,t.components,t7,r.pubsubTopics,r),this.handleIncomingMessage=e,t.handle(re.PUSH,this.onRequest.bind(this),{maxInboundStreams:100}).catch(e=>{t7.error("Failed to register ",re.PUSH,e)})}onRequest(e){let{connection:t,stream:r}=e,{remotePeer:n}=t;t7.info(`Received message from ${n.toString()}`);try{tV(r,tL,async e=>{for await(let t of e){let e=t5.decode(t.slice()),{pubsubTopic:r,wakuMessage:n}=e;if(!n){t7.error("Received empty message");return}if(!r){t7.error("Pubsub topic missing from push message");return}await this.handleIncomingMessage(r,n)}}).then(()=>{t7.info("Receiving pipe closed.")},e=>{t7.error("Error with receiving pipe",e)})}catch(e){t7.error("Error decoding message",e)}}async subscribe(e,t,r){let n;let i=await this.getStream(t),s=t8.createSubscribeRequest(e,r);try{n=await tV([s.encode()],tP,i,tL,async e=>await tv(e))}catch(e){return t7.error("Failed to send subscribe request",e),{success:null,failure:{error:tb.K1.GENERIC_FAIL,peerId:t.id}}}let{statusCode:o,requestId:a,statusDesc:l}=t9.decode(n[0].slice());return o<200||o>=300?(t7.error(`Filter subscribe request ${a} failed with status code ${o}: ${l}`),{failure:{error:tb.K1.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return t7.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:tb.K1.REMOTE_PEER_FAULT,peerId:t.id}}}let i=t8.createUnsubscribeRequest(e,r);try{await tV([i.encode()],tP,n.sink)}catch(e){return t7.error("Failed to send unsubscribe request",e),{success:null,failure:{error:tb.K1.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){let r=await this.getStream(t),n=t8.createUnsubscribeAllRequest(e),i=await tV([n.encode()],tP,r,tL,async e=>await tv(e));if(!i||!i.length)return{failure:{error:tb.K1.REMOTE_PEER_FAULT,peerId:t.id},success:null};let{statusCode:s,requestId:o,statusDesc:a}=t9.decode(i[0].slice());return s<200||s>=300?(t7.error(`Filter unsubscribe all request ${o} failed with status code ${s}: ${a}`),{failure:{error:tb.K1.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t,r;try{t=await this.getStream(e)}catch(t){return t7.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:tb.K1.REMOTE_PEER_FAULT,peerId:e.id}}}let n=t8.createSubscriberPingRequest();try{r=await tV([n.encode()],tP,t,tL,async e=>await tv(e))}catch(t){return t7.error("Failed to send ping request",t),{success:null,failure:{error:tb.K1.GENERIC_FAIL,peerId:e.id}}}if(!r||!r.length)return{success:null,failure:{error:tb.K1.REMOTE_PEER_FAULT,peerId:e.id}};let{statusCode:i,requestId:s,statusDesc:o}=t9.decode(r[0].slice());return i<200||i>=300?(t7.error(`Filter ping request ${s} failed with status code ${i}: ${o}`),{success:null,failure:{error:tb.K1.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}}class rr{proto;constructor(e){this.proto=e}static createRequest(e,t){return new rr({requestId:t6(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){let t=t0.WS.xx.decode(e);return new rr(t)}encode(){return t0.WS.xx.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}let rn=new tw.Yd("light-push");class ri extends tZ{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,rn,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return rn.error("Failed to send waku light push: payload is empty"),{query:null,error:tb.K1.EMPTY_PAYLOAD};if(!await (0,tw.eh)(e,t))return rn.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:tb.K1.SIZE_TOO_BIG};let r=await e.toProtoObj(t);if(!r)return rn.error("Failed to encode to protoMessage, aborting push"),{query:null,error:tb.K1.ENCODE_FAILED};let n=rr.createRequest(r,e.pubsubTopic);return{query:n,error:null}}catch(e){return rn.error("Failed to prepare push message",e),{query:null,error:tb.K1.GENERIC_FAIL}}}async send(e,t,r){let n,i,s;let{query:o,error:a}=await this.preparePushMessage(e,t);if(a||!o)return{success:null,failure:{error:a,peerId:r.id}};try{n=await this.getStream(r)}catch(e){return rn.error("Failed to get stream",e),{success:null,failure:{error:tb.K1.NO_STREAM_AVAILABLE,peerId:r.id}}}try{i=await tV([o.encode()],tP,n,tL,async e=>await tv(e))}catch(e){return rn.error("Failed to send waku light push request",e),{success:null,failure:{error:tb.K1.GENERIC_FAIL,peerId:r.id}}}let l=new tC;i.forEach(e=>{l.append(e)});try{s=rr.decode(l).response}catch(e){return rn.error("Failed to decode push reply",e),{success:null,failure:{error:tb.K1.DECODE_FAILED,peerId:r.id}}}return s?s.isSuccess?{success:r.id,failure:null}:(rn.error("Remote peer rejected the message: ",s.info),{success:null,failure:{error:tb.K1.REMOTE_PEER_REJECTED,peerId:r.id}}):(rn.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:tb.K1.REMOTE_PEER_FAULT,peerId:r.id}})}}let rs={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},ro=BigInt(1e6);(P=eD||(eD={})).BACKWARD="backward",P.FORWARD="forward";class ra{proto;constructor(e){this.proto=e}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){let t,r;let n=e.contentTopics.map(e=>({contentTopic:e})),i=function(e){switch(e){case eD.BACKWARD:return t0.eW.BI.Direction.BACKWARD;case eD.FORWARD:return t0.eW.BI.Direction.FORWARD;default:return t0.eW.BI.Direction.BACKWARD}}(e.pageDirection),s={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:i};return e.startTime&&(t=BigInt(e.startTime.valueOf())*ro),e.endTime&&(r=BigInt(e.endTime.valueOf())*ro),new ra({requestId:t6(),query:{pubsubTopic:e.pubsubTopic,contentFilters:n,pagingInfo:s,startTime:t,endTime:r},response:void 0})}decode(e){let t=t0.eW.e9.decode(e);return new ra(t)}encode(){return t0.eW.e9.encode(this.proto)}}var rl=t0.eW.TA.HistoryError;let rc=new tw.Yd("store");class ru extends tZ{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,rc,t.pubsubTopics,t)}async *queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.cursor;for(;;){let i;e.cursor=n;let s=ra.createQuery(e);try{i=await this.getStream(r)}catch(e){rc.error("Failed to get stream",e);break}let o=await tV([s.encode()],tP,i,tL,async e=>await tv(e)),a=new tC;o.forEach(e=>{a.append(e)});let l=s.decode(a);if(!l.response){rc.warn("Stopping pagination due to store `response` field missing");break}let c=l.response;if(c.error&&c.error!==rl.NONE)throw"History response contains an Error: "+c.error;if(!c.messages||!c.messages.length){rc.warn("Stopping pagination due to store `response.messages` field missing or empty");break}rc.error(`${c.messages.length} messages retrieved from store`),yield c.messages.map(r=>{let n=r.contentTopic;if(void 0!==n){let i=t.get(n);if(i)return i.fromProtoObj(e.pubsubTopic,{...rs,...r})}return Promise.resolve(void 0)});let u=c.pagingInfo?.cursor;if(void 0===u){rc.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;let h=c.pagingInfo?.pageSize,d=s.query?.pagingInfo?.pageSize;if(h&&d&&h<d)break}}}class rh extends Error{constructor(e){super(e),this.name="TimeoutError"}}class rd extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}let rp=e=>void 0===globalThis.DOMException?new rd(e):new DOMException(e),rf=e=>{let t=void 0===e.reason?rp("This operation was aborted."):e.reason;return t instanceof Error?t:rp(t)};function rg(e,t){let r;let{milliseconds:n,fallback:i,message:s,customTimers:o={setTimeout,clearTimeout}}=t,a=new Promise((a,l)=>{if("number"!=typeof n||1!==Math.sign(n))throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(t.signal){let{signal:e}=t;e.aborted&&l(rf(e)),e.addEventListener("abort",()=>{l(rf(e))})}if(n===Number.POSITIVE_INFINITY){e.then(a,l);return}let c=new rh;r=o.setTimeout.call(void 0,()=>{if(i){try{a(i())}catch(e){l(e)}return}"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?l(s):(c.message=s??`Promise timed out after ${n} milliseconds`,l(c))},n),(async()=>{try{a(await e)}catch(e){l(e)}})()}),l=a.finally(()=>{l.clear()});return l.clear=()=>{o.clearTimeout.call(void 0,r),r=void 0},l}let ry=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}},rm=new tw.Yd("wait-for-remote-peer");async function rb(e,t,r){if(t=t??function(e){let t=[];return e.relay&&t.push(tb.Uw.Relay),e.filter&&t.push(tb.Uw.Filter),e.store&&t.push(tb.Uw.Store),e.lightPush&&t.push(tb.Uw.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");let n=[];if(t.includes(tb.Uw.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");n.push(rv(e.relay))}if(t.includes(tb.Uw.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");n.push(rw(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(tb.Uw.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");n.push(rw(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(tb.Uw.Filter)){if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted");n.push(rw(e.filter.protocol,e.libp2p.services.metadata))}r?await rS(Promise.all(n),r,"Timed out waiting for a remote peer."):await Promise.all(n)}async function rw(e,t){let r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t){rm.info(`${r} peer found: `,n[0].id.toString());return}try{await Promise.any(n.map(e=>t.confirmOrAttemptHandshake(e.id)));return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&rm.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),rm.error(`Error waiting for handshake confirmation: ${e}`)}}rm.info(`Waiting for ${r} peer`),await new Promise(n=>{let i=s=>{s.detail?.protocols?.includes(r)&&(t?t.confirmOrAttemptHandshake(s.detail.peerId).then(()=>{e.removeLibp2pEventListener("peer:identify",i),n()}).catch(e=>{"ERR_CONNECTION_BEING_CLOSED"===e.code&&rm.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),rm.error(`Error waiting for handshake confirmation: ${e}`)}):(e.removeLibp2pEventListener("peer:identify",i),n()))};e.addLibp2pEventListener("peer:identify",i)})}async function rv(e){let t=e.getMeshPeers(),r=e.pubsubTopics;for(let n of r)for(;0==t.length;)await function(e,t,r){"function"==typeof r&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=function(e,t,r){let n;let i=new Promise((i,s)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r}).count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let o=[t].flat(),a=[],{addListener:l,removeListener:c}=ry(e),u=(...e)=>{let t=r.multiArgs?e:e[0];(!r.filter||r.filter(t))&&(a.push(t),r.count===a.length&&(n(),i(a)))},h=e=>{n(),s(e)};for(let e of(n=()=>{for(let e of o)c(e,u);for(let e of r.rejectionEvents)c(e,h)},o))l(e,u);for(let e of r.rejectionEvents)l(e,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(a)});if(i.cancel=n,"number"==typeof r.timeout){let e=rg(i,{milliseconds:r.timeout});return e.cancel=n,e}return i}(e,t,r),i=n.then(e=>e[0]);return i.cancel=n.cancel,i}(e.gossipSub,"gossipsub:heartbeat"),t=e.getMeshPeers(n)}let rE=(e,t)=>new Promise((r,n)=>setTimeout(()=>n(t),e));async function rS(e,t,r){await Promise.race([e,rE(t,r)])}let rA=(e,...t)=>{};class rI extends EventTarget{#e=new Map;constructor(){super(),rA(1/0,this)}listenerCount(e){let t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter(({callback:e})=>e!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return null==r||(r=r.filter(({once:e})=>!e),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}class rT extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}let CustomEvent=globalThis.CustomEvent??rT,r_=new tw.Yd("keep-alive");class rR{pingKeepAliveTimers;relayKeepAliveTimers;options;relay;constructor(e,t){this.pingKeepAliveTimers=new Map,this.relayKeepAliveTimers=new Map,this.options=e,this.relay=t}start(e,t,r){this.stop(e);let{pingKeepAlive:n,relayKeepAlive:i}=this.options,s=e.toString();if(0!==n){let i=setInterval(()=>{(async()=>{let i;try{try{i=await t.ping(e),r_.info(`Ping succeeded (${s})`,i)}catch(e){r_.error(`Ping failed for peer (${s}).
|
|
Next ping will be attempted in ${n} seconds.
|
|
`);return}try{await r.merge(e,{metadata:{ping:(0,tj.iY)(i.toString())}})}catch(e){r_.error("Failed to update ping",e)}}catch(e){r_.error(`Ping failed (${s})`,e)}})()},1e3*n);this.pingKeepAliveTimers.set(s,i)}let o=this.relay;if(o&&0!==i){let t=this.scheduleRelayPings(o,i,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){let t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(let e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){let n=[];for(let i of e.pubsubTopics){let s=e.getMeshPeers(i);if(!s.includes(r))continue;let o=(0,tm.Mf)({pubsubTopicShardInfo:(0,tw.Tf)(i),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),a=setInterval(()=>{r_.info("Sending Waku Relay ping message"),e.send(o,{payload:new Uint8Array([1])}).catch(e=>r_.error("Failed to send relay ping",e))},1e3*t);n.push(a)}return n}}let rC=new tw.Yd("connection-manager");class rk extends rI{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];online=!1;isConnected(){return this.online}toggleOnline(){this.online||(this.online=!0,this.dispatchEvent(new CustomEvent(tb.wh.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new CustomEvent(tb.wh.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,i,s){let o=rk.instances.get(e);return o||(o=new rk(t,r,n,i,s),rk.instances.set(e,o)),o}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),rC.info(`Dropped connection with peer ${e.toString()}`)}catch(t){rC.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){let e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map(e=>e.remotePeer),r=[],n=[],i=[],s=[],o=[],a=[];for(let t of e){let e=await this.getTagNamesForPeer(t.id);e.includes(tb.$G.BOOTSTRAP)?r.push(t):e.includes(tb.$G.PEER_EXCHANGE)?n.push(t):e.includes(tb.$G.LOCAL)&&i.push(t)}for(let e of t){let t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(tb.$G.BOOTSTRAP)?s.push(t):r.includes(tb.$G.PEER_EXCHANGE)?o.push(t):r.includes(tb.$G.LOCAL)&&a.push(t)}return{DISCOVERED:{[tb.$G.BOOTSTRAP]:r,[tb.$G.PEER_EXCHANGE]:n,[tb.$G.LOCAL]:i},CONNECTED:{[tb.$G.BOOTSTRAP]:s,[tb.$G.PEER_EXCHANGE]:o,[tb.$G.LOCAL]:a}}}constructor(e,t,r,n,i){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...i},this.keepAliveManager=new rR(t,n),this.run().then(()=>rC.info("Connection Manager is now running")).catch(e=>rC.error("Unexpected error while running service",e)),this.dialPeerStorePeers().catch(e=>rC.error("Unexpected error while dialing peer store peers",e))}async dialPeerStorePeers(){let e=await this.libp2p.peerStore.all(),t=[];for(let r of e)this.libp2p.getConnections().find(e=>e.remotePeer===r.id)||t.push(this.attemptDial(r.id));try{await Promise.all(t)}catch(e){rC.error("Unexpected error while dialing peer store peers",e)}}async run(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener()}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t<this.options.maxDialAttemptsForPeer;)try{rC.info(`Dialing peer ${e.toString()} on attempt ${t+1}`),await this.libp2p.dial(e);let r=await this.getTagNamesForPeer(e);this.libp2p.getConnections(e).forEach(e=>{e.tags=Array.from(new Set([...e.tags,...r]))}),this.dialAttemptsForPeer.set(e.toString(),-1);break}catch(r){r instanceof AggregateError?rC.error(`Error dialing peer ${e.toString()} - ${r.errors}`):rC.error(`Error dialing peer ${e.toString()} - ${r.message}`),this.dialErrorsForPeer.set(e.toString(),r),t++,this.dialAttemptsForPeer.set(e.toString(),t)}if(this.currentActiveParallelDialCount--,this.processDialQueue(),t===this.options.maxDialAttemptsForPeer)try{let t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?rC.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):rC.warn("No errors array found for AggregateError"):r=t.message,rC.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e)}catch(t){throw Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount<this.options.maxParallelDials){let e=this.pendingPeerDialQueue.shift();e&&this.attemptDial(e).catch(e=>{rC.error(e)})}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(e){if(await this.shouldDialPeer(e)){if(this.currentActiveParallelDialCount>=this.options.maxParallelDials){this.pendingPeerDialQueue.push(e);return}this.dialPeer(e).catch(t=>{rC.error(`Error dialing peer ${e.toString()} : ${t}`)})}}onEventHandlers={"peer:discovery":e=>{(async()=>{let{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){rC.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{rC.info(`Connected to peer ${e.detail.toString()}`);let t=e.detail;this.keepAliveManager.start(t,this.libp2p.services.ping,this.libp2p.peerStore);let r=(await this.getTagNamesForPeer(t)).includes(tb.$G.BOOTSTRAP);if(r){let e=this.libp2p.getConnections().filter(e=>e.tags.includes(tb.$G.BOOTSTRAP));e.length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new CustomEvent(tb.Wq.PEER_CONNECT_BOOTSTRAP,{detail:t}))}else this.dispatchEvent(new CustomEvent(tb.Wq.PEER_CONNECT_PEER_EXCHANGE,{detail:t}));this.toggleOnline()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.toggleOffline()})()}};async shouldDialPeer(e){let t=this.libp2p.getConnections(e).length>0;if(t)return rC.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){let t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return rC.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).
|
|
Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(rC.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(rC.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){let t=await this.getTagNamesForPeer(e),r=t.some(e=>e===tb.$G.BOOTSTRAP);if(!r)return!0;{let e=this.libp2p.getConnections().filter(e=>e.tags.find(e=>e===tb.$G.BOOTSTRAP)).length;if(e<this.options.maxBootstrapPeersAllowed)return!0}return!1}async dispatchDiscoveryEvent(e){let t=(await this.getTagNamesForPeer(e)).includes(tb.$G.BOOTSTRAP);this.dispatchEvent(new CustomEvent(t?tb.Wq.PEER_DISCOVERY_BOOTSTRAP:tb.Wq.PEER_DISCOVERY_PEER_EXCHANGE,{detail:e}))}async getTagNamesForPeer(e){try{let t=await this.libp2p.peerStore.get(e);return Array.from(t.tags.keys())}catch(t){return rC.error(`Failed to get peer ${e}, error: ${t}`),[]}}async isPeerTopicConfigured(e){let t=await this.getPeerShardInfo(e,this.libp2p.peerStore);if(!t)return!0;let r=(0,tw.yf)(t),n=r.some(e=>this.configuredPubsubTopics.includes(e));return n}async getPeerShardInfo(e,t){let r=await t.get(e),n=r.metadata.get("shardInfo");if(n)return(0,tw.Ix)(n)}}let rB=new tw.Yd("metadata"),rP="/vac/waku/metadata/1.0.0";class rD extends tZ{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(rP,t.components,rB,(0,tw.yf)(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(rP,e=>{this.onRequest(e)})}async onRequest(e){try{let{stream:t,connection:r}=e,n=t0.fi._.encode(this.shardInfo),i=await tV([n],tP,t,tL,async e=>await tv(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){rB.error("Error handling metadata request",e)}}async query(e){let t;let r=t0.fi.v.encode(this.shardInfo),n=await this.peerStore.get(e);if(!n)return{shardInfo:null,error:tb.K1.NO_PEER_AVAILABLE};try{t=await this.getStream(n)}catch(e){return rB.error("Failed to get stream",e),{shardInfo:null,error:tb.K1.NO_STREAM_AVAILABLE}}let i=await tV([r],tP,t,tL,async e=>await tv(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){let t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){let t=new tC;e.forEach(e=>{t.append(e)});let r=t0.fi._.decode(t);return r?{shardInfo:r,error:null}:(rB.error("Error decoding metadata response"),{shardInfo:null,error:tb.K1.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:(0,tw.kL)(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}class rN 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 rL(e,t,r){let n;if(null==t)return e;if(t.aborted)return Promise.reject(new rN(r?.errorMessage,r?.errorCode));let i=new rN(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)})])}finally{null!=n&&t.removeEventListener("abort",n)}}class rx{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=tx(),this.haveNext=tx()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=tx(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=tx(),await rL(this.readNext.promise,t?.signal,t)}}class rO extends Error{code;constructor(e,t){super(e),this.code=t}}class rM extends rO{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}class rU extends Error{code;constructor(e,t){super(e),this.code=t}}function rF(e,t={}){let r=function(e,t){let r=new rx;e.sink(r).catch(async e=>{await r.end(e)}),e.sink=async e=>{for await(let t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());let i=new tC;return{read:async(e,t)=>{let r;t?.signal?.throwIfAborted();let s=new Promise((e,n)=>{r=()=>{n(new rM("Read aborted"))},t?.signal?.addEventListener("abort",r)});try{if(null==e){let{done:e,value:t}=await Promise.race([n.next(),s]);if(!0===e)return new tC;return t}for(;i.byteLength<e;){let{value:e,done:t}=await Promise.race([n.next(),s]);if(!0===t)throw new rO("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(e)}let t=i.sublist(0,e);return i.consume(e),t}finally{null!=r&&t?.signal?.removeEventListener("abort",r)}},write:async(e,t)=>{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(i.byteLength>0){let r=e.source;e.source=async function*(){t?.yieldBytes===!1?yield i:yield*i,yield*r}()}return e}}}(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=tE.P$(t.maxDataLength));let n=t?.lengthDecoder??tE.Jx,i=t?.lengthEncoder??tE.cv;return{read:async e=>{let i=-1,s=new tC;for(;;){s.append(await r.read(1,e));try{i=n(s)}catch(e){if(e instanceof RangeError)continue;throw e}if(t?.maxLengthLength!=null&&s.byteLength>t.maxLengthLength)throw new rU("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(i>-1)break}if(t?.maxDataLength!=null&&i>t.maxDataLength)throw new rU("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(i,e)},write:async(e,t)=>{await r.write(new tC(i(e.byteLength),e),t)},writeV:async(e,t)=>{let n=new tC(...e.flatMap(e=>[i(e.byteLength),e]));await r.write(n,t)},unwrap:()=>r.unwrap()}}function rK(){let e=tx(),t=!1;return{sink:async r=>{if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){let t=await e.promise;yield*t}()}}let rV=!!globalThis.process?.env?.DUMP_SESSION_KEYS,rH=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function r$(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}let rq=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rz=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!rz)throw Error("Non little-endian hardware is not supported");function rG(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function rj(e){if("string"==typeof e)e=rG(e);else if(r$(e))e=e.slice();else throw Error(`expected Uint8Array, got ${typeof e}`);return e}let rW=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function rY(e,t){if(!r$(e))throw Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw Error(`Uint8Array length ${t} expected`)}function rQ(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),l=n?4:0,c=n?0:4;e.setUint32(t+l,o,n),e.setUint32(t+c,a,n)}function rX(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`wrong positive integer: ${e}`)}function rJ(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function rZ(e,...t){if(!(null!=e&&"object"==typeof e&&(e instanceof Uint8Array||"Uint8Array"===e.constructor.name)))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function r0(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}let r1=(e,t)=>255&e[t++]|(255&e[t++])<<8;class r2{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,rY(e=rj(e),32);let t=r1(e,0),r=r1(e,2),n=r1(e,4),i=r1(e,6),s=r1(e,8),o=r1(e,10),a=r1(e,12),l=r1(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|o<<2)&8191,this.r[7]=(o>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=r1(e,16+2*t)}process(e,t,r=!1){let{h:n,r:i}=this,s=i[0],o=i[1],a=i[2],l=i[3],c=i[4],u=i[5],h=i[6],d=i[7],p=i[8],f=i[9],g=r1(e,t+0),y=r1(e,t+2),m=r1(e,t+4),b=r1(e,t+6),w=r1(e,t+8),v=r1(e,t+10),E=r1(e,t+12),S=r1(e,t+14),A=n[0]+(8191&g),I=n[1]+((g>>>13|y<<3)&8191),T=n[2]+((y>>>10|m<<6)&8191),_=n[3]+((m>>>7|b<<9)&8191),R=n[4]+((b>>>4|w<<12)&8191),C=n[5]+(w>>>1&8191),k=n[6]+((w>>>14|v<<2)&8191),B=n[7]+((v>>>11|E<<5)&8191),P=n[8]+((E>>>8|S<<8)&8191),D=n[9]+(S>>>5|(r?0:2048)),N=0,L=0+A*s+I*(5*f)+T*(5*p)+_*(5*d)+R*(5*h);N=L>>>13,L&=8191,L+=C*(5*u)+k*(5*c)+B*(5*l)+P*(5*a)+D*(5*o),N+=L>>>13,L&=8191;let x=N+A*o+I*s+T*(5*f)+_*(5*p)+R*(5*d);N=x>>>13,x&=8191,x+=C*(5*h)+k*(5*u)+B*(5*c)+P*(5*l)+D*(5*a),N+=x>>>13,x&=8191;let O=N+A*a+I*o+T*s+_*(5*f)+R*(5*p);N=O>>>13,O&=8191,O+=C*(5*d)+k*(5*h)+B*(5*u)+P*(5*c)+D*(5*l),N+=O>>>13,O&=8191;let M=N+A*l+I*a+T*o+_*s+R*(5*f);N=M>>>13,M&=8191,M+=C*(5*p)+k*(5*d)+B*(5*h)+P*(5*u)+D*(5*c),N+=M>>>13,M&=8191;let U=N+A*c+I*l+T*a+_*o+R*s;N=U>>>13,U&=8191,U+=C*(5*f)+k*(5*p)+B*(5*d)+P*(5*h)+D*(5*u),N+=U>>>13,U&=8191;let F=N+A*u+I*c+T*l+_*a+R*o;N=F>>>13,F&=8191,F+=C*s+k*(5*f)+B*(5*p)+P*(5*d)+D*(5*h),N+=F>>>13,F&=8191;let K=N+A*h+I*u+T*c+_*l+R*a;N=K>>>13,K&=8191,K+=C*o+k*s+B*(5*f)+P*(5*p)+D*(5*d),N+=K>>>13,K&=8191;let V=N+A*d+I*h+T*u+_*c+R*l;N=V>>>13,V&=8191,V+=C*a+k*o+B*s+P*(5*f)+D*(5*p),N+=V>>>13,V&=8191;let H=N+A*p+I*d+T*h+_*u+R*c;N=H>>>13,H&=8191,H+=C*l+k*a+B*o+P*s+D*(5*f),N+=H>>>13,H&=8191;let $=N+A*f+I*p+T*d+_*h+R*u;N=$>>>13,$&=8191,$+=C*c+k*l+B*a+P*o+D*s,N+=$>>>13,$&=8191,L=8191&(N=(N=(N<<2)+N|0)+L|0),N>>>=13,x+=N,n[0]=L,n[1]=x,n[2]=O,n[3]=M,n[4]=U,n[5]=F,n[6]=K,n[7]=V,n[8]=H,n[9]=$}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+t[0];e[0]=65535&s;for(let r=1;r<8;r++)s=(e[r]+t[r]|0)+(s>>>16)|0,e[r]=65535&s}update(e){r0(this);let{buffer:t,blockLen:r}=this;e=rj(e);let n=e.length;for(let i=0;i<n;){let s=Math.min(r-this.pos,n-i);if(s===r){for(;r<=n-i;i+=r)this.process(e,i);continue}t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(e){r0(this),function(e,t){rZ(e);let r=t.outputLen;if(e.length<r)throw Error(`digestInto() expects output buffer of length at least ${r}`)}(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=r[t]>>>0,e[i++]=r[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let r3=function(e){let t=(t,r)=>e(r).update(rj(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(e=>new r2(e)),r4=rG("expand 16-byte k"),r6=rG("expand 32-byte k"),r5=rH(r4),r8=rH(r6);function r9(e,t){return e<<t|e>>>32-t}function r7(e){return e.byteOffset%4==0}let ne=4294967296-1,nt=new Uint32Array;function nr(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||!rW(t)))throw Error("options must be object or undefined");let r=Object.assign(e,t);return r}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return rX(i),rX(o),rJ(s),rJ(r),(t,a,l,c,u=0)=>{rZ(t),rZ(a),rZ(l);let h=l.length;if(c||(c=new Uint8Array(h)),rZ(c),rX(u),u<0||u>=ne)throw Error("arx: counter overflow");if(c.length<h)throw Error(`arx: output (${c.length}) is shorter than data (${h})`);let d=[],p=t.length,f,g;if(32===p)f=t.slice(),d.push(f),g=r8;else if(16===p&&r)(f=new Uint8Array(32)).set(t),f.set(t,16),g=r5,d.push(f);else throw Error(`arx: invalid 32-byte key, got length=${p}`);r7(a)||(a=a.slice(),d.push(a));let y=rH(f);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(g,y,rH(a.subarray(0,16)),y),a=a.subarray(16)}let m=16-i;if(m!==a.length)throw Error(`arx: nonce must be ${m} or 16 bytes`);if(12!==m){let e=new Uint8Array(12);e.set(a,s?0:12-a.length),a=e,d.push(a)}let b=rH(a);for(function(e,t,r,n,i,s,o,a){let l=i.length,c=new Uint8Array(64),u=rH(c),h=r7(i)&&r7(s),d=h?rH(i):nt,p=h?rH(s):nt;for(let f=0;f<l;o++){if(e(t,r,n,u,o,a),o>=ne)throw Error("arx: counter overflow");let g=Math.min(64,l-f);if(h&&64===g){let e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)p[r=e+t]=d[r]^u[t];f+=64;continue}for(let e=0,t;e<g;e++)s[t=f+e]=i[t]^c[e];f+=g}}(e,g,y,b,l,c,u,o);d.length>0;)d.pop().fill(0);return c}}function nn(e,t,r,n,i,s=20){let o=e[0],a=e[1],l=e[2],c=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=r[0],w=r[1],v=r[2],E=o,S=a,A=l,I=c,T=u,_=h,R=d,C=p,k=f,B=g,P=y,D=m,N=i,L=b,x=w,O=v;for(let e=0;e<s;e+=2)k=k+(N=r9(N^(E=E+T|0),16))|0,E=E+(T=r9(T^k,12))|0,k=k+(N=r9(N^E,8))|0,T=r9(T^k,7),B=B+(L=r9(L^(S=S+_|0),16))|0,S=S+(_=r9(_^B,12))|0,B=B+(L=r9(L^S,8))|0,_=r9(_^B,7),P=P+(x=r9(x^(A=A+R|0),16))|0,A=A+(R=r9(R^P,12))|0,P=P+(x=r9(x^A,8))|0,R=r9(R^P,7),D=D+(O=r9(O^(I=I+C|0),16))|0,I=I+(C=r9(C^D,12))|0,D=D+(O=r9(O^I,8))|0,C=r9(C^D,7),P=P+(O=r9(O^(E=E+_|0),16))|0,E=E+(_=r9(_^P,12))|0,P=P+(O=r9(O^E,8))|0,_=r9(_^P,7),D=D+(N=r9(N^(S=S+R|0),16))|0,S=S+(R=r9(R^D,12))|0,D=D+(N=r9(N^S,8))|0,R=r9(R^D,7),k=k+(L=r9(L^(A=A+C|0),16))|0,A=A+(C=r9(C^k,12))|0,k=k+(L=r9(L^A,8))|0,C=r9(C^k,7),B=B+(x=r9(x^(I=I+T|0),16))|0,I=I+(T=r9(T^B,12))|0,B=B+(x=r9(x^I,8))|0,T=r9(T^B,7);let M=0;n[M++]=o+E|0,n[M++]=a+S|0,n[M++]=l+A|0,n[M++]=c+I|0,n[M++]=u+T|0,n[M++]=h+_|0,n[M++]=d+R|0,n[M++]=p+C|0,n[M++]=f+k|0,n[M++]=g+B|0,n[M++]=y+P|0,n[M++]=m+D|0,n[M++]=i+N|0,n[M++]=b+L|0,n[M++]=w+x|0,n[M++]=v+O|0}let ni=nr(nn,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ns=nr(nn,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let i=e[0],s=e[1],o=e[2],a=e[3],l=t[0],c=t[1],u=t[2],h=t[3],d=t[4],p=t[5],f=t[6],g=t[7],y=r[0],m=r[1],b=r[2],w=r[3];for(let e=0;e<20;e+=2)d=d+(y=r9(y^(i=i+l|0),16))|0,i=i+(l=r9(l^d,12))|0,d=d+(y=r9(y^i,8))|0,l=r9(l^d,7),p=p+(m=r9(m^(s=s+c|0),16))|0,s=s+(c=r9(c^p,12))|0,p=p+(m=r9(m^s,8))|0,c=r9(c^p,7),f=f+(b=r9(b^(o=o+u|0),16))|0,o=o+(u=r9(u^f,12))|0,f=f+(b=r9(b^o,8))|0,u=r9(u^f,7),g=g+(w=r9(w^(a=a+h|0),16))|0,a=a+(h=r9(h^g,12))|0,g=g+(w=r9(w^a,8))|0,h=r9(h^g,7),f=f+(w=r9(w^(i=i+c|0),16))|0,i=i+(c=r9(c^f,12))|0,f=f+(w=r9(w^i,8))|0,c=r9(c^f,7),g=g+(y=r9(y^(s=s+u|0),16))|0,s=s+(u=r9(u^g,12))|0,g=g+(y=r9(y^s,8))|0,u=r9(u^g,7),d=d+(m=r9(m^(o=o+h|0),16))|0,o=o+(h=r9(h^d,12))|0,d=d+(m=r9(m^o,8))|0,h=r9(h^d,7),p=p+(b=r9(b^(a=a+l|0),16))|0,a=a+(l=r9(l^p,12))|0,p=p+(b=r9(b^a,8))|0,l=r9(l^p,7);let v=0;n[v++]=i,n[v++]=s,n[v++]=o,n[v++]=a,n[v++]=y,n[v++]=m,n[v++]=b,n[v++]=w},allowShortKeys:!1}),no=new Uint8Array(16),na=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(no.subarray(r))},nl=new Uint8Array(32);function nc(e,t,r,n,i){let s=e(t,r,nl),o=r3.create(s);i&&na(o,i),na(o,n);let a=new Uint8Array(16),l=rq(a);rQ(l,0,BigInt(i?i.length:0),!0),rQ(l,8,BigInt(n.length),!0),o.update(a);let c=o.digest();return s.fill(0),c}let nu=e=>(t,r,n)=>(rY(t,32),rY(r),{encrypt:(i,s)=>{let o=i.length,a=o+16;s?rY(s,a):s=new Uint8Array(a),e(t,r,i,s,1);let l=nc(e,t,r,s.subarray(0,-16),n);return s.set(l,o),s},decrypt:(i,s)=>{let o=i.length,a=o-16;if(o<16)throw Error("encrypted data must be at least 16 bytes");s?rY(s,a):s=new Uint8Array(a);let l=i.subarray(0,-16),c=i.subarray(-16),u=nc(e,t,r,l,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(c,u))throw Error("invalid tag");return e(t,r,l,s,1),s}}),nh=(Object.assign(D=nu(ni),{blockSize:64,nonceLength:12,tagLength:16}),D);nu(ns);var nd=r(8289);let np=BigInt(4294967296-1),nf=BigInt(32);function ng(e,t=!1){return t?{h:Number(e&np),l:Number(e>>nf&np)}:{h:0|Number(e>>nf&np),l:0|Number(e&np)}}var ny={fromBig:ng,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:s,l:o}=ng(e[i],t);[r[i],n[i]]=[s,o]}return[r,n]},toBig:(e,t)=>BigInt(e>>>0)<<nf|BigInt(t>>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<<r|t>>>32-r,rotlSL:(e,t,r)=>t<<r|e>>>32-r,rotlBH:(e,t,r)=>t<<r-32|e>>>64-r,rotlBL:(e,t,r)=>e<<r-32|t>>>64-r,add:function(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/4294967296|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/4294967296|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/4294967296|0)|0,add5H:(e,t,r,n,i,s)=>t+r+n+i+s+(e/4294967296|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},nm=r(2305);let[nb,nw]=ny.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(e=>BigInt(e))),nv=new Uint32Array(80),nE=new Uint32Array(80);class nS extends nd.VR{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:r,Bl:n,Ch:i,Cl:s,Dh:o,Dl:a,Eh:l,El:c,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,i,s,o,a,l,c,u,h,d,p,f,g]}set(e,t,r,n,i,s,o,a,l,c,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|o,this.Dl=0|a,this.Eh=0|l,this.El=0|c,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)nv[r]=e.getUint32(t),nE[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|nv[e-15],r=0|nE[e-15],n=ny.rotrSH(t,r,1)^ny.rotrSH(t,r,8)^ny.shrSH(t,r,7),i=ny.rotrSL(t,r,1)^ny.rotrSL(t,r,8)^ny.shrSL(t,r,7),s=0|nv[e-2],o=0|nE[e-2],a=ny.rotrSH(s,o,19)^ny.rotrBH(s,o,61)^ny.shrSH(s,o,6),l=ny.rotrSL(s,o,19)^ny.rotrBL(s,o,61)^ny.shrSL(s,o,6),c=ny.add4L(i,l,nE[e-7],nE[e-16]),u=ny.add4H(c,n,a,nv[e-7],nv[e-16]);nv[e]=0|u,nE[e]=0|c}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:o,Cl:a,Dh:l,Dl:c,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){let t=ny.rotrSH(u,h,14)^ny.rotrSH(u,h,18)^ny.rotrBH(u,h,41),b=ny.rotrSL(u,h,14)^ny.rotrSL(u,h,18)^ny.rotrBL(u,h,41),w=u&d^~u&f,v=h&p^~h&g,E=ny.add5L(m,b,v,nw[e],nE[e]),S=ny.add5H(E,y,t,w,nb[e],nv[e]),A=0|E,I=ny.rotrSH(r,n,28)^ny.rotrBH(r,n,34)^ny.rotrBH(r,n,39),T=ny.rotrSL(r,n,28)^ny.rotrBL(r,n,34)^ny.rotrBL(r,n,39),_=r&i^r&o^i&o,R=n&s^n&a^s&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=ny.add(0|l,0|c,0|S,0|A)),l=0|o,c=0|a,o=0|i,a=0|s,i=0|r,s=0|n;let C=ny.add3L(A,T,R);r=ny.add3H(C,S,I,_),n=0|C}({h:r,l:n}=ny.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=ny.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=ny.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:l,l:c}=ny.add(0|this.Dh,0|this.Dl,0|l,0|c)),({h:u,l:h}=ny.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=ny.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=ny.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=ny.add(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,i,s,o,a,l,c,u,h,d,p,f,g,y,m)}roundClean(){nv.fill(0),nE.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)}}let nA=(0,nm.hE)(()=>new nS);BigInt(0);let nI=BigInt(1),nT=BigInt(2);function n_(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function nR(e){if(!n_(e))throw Error("Uint8Array expected")}let nC=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function nk(e){nR(e);let t="";for(let r=0;r<e.length;r++)t+=nC[e[r]];return t}function nB(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}let nP={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function nD(e){return e>=nP._0&&e<=nP._9?e-nP._0:e>=nP._A&&e<=nP._F?e-(nP._A-10):e>=nP._a&&e<=nP._f?e-(nP._a-10):void 0}function nN(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);let t=e.length,r=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){let r=nD(e.charCodeAt(i)),s=nD(e.charCodeAt(i+1));if(void 0===r||void 0===s){let t=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+i)}n[t]=16*r+s}return n}function nL(e){return nB(nk(e))}function nx(e){return nR(e),nB(nk(Uint8Array.from(e).reverse()))}function nO(e,t){return nN(e.toString(16).padStart(2*t,"0"))}function nM(e,t){return nO(e,t).reverse()}function nU(e,t,r){let n;if("string"==typeof t)try{n=nN(t)}catch(r){throw Error(`${e} must be valid hex string, got "${t}". Cause: ${r}`)}else if(n_(t))n=Uint8Array.from(t);else throw Error(`${e} must be hex string or Uint8Array`);let i=n.length;if("number"==typeof r&&i!==r)throw Error(`${e} expected ${r} bytes, got ${i}`);return n}function nF(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];nR(n),t+=n.length}let r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}let nK=e=>(nT<<BigInt(e-1))-nI,nV=e=>new Uint8Array(e),nH=e=>Uint8Array.from(e);function n$(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");let n=nV(e),i=nV(e),s=0,o=()=>{n.fill(1),i.fill(0),s=0},a=(...e)=>r(i,n,...e),l=(e=nV())=>{i=a(nH([0]),e),n=a(),0!==e.length&&(i=a(nH([1]),e),n=a())},c=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let e=0,r=[];for(;e<t;){n=a();let t=n.slice();r.push(t),e+=n.length}return nF(...r)};return(e,t)=>{let r;for(o(),l(e);!(r=t(c()));)l();return o(),r}}let nq={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||n_(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function nz(e,t,r={}){let n=(t,r,n)=>{let i=nq[r];if("function"!=typeof i)throw Error(`Invalid validator "${r}", expected function`);let s=e[t];if((!n||void 0!==s)&&!i(s,e))throw Error(`Invalid param ${String(t)}=${s} (${typeof s}), expected ${r}`)};for(let[e,r]of Object.entries(t))n(e,r,!1);for(let[e,t]of Object.entries(r))n(e,t,!0);return e}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let nG=BigInt(0),nj=BigInt(1),nW=BigInt(2),nY=BigInt(3),nQ=BigInt(4),nX=BigInt(5),nJ=BigInt(8);function nZ(e,t){let r=e%t;return r>=nG?r:t+r}function n0(e,t,r){if(r<=nG||t<nG)throw Error("Expected power/modulo > 0");if(r===nj)return nG;let n=nj;for(;t>nG;)t&nj&&(n=n*e%r),e=e*e%r,t>>=nj;return n}function n1(e,t,r){let n=e;for(;t-- >nG;)n*=n,n%=r;return n}function n2(e,t){if(e===nG||t<=nG)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=nZ(e,t),n=t,i=nG,s=nj,o=nj,a=nG;for(;r!==nG;){let e=n/r,t=n%r,l=i-o*e,c=s-a*e;n=r,r=t,i=o,s=a,o=l,a=c}let l=n;if(l!==nj)throw Error("invert: does not exist");return nZ(i,t)}BigInt(9),BigInt(16);let n3=(e,t)=>(nZ(e,t)&nj)===nj,n4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function n6(e,t){let r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function n5(e,t,r=!1,n={}){if(e<=nG)throw Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:s}=n6(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");let o=function(e){if(e%nQ===nY){let t=(e+nj)/nQ;return function(e,r){let n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}if(e%nJ===nX){let t=(e-nX)/nJ;return function(e,r){let n=e.mul(r,nW),i=e.pow(n,t),s=e.mul(r,i),o=e.mul(e.mul(s,nW),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),r))throw Error("Cannot find square root");return a}}return function(e){let t,r,n;let i=(e-nj)/nW;for(t=e-nj,r=0;t%nW===nG;t/=nW,r++);for(n=nW;n<e&&n0(n,i,e)!==e-nj;n++);if(1===r){let t=(e+nj)/nQ;return function(e,r){let n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw Error("Cannot find square root");return n}}let s=(t+nj)/nW;return function(e,o){if(e.pow(o,i)===e.neg(e.ONE))throw Error("Cannot find square root");let a=r,l=e.pow(e.mul(e.ONE,n),t),c=e.pow(o,s),u=e.pow(o,t);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(u);t<a&&!e.eql(r,e.ONE);t++)r=e.sqr(r);let r=e.pow(l,nj<<BigInt(a-t-1));l=e.sqr(r),c=e.mul(c,r),u=e.mul(u,l),a=t}return c}}(e)}(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:nK(i),ZERO:nG,ONE:nj,create:t=>nZ(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error(`Invalid field element: expected bigint, got ${typeof t}`);return nG<=t&&t<e},is0:e=>e===nG,isOdd:e=>(e&nj)===nj,neg:t=>nZ(-t,e),eql:(e,t)=>e===t,sqr:t=>nZ(t*t,e),add:(t,r)=>nZ(t+r,e),sub:(t,r)=>nZ(t-r,e),mul:(t,r)=>nZ(t*r,e),pow:(e,t)=>(function(e,t,r){if(r<nG)throw Error("Expected power > 0");if(r===nG)return e.ONE;if(r===nj)return t;let n=e.ONE,i=t;for(;r>nG;)r&nj&&(n=e.mul(n,i)),i=e.sqr(i),r>>=nj;return n})(a,e,t),div:(t,r)=>nZ(t*n2(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>n2(t,e),sqrt:n.sqrt||(e=>o(a,e)),invertBatch:e=>(function(e,t){let r=Array(t.length),n=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),i=e.inv(n);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),i),r})(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?nM(e,s):nO(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?nx(e):nL(e)}});return Object.freeze(a)}function n8(e){if("bigint"!=typeof e)throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function n9(e){let t=n8(e);return t+Math.ceil(t/2)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let n7=BigInt(0),ie=BigInt(1);function it(e,t){let r=(e,t)=>{let r=t.negate();return e?r:t},n=e=>({windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,i=t;for(;r>n7;)r&ie&&(n=n.add(i)),i=i.double(),r>>=ie;return n},precomputeWindow(e,t){let{windows:r,windowSize:i}=n(t),s=[],o=e,a=o;for(let e=0;e<r;e++){a=o,s.push(a);for(let e=1;e<i;e++)a=a.add(o),s.push(a);o=a.double()}return s},wNAF(t,i,s){let{windows:o,windowSize:a}=n(t),l=e.ZERO,c=e.BASE,u=BigInt(2**t-1),h=2**t,d=BigInt(t);for(let e=0;e<o;e++){let t=e*a,n=Number(s&u);s>>=d,n>a&&(n-=h,s+=ie);let o=t+Math.abs(n)-1,p=e%2!=0,f=n<0;0===n?c=c.add(r(p,i[t])):l=l.add(r(f,i[o]))}return{p:l,f:c}},wNAFCached(e,t,r,n){let i=e._WINDOW_SIZE||1,s=t.get(e);return s||(s=this.precomputeWindow(e,i),1!==i&&t.set(e,n(s))),this.wNAF(i,s,r)}}}function ir(e){return!function(e){let t=n4.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});nz(e,t)}(e.Fp),nz(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...n6(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let ii=BigInt(0),is=BigInt(1),io=BigInt(2),ia=BigInt(8),il={zip215:!0},ic=BigInt(0),iu=BigInt(1),ih=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),id=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ip=BigInt(0),ig=BigInt(1),iy=BigInt(2),im=BigInt(5),ib=BigInt(10),iw=BigInt(20),iv=BigInt(40),iE=BigInt(80);function iS(e){let t=e*e%ih,r=t*e%ih,n=n1(r,iy,ih)*r%ih,i=n1(n,ig,ih)*e%ih,s=n1(i,im,ih)*i%ih,o=n1(s,ib,ih)*s%ih,a=n1(o,iw,ih)*o%ih,l=n1(a,iv,ih)*a%ih,c=n1(l,iE,ih)*l%ih,u=n1(c,iE,ih)*l%ih,h=n1(u,ib,ih)*s%ih,d=n1(h,iy,ih)*e%ih;return{pow_p_5_8:d,b2:r}}function iA(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function iI(e,t){let r=nZ(t*t*t,ih),n=nZ(r*r*t,ih),i=iS(e*n).pow_p_5_8,s=nZ(e*r*i,ih),o=nZ(t*s*s,ih),a=s,l=nZ(s*id,ih),c=o===e,u=o===nZ(-e,ih),h=o===nZ(-e*id,ih);return c&&(s=a),(u||h)&&(s=l),n3(s,ih)&&(s=nZ(-s,ih)),{isValid:c||u,value:s}}let iT=n5(ih,void 0,!0),i_={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:iT,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:nA,randomBytes:nm.O6,adjustScalarBytes:iA,uvRatio:iI},iR=function(e){let t=function(e){let t=ir(e);return nz(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n:n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:l}=t,c=io<<BigInt(8*a)-is,u=r.create,h=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:ii}}}),d=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,r)=>{if(t.length||r)throw Error("Contexts/pre-hash are not supported");return e}),f=e=>"bigint"==typeof e&&ii<e,g=(e,t)=>f(e)&&f(t)&&e<t,y=e=>e===ii||g(e,c);function m(e,t){if(g(e,t))return e;throw Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function b(e){return e===ii?e:m(e,n)}let w=new Map;function v(e){if(!(e instanceof E))throw Error("ExtendedPoint expected")}class E{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!y(e))throw Error("x required");if(!y(t))throw Error("y required");if(!y(r))throw Error("z required");if(!y(n))throw Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw Error("extended point not allowed");let{x:t,y:r}=e||{};if(!y(t)||!y(r))throw Error("invalid affine point");return new E(t,r,is,u(t*r))}static normalizeZ(e){let t=r.invertBatch(e.map(e=>e.ez));return e.map((e,r)=>e.toAffine(t[r])).map(E.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,w.delete(this)}assertValidity(){let{a:e,d:r}=t;if(this.is0())throw Error("bad point: ZERO");let{ex:n,ey:i,ez:s,et:o}=this,a=u(n*n),l=u(i*i),c=u(s*s),h=u(c*c),d=u(a*e),p=u(c*u(d+l)),f=u(h+u(r*u(a*l)));if(p!==f)throw Error("bad point: equation left != right (1)");let g=u(n*i),y=u(s*o);if(g!==y)throw Error("bad point: equation left != right (2)")}equals(e){v(e);let{ex:t,ey:r,ez:n}=this,{ex:i,ey:s,ez:o}=e,a=u(t*o),l=u(i*n),c=u(r*o),h=u(s*n);return a===l&&c===h}is0(){return this.equals(E.ZERO)}negate(){return new E(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:e}=t,{ex:r,ey:n,ez:i}=this,s=u(r*r),o=u(n*n),a=u(io*u(i*i)),l=u(e*s),c=r+n,h=u(u(c*c)-s-o),d=l+o,p=d-a,f=l-o,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new E(g,y,b,m)}add(e){v(e);let{a:r,d:n}=t,{ex:i,ey:s,ez:o,et:a}=this,{ex:l,ey:c,ez:h,et:d}=e;if(r===BigInt(-1)){let e=u((s-i)*(c+l)),t=u((s+i)*(c-l)),r=u(t-e);if(r===ii)return this.double();let n=u(o*io*d),p=u(a*io*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),w=u(f*y),v=u(r*g);return new E(m,b,v,w)}let p=u(i*l),f=u(s*c),g=u(a*n*d),y=u(o*h),m=u((i+s)*(l+c)-p-f),b=y-g,w=y+g,S=u(f-r*p),A=u(m*b),I=u(w*S),T=u(m*S),_=u(b*w);return new E(A,I,_,T)}subtract(e){return this.add(e.negate())}wNAF(e){return I.wNAFCached(this,w,e,E.normalizeZ)}multiply(e){let{p:t,f:r}=this.wNAF(m(e,n));return E.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=b(e);return t===ii?A:this.equals(A)||t===is?this:this.equals(S)?this.wNAF(t).p:I.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(l).is0()}isTorsionFree(){return I.unsafeLadder(this,n).is0()}toAffine(e){let{ex:t,ey:n,ez:i}=this,s=this.is0();null==e&&(e=s?ia:r.inv(i));let o=u(t*e),a=u(n*e),l=u(i*e);if(s)return{x:ii,y:is};if(l!==is)throw Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){let{h:e}=t;return e===is?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){let{d:i,a:s}=t,o=r.BYTES;e=nU("pointHex",e,o);let a=e.slice(),l=e[o-1];a[o-1]=-129&l;let d=nx(a);d===ii||(n?m(d,c):m(d,r.ORDER));let p=u(d*d),f=u(p-is),g=u(i*p-s),{isValid:y,value:b}=h(f,g);if(!y)throw Error("Point.fromHex: invalid y coordinate");let w=(b&is)===is,v=(128&l)!=0;if(!n&&b===ii&&v)throw Error("Point.fromHex: x=0 and x_0=1");return v!==w&&(b=u(-b)),E.fromAffine({x:b,y:d})}static fromPrivateKey(e){return T(e).point}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=nM(t,r.BYTES);return n[n.length-1]|=e&is?128:0,n}toHex(){return nk(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,is,u(t.Gx*t.Gy)),E.ZERO=new E(ii,is,is,ii);let{BASE:S,ZERO:A}=E,I=it(E,8*a);function T(e){e=nU("private key",e,a);let t=nU("hashed private key",s(e),2*a),r=d(t.slice(0,a)),i=t.slice(a,2*a),o=nZ(nx(r),n),l=S.multiply(o),c=l.toRawBytes();return{head:r,prefix:i,scalar:o,point:l,pointBytes:c}}function _(e=new Uint8Array,...t){let r=nF(...t);return nZ(nx(s(p(r,nU("context",e),!!i))),n)}return S._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return T(e).pointBytes},sign:function(e,t,s={}){e=nU("message",e),i&&(e=i(e));let{prefix:o,scalar:l,pointBytes:c}=T(t),u=_(s.context,o,e),h=S.multiply(u).toRawBytes(),d=_(s.context,h,c,e),p=nZ(u+d*l,n);b(p);let f=nF(h,nM(p,r.BYTES));return nU("result",f,2*a)},verify:function(e,t,n,s=il){let o,a,l;let{context:c,zip215:u}=s,h=r.BYTES;e=nU("signature",e,2*h),t=nU("message",t),i&&(t=i(t));let d=nx(e.slice(h,2*h));try{o=E.fromHex(n,u),a=E.fromHex(e.slice(0,h),u),l=S.multiplyUnsafe(d)}catch(e){return!1}if(!u&&o.isSmallOrder())return!1;let p=_(c,a.toRawBytes(),o.toRawBytes(),t),f=a.add(o.multiplyUnsafe(p));return f.subtract(l).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=E.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(i_);({...i_});let iC=function(e){let t=(nz(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})),{P:r}=t,n=e=>nZ(e,r),i=t.montgomeryBits,s=Math.ceil(i/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>n0(e,r-BigInt(2),r));function c(e,t,r){let i=n(e*(t-r));return[t=n(t-i),r=n(r+i)]}function u(e){if("bigint"==typeof e&&ic<=e&&e<r)return e;throw Error("Expected valid scalar 0 < scalar < CURVE.P")}let h=(t.a-BigInt(2))/BigInt(4);function d(e,t){let r=function(e){let t=nU("u coordinate",e,s);return 32===o&&(t[31]&=127),nx(t)}(t),d=function(e){let t=nU("scalar",e),r=t.length;if(r!==s&&r!==o)throw Error(`Expected ${s} or ${o} bytes, got ${r}`);return nx(a(t))}(e),p=function(e,t){let r;let s=u(e),o=u(t),a=iu,d=ic,p=s,f=iu,g=ic;for(let e=BigInt(i-1);e>=ic;e--){let t=o>>e&iu;g^=t,a=(r=c(g,a,p))[0],p=r[1],d=(r=c(g,d,f))[0],f=r[1],g=t;let i=a+d,l=n(i*i),u=a-d,y=n(u*u),m=l-y,b=p+f,w=p-f,v=n(w*i),E=n(b*u),S=v+E,A=v-E;p=n(S*S),f=n(s*n(A*A)),a=n(l*y),d=n(m*(l+n(h*m)))}a=(r=c(g,a,p))[0],p=r[1],d=(r=c(g,d,f))[0],f=r[1];let y=l(d);return n(a*y)}(r,d);if(p===ic)throw Error("Invalid private or public key received");return nM(n(p),s)}let p=nM(n(t.Gu),s);function f(e){return d(e,p)}return{scalarMult:d,scalarMultBase:f,getSharedSecret:(e,t)=>d(e,t),getPublicKey:e=>f(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:p}}({P:ih,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{let{pow_p_5_8:t,b2:r}=iS(e);return nZ(n1(t,BigInt(3),ih)*r,ih)},adjustScalarBytes:iA,randomBytes:nm.O6}),ik=(iT.ORDER+BigInt(3))/BigInt(8);function iB(e){if(!(e instanceof iF))throw Error("RistrettoPoint expected")}iT.pow(iy,ik),iT.sqrt(iT.neg(iT.ONE)),iT.ORDER,BigInt(5),BigInt(8),BigInt(486662),function(e,t){if(!e.isOdd)throw Error("Field doesn't have isOdd");let r=e.sqrt(t);e.isOdd(r)&&e.neg(r)}(iT,iT.neg(BigInt(486664)));let iP=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),iD=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),iN=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),iL=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ix=e=>iI(ig,e),iO=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),iM=e=>iR.CURVE.Fp.create(bytesToNumberLE(e)&iO);function iU(e){let{d:t}=iR.CURVE,r=iR.CURVE.Fp.ORDER,n=iR.CURVE.Fp.create,i=n(null*e*e),s=n((i+ig)*iN),o=BigInt(-1),a=n((o-t*i)*n(i+t)),{isValid:l,value:c}=iI(s,a),u=n(c*e);isNegativeLE(u,r)||(u=n(-u)),l||(c=u),l||(o=i);let h=n(o*(i-ig)*iL-a),d=c*c,p=n((c+c)*a),f=n(h*iP),g=n(ig-d),y=n(ig+d);return new iR.ExtendedPoint(n(p*y),n(g*f),n(f*y),n(p*g))}class iF{constructor(e){this.ep=e}static fromAffine(e){return new iF(iR.ExtendedPoint.fromAffine(e))}static hashToCurve(e){e=ensureBytes("ristrettoHash",e,64);let t=iM(e.slice(0,32)),r=iU(t),n=iM(e.slice(32,64)),i=iU(n);return new iF(r.add(i))}static fromHex(e){e=ensureBytes("ristrettoHex",e,32);let{a:t,d:r}=iR.CURVE,n=iR.CURVE.Fp.ORDER,i=iR.CURVE.Fp.create,s="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=iM(e);if(!equalBytes(numberToBytesLE(o,32),e)||isNegativeLE(o,n))throw Error(s);let a=i(o*o),l=i(ig+t*a),c=i(ig-t*a),u=i(l*l),h=i(c*c),d=i(t*r*u-h),{isValid:p,value:f}=ix(i(d*h)),g=i(f*c),y=i(f*g*d),m=i((o+o)*g);isNegativeLE(m,n)&&(m=i(-m));let b=i(l*y),w=i(m*b);if(!p||isNegativeLE(w,n)||b===ip)throw Error(s);return new iF(new iR.ExtendedPoint(m,b,ig,w))}toRawBytes(){let e,{ex:t,ey:r,ez:n,et:i}=this.ep,s=iR.CURVE.Fp.ORDER,o=iR.CURVE.Fp.create,a=o(o(n+r)*o(n-r)),l=o(t*r),c=o(l*l),{value:u}=ix(o(a*c)),h=o(u*a),d=o(u*l),p=o(h*d*i);if(isNegativeLE(i*p,s)){let n=o(null*r),i=o(null*t);t=n,r=i,e=o(h*iD)}else e=d;isNegativeLE(t*p,s)&&(r=o(-r));let f=o((n-r)*e);return isNegativeLE(f,s)&&(f=o(-f)),numberToBytesLE(f,32)}toHex(){return bytesToHex(this.toRawBytes())}toString(){return this.toHex()}equals(e){iB(e);let{ex:t,ey:r}=this.ep,{ex:n,ey:i}=e.ep,s=iR.CURVE.Fp.create,o=s(t*i)===s(r*n),a=s(r*i)===s(t*n);return o||a}add(e){return iB(e),new iF(this.ep.add(e.ep))}subtract(e){return iB(e),new iF(this.ep.subtract(e.ep))}multiply(e){return new iF(this.ep.multiply(e))}multiplyUnsafe(e){return new iF(this.ep.multiplyUnsafe(e))}double(){return new iF(this.ep.double())}negate(){return new iF(this.ep.negate())}}var iK=r(5493);class iV extends nm.kb{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,(0,iK.vp)(e);let r=(0,nm.O0)(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),i.fill(0)}update(e){return(0,iK.Gg)(this),this.iHash.update(e),this}digestInto(e){(0,iK.Gg)(this),(0,iK.aI)(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:r,finished:n,destroyed:i,blockLen:s,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=s,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let iH=(e,t,r)=>new iV(e,t).update(r).digest();iH.create=(e,t)=>new iV(e,t);let i$=new Uint8Array([0]),iq=new Uint8Array;var iz=r(9802);let iG={hashSHA256:e=>(0,iz.J)(e.subarray()),getHKDF(e,t){var r,n;let i=(r=iz.J,n=e,(0,iK.vp)(r),void 0===n&&(n=new Uint8Array(r.outputLen)),iH(r,(0,nm.O0)(n),(0,nm.O0)(t))),s=function(e,t,r,n=32){if((0,iK.vp)(e),(0,iK.Rx)(n),n>255*e.outputLen)throw Error("Length should be <= 255*HashLen");let i=Math.ceil(n/e.outputLen);void 0===r&&(r=iq);let s=new Uint8Array(i*e.outputLen),o=iH.create(e,t),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let t=0;t<i;t++)i$[0]=t+1,a.update(0===t?iq:l).update(r).update(i$).digestInto(l),s.set(l,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),i$.fill(0),s.slice(0,n)}(iz.J,i,void 0,96),o=s.subarray(0,32),a=s.subarray(32,64),l=s.subarray(64,96);return[o,a,l]},generateX25519KeyPair(){let e=iC.utils.randomPrivateKey(),t=iC.getPublicKey(e);return{publicKey:t,privateKey:e}},generateX25519KeyPairFromSeed(e){let t=iC.getPublicKey(e);return{publicKey:t,privateKey:e}},generateX25519SharedKey:(e,t)=>iC.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>nh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>nh(n,t,r).decrypt(e.subarray(),i)},ij=e=>{let t=(0,tS.E)(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};ij.bytes=2;let iW=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};iW.bytes=2;class iY extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=iY.code}static code="ERR_UNEXPECTED_PEER"}class iQ extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=iQ.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}r(9642),r(6204);class iX extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=iX.code,this.type=iX.type}static code="ABORT_ERR";static type="aborted"}class iJ extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class iZ extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}let i0="ERR_TIMEOUT";var i1=r(2595),i2=r(2223),i3=r(9029),i4=r(9137),i6=r(1818);r(2366),r(4196);var i5=r(7519);function i8(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=0===r[0]?r.subarray(1):r,null!=t){if(r.length>t)throw Error("byte array longer than desired length");r=tA([new Uint8Array(t-r.length),r])}return(0,i5.B)(r,"base64url")}function i9(e){let t=function(e,t){let r=(0,i2.m)(e,"base64urlpad");if(null!=t){if(r.length>t)throw Error("byte array longer than desired length");r=tA([new Uint8Array(t-r.length),r])}return r}(e);return new i1.jsbn.BigInteger((0,i5.B)(t,"base16"),16)}function i7(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}function se(e,t){let r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}var st=r(9678),sr={get(e=globalThis){let t=e.crypto;if(null==t||null==t.subtle)throw Object.assign(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 t}};let sn={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function si(e,t){let r=function(e){let t=e?.algorithm??"AES-GCM",r=e?.keyLength??16,n=e?.nonceLength??12,i=e?.digest??"SHA-256",s=e?.saltLength??16,o=e?.iterations??32767,a=sr.get();async function l(e,l){let c;let u=a.getRandomValues(new Uint8Array(s)),h=a.getRandomValues(new Uint8Array(n)),d={name:t,iv:h};if("string"==typeof l&&(l=(0,i2.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",sn,{name:"AES-GCM"},!0,["encrypt"]);try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}catch{c=await a.subtle.importKey("jwk",sn,{name:"AES-GCM"},!0,["encrypt"])}}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}let p=await a.subtle.encrypt(d,c,e);return tA([u,d.iv,new Uint8Array(p)])}async function c(e,l){let c;let u=e.subarray(0,s),h=e.subarray(s,s+n),d=e.subarray(s+n);if("string"==typeof l&&(l=(0,i2.m)(l)),0===l.length)try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}catch{c=await a.subtle.importKey("jwk",sn,{name:"AES-GCM"},!0,["decrypt"])}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}let p=await a.subtle.decrypt({name:t,iv:h},c,d);return new Uint8Array(p)}return r*=8,{encrypt:l,decrypt:c}}(),n=await r.encrypt(e,t);return st.base64.encode(n)}var ss=r(6995);(N=eN||(eN={})).RSA="RSA",N.Ed25519="Ed25519",N.Secp256k1="Secp256k1",(L=eL||(eL={}))[L.RSA=0]="RSA",L[L.Ed25519=1]="Ed25519",L[L.Secp256k1=2]="Secp256k1",(eN||(eN={})).codec=()=>(0,ss.Ji)(eL),(x=ex||(ex={})).codec=()=>(null==s&&(s=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eN.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.Type=eN.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),s),x.encode=e=>(0,ss.LE)(e,x.codec()),x.decode=e=>(0,ss.C6)(e,x.codec()),(O=eO||(eO={})).codec=()=>(null==o&&(o=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eN.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.Type=eN.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),o),O.encode=e=>(0,ss.LE)(e,O.codec()),O.decode=e=>(0,ss.C6)(e,O.codec());class so{_key;constructor(e){this._key=sd(e,32)}verify(e,t){var r;return r=this._key,iR.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return ex.encode({Type:eN.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return i7(e)?e.then(({bytes:e})=>e):e.bytes}}class sa{_key;_publicKey;constructor(e,t){this._key=sd(e,64),this._publicKey=sd(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return iR.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new so(this._publicKey)}marshal(){return this._key}get bytes(){return eO.encode({Type:eN.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}async hash(){let e;let t=i6.sha256.digest(this.bytes);return i7(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=i4.identity.digest(this.public.bytes);return i3.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return si(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function sl(e){if(e.length>64){e=sd(e,96);let t=e.subarray(0,64),r=e.subarray(64,e.length);return new sa(t,r)}e=sd(e,64);let t=e.subarray(0,64),r=e.subarray(32);return new sa(t,r)}function sc(e){return new so(e=sd(e,32))}async function su(){let{privateKey:e,publicKey:t}=function(){let e=iR.utils.randomPrivateKey(),t=iR.getPublicKey(e),r=se(e,t);return{privateKey:r,publicKey:t}}();return new sa(e,t)}async function sh(e){let{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=iR.getPublicKey(e),r=se(e,t);return{privateKey:r,publicKey:t}}(e);return new sa(t,r)}function sd(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new iJ(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function sp(e,t){return t.map(t=>i9(e[t]))}async function sf(e){let t=await sr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await sb(t);return{privateKey:r[0],publicKey:r[1]}}async function sg(e){let t=await sr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),r=[t,await sw(e)],n=await sb({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function sy(e,t){let r=await sr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await sr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function sm(e,t,r){let n=await sr.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return sr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function sb(e){if(null==e.privateKey||null==e.publicKey)throw new iJ("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([sr.get().subtle.exportKey("jwk",e.privateKey),sr.get().subtle.exportKey("jwk",e.publicKey)])}async function sw(e){return sr.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function sv(e,t,r,n){let i=t?i1.pki.setRsaPublicKey(...sp(e,["n","e"])):i1.pki.setRsaPrivateKey(...sp(e,["n","e","d","p","q","dp","dq","qi"])),s=(0,i5.B)(r instanceof Uint8Array?r:r.subarray(),"ascii"),o=n(s,i);return(0,i2.m)(o,"ascii")}function sE(e){if("RSA"!==e.kty)throw new iJ("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new iJ("invalid key modulus","ERR_INVALID_KEY_MODULUS");let t=(0,i2.m)(e.n,"base64url");return 8*t.length}r(8439),r(411);let sS=8192;class sA{_key;constructor(e){this._key=e}verify(e,t){return sm(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new iJ("JWK was missing components","ERR_INVALID_PARAMETERS");let t=i1.pki.publicKeyToAsn1({n:i9(e.n),e:i9(e.e)});return(0,i2.m)(i1.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return ex.encode({Type:eN.RSA,Data:this.marshal()}).subarray()}encrypt(e){return sv(this._key,!0,e,(e,t)=>t.encrypt(e))}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return i7(e)?e.then(({bytes:e})=>e):e.bytes}}class sI{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(e)||e<=0)throw new iJ("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,nm.O6)(e)}(16)}sign(e){return sy(this._key,e)}get public(){if(null==this._publicKey)throw new iJ("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new sA(this._publicKey)}decrypt(e){return sv(this._key,!1,e,(e,t)=>t.decrypt(e))}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new iJ("JWK was missing components","ERR_INVALID_PARAMETERS");let t=i1.pki.privateKeyToAsn1({n:i9(e.n),e:i9(e.e),d:i9(e.d),p:i9(e.p),q:i9(e.q),dP:i9(e.dp),dQ:i9(e.dq),qInv:i9(e.qi)});return(0,i2.m)(i1.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return eO.encode({Type:eN.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return i7(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,i5.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){let t=new i1.util.ByteBuffer(this.marshal()),r=i1.asn1.fromDer(t),n=i1.pki.privateKeyFromAsn1(r);return i1.pki.encryptRsaPrivateKey(n,e,{algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"})}if("libp2p-key"===t)return si(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function sT(e){let t=function(e){let t=i1.asn1.fromDer((0,i5.B)(e,"ascii")),r=i1.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:i8(r.n),e:i8(r.e),d:i8(r.d),p:i8(r.p),q:i8(r.q),dp:i8(r.dP),dq:i8(r.dQ),qi:i8(r.qInv),alg:"RS256"}}(e);if(sE(t)>sS)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await sg(t);return new sI(r.privateKey,r.publicKey)}function s_(e){let t=function(e){let t=i1.asn1.fromDer((0,i5.B)(e,"ascii")),r=i1.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:i8(r.n),e:i8(r.e)}}(e);if(sE(t)>sS)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new sA(t)}async function sR(e){if(sE(e)>sS)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await sg(e);return new sI(t.privateKey,t.publicKey)}async function sC(e){if(e>sS)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await sf(e);return new sI(t.privateKey,t.publicKey)}let{bytesToNumberBE:sk,hexToBytes:sB}=tu,sP={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){let{Err:t}=sP;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");let r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(128&n[0])throw new t("Invalid signature integer: negative");if(0===n[0]&&!(128&n[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:sk(n),l:e.subarray(r+2)}},toSig(e){let{Err:t}=sP,r="string"==typeof e?sB(e):e;nR(r);let n=r.length;if(n<2||48!=r[0])throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:i,l:s}=sP._parseInt(r.subarray(2)),{d:o,l:a}=sP._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(e){let t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,r=e=>{let t=e.toString(16);return 1&t.length?`0${t}`:t},n=t(r(e.s)),i=t(r(e.r)),s=n.length/2,o=i.length/2,a=r(s),l=r(o);return`30${r(o+s+4)}02${l}${i}02${a}${n}`}},sD=BigInt(0),sN=BigInt(1),sL=(BigInt(2),BigInt(3));BigInt(4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let sx=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),sO=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),sM=BigInt(1),sU=BigInt(2),sF=(e,t)=>(e+t/sU)/t,sK=n5(sx,void 0,void 0,{sqrt:function(e){let t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),l=e*e*e%sx,c=l*l*e%sx,u=n1(c,t,sx)*c%sx,h=n1(u,t,sx)*c%sx,d=n1(h,sU,sx)*l%sx,p=n1(d,n,sx)*d%sx,f=n1(p,i,sx)*p%sx,g=n1(f,o,sx)*f%sx,y=n1(g,a,sx)*g%sx,m=n1(y,o,sx)*f%sx,b=n1(m,t,sx)*c%sx,w=n1(b,s,sx)*p%sx,v=n1(w,r,sx)*l%sx,E=n1(v,sU,sx);if(!sK.eql(sK.sqr(E),e))throw Error("Cannot find square root");return E}}),sV=function(e,t){let r=t=>(function(e){let t=function(e){let t=ir(e);return nz(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n:n}=t,i=r.BYTES+1,s=2*r.BYTES+1;function o(e){return nZ(e,n)}let{ProjectivePoint:a,normPrivateKeyToScalar:l,weierstrassEquation:c,isWithinCurveOrder:u}=function(e){let t=/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function(e){let t=ir(e);nz(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,n.ZERO))throw Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=t.toBytes||((e,t,n)=>{let i=t.toAffine();return nF(Uint8Array.from([4]),r.toBytes(i.x),r.toBytes(i.y))}),i=t.fromBytes||(e=>{let t=e.subarray(1),n=r.fromBytes(t.subarray(0,r.BYTES)),i=r.fromBytes(t.subarray(r.BYTES,2*r.BYTES));return{x:n,y:i}});function s(e){let{a:n,b:i}=t,s=r.sqr(e),o=r.mul(s,e);return r.add(r.add(o,r.mul(e,n)),i)}if(!r.eql(r.sqr(t.Gy),s(t.Gx)))throw Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&sD<e&&e<t.n}function a(e){if(!o(e))throw Error("Expected valid bigint: 0 < bigint < curve.n")}function l(e){let r;let{allowedPrivateKeyLengths:n,nByteLength:i,wrapPrivateKey:s,n:o}=t;if(n&&"bigint"!=typeof e){if(n_(e)&&(e=nk(e)),"string"!=typeof e||!n.includes(e.length))throw Error("Invalid key");e=e.padStart(2*i,"0")}try{r="bigint"==typeof e?e:nL(nU("private key",e,i))}catch(t){throw Error(`private key must be ${i} bytes, hex or bigint, not ${typeof e}`)}return s&&(r=nZ(r,o)),a(r),r}let c=new Map;function u(e){if(!(e instanceof h))throw Error("ProjectivePoint expected")}class h{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t))throw Error("y required");if(null==n||!r.isValid(n))throw Error("z required")}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error("invalid affine point");if(e instanceof h)throw Error("projective point not allowed");let i=e=>r.eql(e,r.ZERO);return i(t)&&i(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){let t=r.invertBatch(e.map(e=>e.pz));return e.map((e,r)=>e.toAffine(t[r])).map(h.fromAffine)}static fromHex(e){let t=h.fromAffine(i(nU("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(l(e))}_setWindowSize(e){this._WINDOW_SIZE=e,c.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw Error("bad point: ZERO")}let{x:e,y:n}=this.toAffine();if(!r.isValid(e)||!r.isValid(n))throw Error("bad point: x or y not FE");let i=r.sqr(n),o=s(e);if(!r.eql(i,o))throw Error("bad point: equation left != right");if(!this.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){u(e);let{px:t,py:n,pz:i}=this,{px:s,py:o,pz:a}=e,l=r.eql(r.mul(t,a),r.mul(s,i)),c=r.eql(r.mul(n,a),r.mul(o,i));return l&&c}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){let{a:e,b:n}=t,i=r.mul(n,sL),{px:s,py:o,pz:a}=this,l=r.ZERO,c=r.ZERO,u=r.ZERO,d=r.mul(s,s),p=r.mul(o,o),f=r.mul(a,a),g=r.mul(s,o);return g=r.add(g,g),u=r.mul(s,a),u=r.add(u,u),l=r.mul(e,u),c=r.mul(i,f),c=r.add(l,c),l=r.sub(p,c),c=r.add(p,c),c=r.mul(l,c),l=r.mul(g,l),u=r.mul(i,u),f=r.mul(e,f),g=r.sub(d,f),g=r.mul(e,g),g=r.add(g,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,g),c=r.add(c,d),f=r.mul(o,a),f=r.add(f,f),d=r.mul(f,g),l=r.sub(l,d),u=r.mul(f,p),u=r.add(u,u),new h(l,c,u=r.add(u,u))}add(e){u(e);let{px:n,py:i,pz:s}=this,{px:o,py:a,pz:l}=e,c=r.ZERO,d=r.ZERO,p=r.ZERO,f=t.a,g=r.mul(t.b,sL),y=r.mul(n,o),m=r.mul(i,a),b=r.mul(s,l),w=r.add(n,i),v=r.add(o,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,s);let E=r.add(o,l);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(i,s),c=r.add(a,l),E=r.mul(E,c),c=r.add(m,b),E=r.sub(E,c),p=r.mul(f,v),c=r.mul(g,b),p=r.add(c,p),c=r.sub(m,p),p=r.add(m,p),d=r.mul(c,p),m=r.add(y,y),m=r.add(m,y),b=r.mul(f,b),v=r.mul(g,v),m=r.add(m,b),b=r.sub(y,b),b=r.mul(f,b),v=r.add(v,b),y=r.mul(m,v),d=r.add(d,y),y=r.mul(E,v),c=r.mul(w,c),c=r.sub(c,y),y=r.mul(w,m),p=r.mul(E,p),new h(c,d,p=r.add(p,y))}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,c,e,e=>{let t=r.invertBatch(e.map(e=>e.pz));return e.map((e,r)=>e.toAffine(t[r])).map(h.fromAffine)})}multiplyUnsafe(e){let n=h.ZERO;if(e===sD)return n;if(a(e),e===sN)return this;let{endo:i}=t;if(!i)return p.unsafeLadder(this,e);let{k1neg:s,k1:o,k2neg:l,k2:c}=i.splitScalar(e),u=n,d=n,f=this;for(;o>sD||c>sD;)o&sN&&(u=u.add(f)),c&sN&&(d=d.add(f)),f=f.double(),o>>=sN,c>>=sN;return s&&(u=u.negate()),l&&(d=d.negate()),d=new h(r.mul(d.px,i.beta),d.py,d.pz),u.add(d)}multiply(e){let n,i;a(e);let{endo:s}=t;if(s){let{k1neg:t,k1:o,k2neg:a,k2:l}=s.splitScalar(e),{p:c,f:u}=this.wNAF(o),{p:d,f:f}=this.wNAF(l);c=p.constTimeNegate(t,c),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,s.beta),d.py,d.pz),n=c.add(d),i=u.add(f)}else{let{p:t,f:r}=this.wNAF(e);n=t,i=r}return h.normalizeZ([n,i])[0]}multiplyAndAddUnsafe(e,t,r){let n=h.BASE,i=(e,t)=>t!==sD&&t!==sN&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=i(this,t).add(i(e,r));return s.is0()?void 0:s}toAffine(e){let{px:t,py:n,pz:i}=this,s=this.is0();null==e&&(e=s?r.ONE:r.inv(i));let o=r.mul(t,e),a=r.mul(n,e),l=r.mul(i,e);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){let{h:e,isTorsionFree:r}=t;if(e===sN)return!0;if(r)return r(h,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:e,clearCofactor:r}=t;return e===sN?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),n(h,this,e)}toHex(e=!0){return nk(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);let d=t.nBitLength,p=it(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:l,weierstrassEquation:s,isWithinCurveOrder:o}}({...t,toBytes(e,t,n){let i=t.toAffine(),s=r.toBytes(i.x),o=nF;return n?o(Uint8Array.from([t.hasEvenY()?2:3]),s):o(Uint8Array.from([4]),s,r.toBytes(i.y))},fromBytes(e){let t=e.length,n=e[0],o=e.subarray(1);if(t===i&&(2===n||3===n)){let e;let t=nL(o);if(!(sD<t&&t<r.ORDER))throw Error("Point is not on curve");let i=c(t);try{e=r.sqrt(i)}catch(t){let e=t instanceof Error?": "+t.message:"";throw Error("Point is not on curve"+e)}let s=(e&sN)===sN;return(1&n)==1!==s&&(e=r.neg(e)),{x:t,y:e}}if(t===s&&4===n){let e=r.fromBytes(o.subarray(0,r.BYTES)),t=r.fromBytes(o.subarray(r.BYTES,2*r.BYTES));return{x:e,y:t}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),h=e=>nk(nO(e,t.nByteLength));function d(e){let t=n>>sN;return e>t}let p=(e,t,r)=>nL(e.slice(t,r));class f{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){let r=t.nByteLength;return new f(p(e=nU("compactSignature",e,2*r),0,r),p(e,r,2*r))}static fromDER(e){let{r:t,s:r}=sP.toSig(nU("DER",e));return new f(t,r)}assertValidity(){if(!u(this.r))throw Error("r must be 0 < r < CURVE.n");if(!u(this.s))throw Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){let{r:i,s,recovery:l}=this,c=m(nU("msgHash",e));if(null==l||![0,1,2,3].includes(l))throw Error("recovery id invalid");let u=2===l||3===l?i+t.n:i;if(u>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let d=(1&l)==0?"02":"03",p=a.fromHex(d+h(u)),f=n2(u,n),g=o(-c*f),y=o(s*f),b=a.BASE.multiplyAndAddUnsafe(p,g,y);if(!b)throw Error("point at infinify");return b.assertValidity(),b}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return nN(this.toDERHex())}toDERHex(){return sP.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return nN(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}function g(e){let t=n_(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===i||n===s:r?n===2*i||n===2*s:e instanceof a}let y=t.bits2int||function(e){let r=nL(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},m=t.bits2int_modN||function(e){return o(y(e))},b=nK(t.nBitLength);function w(e){if("bigint"!=typeof e)throw Error("bigint expected");if(!(sD<=e&&e<b))throw Error(`bigint expected < 2^${t.nBitLength}`);return nO(e,t.nByteLength)}let v={lowS:t.lowS,prehash:!1},E={lowS:t.lowS,prehash:!1};return a.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return a.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(g(e))throw Error("first arg must be private key");if(!g(t))throw Error("second arg must be public key");let n=a.fromHex(t);return n.multiply(l(e)).toRawBytes(r)},sign:function(e,i,s=v){let{seed:c,k2sig:h}=function(e,i,s=v){if(["recovered","canonical"].some(e=>e in s))throw Error("sign() legacy options not supported");let{hash:c,randomBytes:h}=t,{lowS:p,prehash:g,extraEntropy:b}=s;null==p&&(p=!0),e=nU("msgHash",e),g&&(e=nU("prehashed msgHash",c(e)));let E=m(e),S=l(i),A=[w(S),w(E)];if(null!=b&&!1!==b){let e=!0===b?h(r.BYTES):b;A.push(nU("extraEntropy",e))}let I=nF(...A);return{seed:I,k2sig:function(e){let t=y(e);if(!u(t))return;let r=n2(t,n),i=a.BASE.multiply(t).toAffine(),s=o(i.x);if(s===sD)return;let l=o(r*o(E+s*S));if(l===sD)return;let c=(i.x===s?0:2)|Number(i.y&sN),h=l;return p&&d(l)&&(h=d(l)?o(-l):l,c^=1),new f(s,h,c)}}}(e,i,s),p=n$(t.hash.outputLen,t.nByteLength,t.hmac);return p(c,h)},verify:function(e,r,i,s=E){let l,c;if(r=nU("msgHash",r),i=nU("publicKey",i),"strict"in s)throw Error("options.strict was renamed to lowS");let{lowS:u,prehash:h}=s;try{if("string"==typeof e||n_(e))try{c=f.fromDER(e)}catch(t){if(!(t instanceof sP.Err))throw t;c=f.fromCompact(e)}else if("object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s){let{r:t,s:r}=e;c=new f(t,r)}else throw Error("PARSE");l=a.fromHex(i)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(u&&c.hasHighS())return!1;h&&(r=t.hash(r));let{r:d,s:p}=c,g=m(r),y=n2(p,n),b=o(g*y),w=o(d*y),v=a.BASE.multiplyAndAddUnsafe(l,b,w)?.toAffine();if(!v)return!1;let S=o(v.x);return S===d},ProjectivePoint:a,Signature:f,utils:{isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let e=n9(t.n);return function(e,t,r=!1){let n=e.length,i=n8(t),s=n9(t);if(n<16||n<s||n>1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);let o=r?nL(e):nx(e),a=nZ(o,t-nj)+nj;return r?nM(a,i):nO(a,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=a.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}})({...e,hash:t,hmac:(e,...r)=>iH(t,e,(0,nm.eV)(...r)),randomBytes:nm.O6});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:sK,n:sO,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-sM*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=BigInt("0x100000000000000000000000000000000"),s=sF(t*e,sO),o=sF(-r*e,sO),a=nZ(e-s*t-o*n,sO),l=nZ(-s*r-o*t,sO),c=a>i,u=l>i;if(c&&(a=sO-a),u&&(l=sO-l),a>i||l>i)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:c,k1:a,k2neg:u,k2:l}}}},iz.J);function sH(e){try{sV.ProjectivePoint.fromHex(e)}catch(e){throw new iJ(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),sV.ProjectivePoint;class s${_key;constructor(e){sH(e),this._key=e}verify(e,t){return function(e,t,r){let n=i6.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(i7(n))return n.then(({digest:r})=>sV.verify(t,r,e)).catch(e=>{throw new iJ(String(e),"ERR_INVALID_INPUT")});try{return sV.verify(t,n.digest,e)}catch(e){throw new iJ(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return function(e){let t=sV.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}get bytes(){return ex.encode({Type:eN.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}async hash(){let e;let t=i6.sha256.digest(this.bytes);return i7(t)?{bytes:e}=await t:e=t.bytes,e}}class sq{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return sV.getPublicKey(e,!0)}catch(e){throw new iJ(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{sV.getPublicKey(e,!0)}catch(e){throw new iJ(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),sH(this._publicKey)}sign(e){return function(e,t){let r=i6.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(i7(r))return r.then(({digest:t})=>sV.sign(t,e).toDERRawBytes()).catch(e=>{throw new iJ(String(e),"ERR_INVALID_INPUT")});try{return sV.sign(r.digest,e).toDERRawBytes()}catch(e){throw new iJ(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new s$(this._publicKey)}marshal(){return this._key}get bytes(){return eO.encode({Type:eN.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return i7(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,i5.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return si(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function sz(e){return new sq(e)}function sG(e){return new s$(e)}async function sj(){let e=sV.utils.randomPrivateKey();return new sq(e)}let sW={rsa:td,ed25519:th,secp256k1:tp};function sY(e){let t=Object.keys(sW).join(" / ");return new iJ(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}async function sQ(e){let t=eO.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eN.RSA:return sW.rsa.unmarshalRsaPrivateKey(r);case eN.Ed25519:return sW.ed25519.unmarshalEd25519PrivateKey(r);case eN.Secp256k1:return sW.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw sY(t.Type??"RSA")}}let sX=Symbol.for("@libp2p/peer-id");function sJ(e){return null!=e&&!!e[sX]}var sZ=r(4110),s0=r(8590),s1=r(50);let s2=Symbol.for("nodejs.util.inspect.custom"),s3=Object.values(sZ.gh).map(e=>e.decoder).reduce((e,t)=>e.or(t),sZ.gh.identity.decoder);class s4{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()})`}[sX]=!0;toString(){return null==this.string&&(this.string=i3.base58btc.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return s0.k0.createV1(114,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return(0,tI.f)(this.multihash.bytes,e);if("string"==typeof e)return s9(e).equals(this);if(e?.multihash?.bytes!=null)return(0,tI.f)(this.multihash.bytes,e.multihash.bytes);throw Error("not valid Id")}[s2](){return`PeerId(${this.toString()})`}}class s6 extends s4{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class s5 extends s4{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class s8 extends s4{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function s9(e,t){if(t=t??s3,"1"===e.charAt(0)||"Q"===e.charAt(0)){let t=s1.Jx(i3.base58btc.decode(`z${e}`));return e.startsWith("12D")?new s5({multihash:t}):e.startsWith("16U")?new s8({multihash:t}):new s6({multihash:t})}return s7(s3.decode(e))}function s7(e){try{let t=s1.Jx(e);if(t.code===i4.identity.code){if(36===t.digest.length)return new s5({multihash:t});if(37===t.digest.length)return new s8({multihash:t})}if(t.code===i6.sha256.code)return new s6({multihash:t})}catch{return function(e){if(null==e||null==e.multihash||null==e.version||1===e.version&&114!==e.code)throw Error("Supplied PeerID CID is invalid");let t=e.multihash;if(t.code===i6.sha256.code)return new s6({multihash:e.multihash});if(t.code===i4.identity.code){if(36===t.digest.length)return new s5({multihash:e.multihash});if(37===t.digest.length)return new s8({multihash:e.multihash})}throw Error("Supplied PeerID CID is invalid")}(s0.k0.decode(e))}throw Error("Supplied PeerID CID is invalid")}async function oe(e,t){return 36===e.length?new s5({multihash:s1.Ue(i4.identity.code,e),privateKey:t}):37===e.length?new s8({multihash:s1.Ue(i4.identity.code,e),privateKey:t}):new s6({multihash:await i6.sha256.digest(e),publicKey:e,privateKey:t})}async function ot(e,t,r){var n;let i=await or(e,oi(t));if(null==e.publicKey)throw Error("PublicKey was missing from local PeerId");return n=e.publicKey,eU.encode({identityKey:n,identitySig:i,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function or(e,t){if(null==e.privateKey)throw Error("PrivateKey was missing from PeerId");let r=await sQ(e.privateKey);return r.sign(t)}async function on(e){return oe(e.identityKey)}function oi(e){let t=(0,i2.m)("noise-libp2p-static-key:");return e instanceof Uint8Array?tA([t,e],t.length+e.length):(e.prepend(t),e)}async function os(e,t,r){let n=await oe(t.identityKey);if(!n.equals(r))throw Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=oi(e);if(null==n.publicKey)throw Error("PublicKey was missing from PeerId");if(null==t.identitySig)throw Error("Signature was missing from message");let s=function(e){let t=ex.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eN.RSA:return sW.rsa.unmarshalRsaPublicKey(r);case eN.Ed25519:return sW.ed25519.unmarshalEd25519PublicKey(r);case eN.Secp256k1:return sW.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw sY(t.Type??"unknown")}}(n.publicKey),o=await s.verify(i,t.identitySig);if(!o)throw Error("Static key doesn't match to peer that signed payload!");return n}function oo(e){return!!(e instanceof Uint8Array||tR(e))&&32===e.byteLength}(M=eM||(eM={})).codec=()=>(null==a&&(a=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(let r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();t>>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r})),a),M.encode=e=>(0,ss.LE)(e,M.codec()),M.decode=e=>(0,ss.C6)(e,M.codec()),(U=eU||(eU={})).codec=()=>(null==l&&(l=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),eM.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={identityKey:(0,tS.u)(0),identitySig:(0,tS.u)(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=eM.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),l),U.encode=e=>(0,ss.LE)(e,U.codec()),U.decode=e=>(0,ss.C6)(e,U.codec());class oa{n;bytes;view;constructor(e=0){this.n=e,this.bytes=(0,tS.u)(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}class ol{crypto;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=t}encryptWithAd(e,t,r){let n=this.encrypt(e.k,e.n,t,r);return e.n.increment(),n}decryptWithAd(e,t,r,n){let{plaintext:i,valid:s}=this.decrypt(e.k,e.n,t,r,n);return s&&e.n.increment(),{plaintext:i,valid:s}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return(0,tS.u)(32)}isEmptyKey(e){let t=this.createEmptyKey();return(0,tI.f)(t,e)}encrypt(e,t,r,n){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(n,t.getBytes(),r,e)}encryptAndHash(e,t){let r;return r=this.hasKey(e.cs)?this.encryptWithAd(e.cs,e.h,t):t,this.mixHash(e,r),r}decrypt(e,t,r,n,i){t.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(n,t.getBytes(),r,e,i);return s?{plaintext:s,valid:!0}:{plaintext:(0,tS.u)(0),valid:!1}}decryptAndHash(e,t){let r;let n=!0;return this.hasKey(e.cs)?{plaintext:r,valid:n}=this.decryptWithAd(e.cs,e.h,t):r=t,this.mixHash(e,t),{plaintext:r,valid:n}}dh(e,t){try{let r=this.crypto.generateX25519SharedKey(e,t);if(32===r.length)return r;return r.subarray(0,32)}catch(e){return this.log.error("error deriving shared key",e),(0,tS.u)(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){let r=this.crypto.hashSHA256(new tC(e,t));return r}mixKey(e,t){let[r,n]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(n),e.ck=r}initializeKey(e){return{k:e,n:new oa}}initializeSymmetric(e){let t=(0,i2.m)(e,"utf-8"),r=this.hashProtocolName(t),n=this.createEmptyKey(),i=this.initializeKey(n);return{cs:i,ck:r,h:r}}hashProtocolName(e){if(!(e.length<=32))return this.getHash(e,(0,tS.u)(0));{let t=(0,tS.u)(32);return t.set(e),t}}split(e){let[t,r]=this.crypto.getHKDF(e.ck,(0,tS.u)(0)),n=this.initializeKey(t),i=this.initializeKey(r);return{cs1:n,cs2:i}}writeMessageRegular(e,t){let r=this.encryptWithAd(e,(0,tS.u)(0),t),n=this.createEmptyKey(),i=(0,tS.u)(0);return{ne:n,ns:i,ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,(0,tS.u)(0),t.ciphertext)}}class oc extends ol{initializeInitiator(e,t,r,n){let i=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");this.mixHash(i,e);let s=(0,tS.u)(32);return{ss:i,s:t,rs:r,psk:n,re:s}}initializeResponder(e,t,r,n){let i=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");this.mixHash(i,e);let s=(0,tS.u)(32);return{ss:i,s:t,rs:r,psk:n,re:s}}writeMessageA(e,t,r){let n=(0,tS.u)(0);void 0!==r?e.e=r:e.e=this.crypto.generateX25519KeyPair();let i=e.e.publicKey;this.mixHash(e.ss,i);let s=this.encryptAndHash(e.ss,t);return{ne:i,ns:n,ciphertext:s}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t);return{ne:r,ns:i,ciphertext:s}}writeMessageC(e,t){let r=e.s.publicKey,n=this.encryptAndHash(e.ss,r);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let i=this.encryptAndHash(e.ss,t),s=this.createEmptyKey(),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,messageBuffer:{ne:s,ns:n,ciphertext:i},cs1:o,cs2:a}}readMessageA(e,t){return oo(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(oo(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);n&&oo(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:i,valid:s}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:i,valid:n&&s}}readMessageC(e,t){let{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);if(n&&oo(r)&&(e.rs=r),!e.e)throw Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:i,valid:s}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,plaintext:i,valid:n&&s,cs1:o,cs2:a}}initSession(e,t,r){let n=this.createEmptyKey(),i=(0,tS.u)(32);return{hs:e?this.initializeInitiator(t,r,i,n):this.initializeResponder(t,r,i,n),i:e,mc:0}}sendMessage(e,t,r){let n;if(0===e.mc)n=this.writeMessageA(e.hs,t,r);else if(1===e.mc)n=this.writeMessageB(e.hs,t);else if(2===e.mc){let{h:r,messageBuffer:i,cs1:s,cs2:o}=this.writeMessageC(e.hs,t);n=i,e.h=r,e.cs1=s,e.cs2=o}else if(e.mc>2){if(e.i){if(!e.cs1)throw Error("CS1 (cipher state) is not defined");n=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw Error("CS2 (cipher state) is not defined");n=this.writeMessageRegular(e.cs2,t)}}else throw Error("Session invalid.");return e.mc++,n}recvMessage(e,t){let r=(0,tS.u)(0),n=!1;if(0===e.mc)({plaintext:r,valid:n}=this.readMessageA(e.hs,t));else if(1===e.mc)({plaintext:r,valid:n}=this.readMessageB(e.hs,t));else if(2===e.mc){let{h:i,plaintext:s,valid:o,cs1:a,cs2:l}=this.readMessageC(e.hs,t);r=s,n=o,e.h=i,e.cs1=a,e.cs2=l}return e.mc++,{plaintext:r,valid:n}}}function ou(e,t){t.enabled&&rV&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${(0,i5.B)(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${(0,i5.B)(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function oh(e,t){t.enabled&&rV&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${(0,i5.B)(e.subarray(),"hex")}`)}class od{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(e,t,r,n,i,s,o,a,l){this.log=e.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=l??new oc(e,i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){var e,t;if(e=this.session.hs.s,(t=this.log).enabled&&rV&&(t(`LOCAL_STATIC_PUBLIC_KEY ${(0,i5.B)(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${(0,i5.B)(e.privateKey,"hex")}`)),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,(0,tS.u)(0));await this.connection.write(new tC(e.ne,e.ciphertext)),this.log.trace("Stage 0 - Initiator finished sending first message."),ou(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");let e=function(e){if(e.length<32)throw Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:(0,tS.u)(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new iQ("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),oh(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){var e,t;this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");let r=function(e){if(e.length<80)throw Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}((await this.connection.read()).subarray()),{plaintext:n,valid:i}=this.xx.recvMessage(this.session,r);if(!i)throw new iQ("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),oh(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&rV&&t(`REMOTE_STATIC_PUBLIC_KEY ${(0,i5.B)(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{let e=eU.decode(n);this.remotePeer=this.remotePeer||await on(e),await os(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new iY(`Error occurred while verifying signed payload: ${e.message}`)}this.log.trace("All good with the signature!")}else{this.log.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(new tC(e.ne,e.ns,e.ciphertext)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),ou(this.session.hs.e,this.log)}}async finish(){var e,t;if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(new tC(e.ns,e.ciphertext)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");let e=function(e){if(e.length<48)throw Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:(0,tS.u)(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}((await this.connection.read()).subarray()),{plaintext:t,valid:r}=this.xx.recvMessage(this.session,e);if(!r)throw new iQ("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{let e=eU.decode(t);this.remotePeer=this.remotePeer||await on(e),await os(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new iY(`Error occurred while verifying signed payload: ${e.message}`)}}e=this.session,(t=this.log).enabled&&rV&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${(0,i5.B)(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${(0,i5.B)(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){let r=this.getCS(t);return this.xx.encryptWithAd(r,(0,tS.u)(0),e)}decrypt(e,t,r){let n=this.getCS(t,!1);return this.xx.decryptWithAd(n,(0,tS.u)(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new iQ("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}}class op{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:r,extensions:n,crypto:i,prologueBytes:s}=t,{metrics:o}=e;this.components=e,this.crypto=i??iG,this.extensions=n,this.metrics=o?{xxHandshakeSuccesses:o.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:o.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:o.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:o.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:o.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}:void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??(0,tS.u)(0)}async secureOutbound(e,t,r){let n=rF(t,{lengthEncoder:ij,lengthDecoder:iW,maxDataLength:65535}),i=await this.performHandshake({connection:n,isInitiator:!0,localPeer:e,remotePeer:r}),s=await this.createSecureConnection(n,i);return t.source=s.source,t.sink=s.sink,{conn:t,remoteExtensions:i.remoteExtensions,remotePeer:i.remotePeer}}async secureInbound(e,t,r){let n=rF(t,{lengthEncoder:ij,lengthDecoder:iW,maxDataLength:65535}),i=await this.performHandshake({connection:n,isInitiator:!1,localPeer:e,remotePeer:r}),s=await this.createSecureConnection(n,i);return t.source=s.source,t.sink=s.sink,{conn:t,remotePeer:i.remotePeer,remoteExtensions:i.remoteExtensions}}async performHandshake(e){let t=await ot(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:r,remotePeer:n,connection:i}=e,s=new od(this.components,r,t,this.prologue,this.crypto,this.staticKeys,i,n);try{await s.propose(),await s.exchange(),await s.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){if(this.metrics?.xxHandshakeErrors.increment(),e instanceof Error)throw e.message=`Error occurred during XX handshake: ${e.message}`,e}return s}async createSecureConnection(e,t){var r,n;let[i,s]=function(){let e=rK(),t=rK();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),o=e.unwrap();return await tV(i,(r=this.metrics,async function*(e){for await(let n of e)for(let e=0;e<n.length;e+=65519){let i,s=e+65519;s>n.length&&(s=n.length),i=n instanceof Uint8Array?t.encrypt(n.subarray(e,s),t.session):t.encrypt(n.sublist(e,s),t.session),r?.encryptedPackets.increment(),yield new tC(ij(i.byteLength),i)}}),o,e=>tL(e,{lengthDecoder:iW}),(n=this.metrics,async function*(e){for await(let r of e)for(let e=0;e<r.length;e+=65535){let i=e+65535;if(i>r.length&&(i=r.length),i-16<e)throw Error("Invalid chunk");let s=r.sublist(e,i),o=r.subarray(e,i-16),{plaintext:a,valid:l}=t.decrypt(s,t.session,o);if(!l)throw n?.decryptErrors.increment(),Error("Failed to validate decrypted chunk");n?.decryptedPackets.increment(),yield a}}),i),s}}let of=Symbol.for("@libp2p/peer-discovery"),og=Symbol.for("@libp2p/service-capabilities"),oy=Symbol.for("@libp2p/service-dependencies");class om{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,r=e();return void 0===r&&(this.index=t),r}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,r){return this.readAtomically(()=>{if(!(t>0)||void 0!==this.readGivenChar(e))return r()})}readNumber(e,t,r,n){return this.readAtomically(()=>{let i=0,s=0,o=this.peekChar();if(void 0===o)return;let a=2**(8*n)-1;for(;;){let r=this.readAtomically(()=>{let t=this.readChar();if(void 0===t)return;let r=Number.parseInt(t,e);if(!Number.isNaN(r))return r});if(void 0===r)break;if(i*=e,(i+=r)>a||(s+=1,void 0!==t&&s>t))return}return 0===s?void 0:!r&&"0"===o&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let r=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(void 0===r)return;e[t]=r}return e})}readIPv6Addr(){let e=e=>{for(let t=0;t<e.length/2;t++){let r=2*t;if(t<e.length-3){let n=this.readSeparator(":",t,()=>this.readIPv4Addr());if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}let n=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n||void 0===this.readGivenChar(":")||void 0===this.readGivenChar(":"))return;let i=new Uint8Array(14),[s]=e(i.subarray(0,16-(r+2)));return t.set(i.subarray(0,s),16-s),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}let ob=new om;parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ow=r(8273);function ov(e){return!!function(e){if(!(e.length>15))return ob.new(e).parseWith(()=>ob.readIPv4Addr())}(e)}function oE(e){return!!function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return ob.new(e).parseWith(()=>ob.readIPv6Addr())}(e)}function oS(e){return!!function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return ob.new(e).parseWith(()=>ob.readIPAddr())}(e)}let oA=function(e){let t=0;if(ov(e=e.toString().trim())){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(e=>{r[t++]=255&parseInt(e,10)}),r}if(oE(e)){let r;let n=e.split(":",8);for(r=0;r<n.length;r++){let e;let t=ov(n[r]);t&&(e=oA(n[r]),n[r]=(0,i5.B)(e.slice(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,(0,i5.B)(e.slice(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(r=0;r<n.length&&""!==n[r];r++);let e=[r,1];for(r=9-n.length;r>0;r--)e.push("0");n.splice.apply(n,e)}let i=new Uint8Array(t+16);for(r=0;r<n.length;r++){let e=parseInt(n[r],16);i[t++]=e>>8&255,i[t++]=255&e}return i}throw Error("invalid ip address")},oI=function(e,t=0,r){t=~~t,r=r??e.length-t;let n=new DataView(e.buffer);if(4===r){let n=[];for(let i=0;i<r;i++)n.push(e[t+i]);return n.join(".")}if(16===r){let e=[];for(let i=0;i<r;i+=2)e.push(n.getUint16(t+i).toString(16));return e.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""},oT={},o_={};function oR(e){if("number"==typeof e){if(null!=o_[e])return o_[e];throw Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=oT[e])return oT[e];throw Error(`no protocol with name: ${e}`)}throw Error(`invalid protocol id type: ${typeof e}`)}function oC(e,t){let r=oR(e);switch(r.code){case 4:case 41:return function(e){let t=oI(e,0,e.length);if(null==t)throw Error("ipBuff is required");if(!oS(t))throw Error("invalid ip address");return t}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ox(t);case 6:case 273:case 33:case 132:return oN(t).toString();case 421:return function(e){let t=tE.Jx(e),r=e.slice(tE.P$(t));if(r.length!==t)throw Error("inconsistent lengths");return(0,i5.B)(r,"base58btc")}(t);case 444:case 445:return function(e){let t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=(0,i5.B)(t,"base32"),i=oN(r);return`${n}:${i}`}(t);case 466:return function(e){let t=tE.Jx(e),r=e.slice(tE.P$(t));if(r.length!==t)throw Error("inconsistent lengths");return"u"+(0,i5.B)(r,"base64url")}(t);case 481:return globalThis.encodeURIComponent(ox(t));default:return(0,i5.B)(t,"base16")}}function ok(e,t){let r=oR(e);switch(r.code){case 4:case 41:return function(e){if(!oS(e))throw Error("invalid ip address");return oA(e)}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return oL(t);case 6:case 273:case 33:case 132:return oD(parseInt(t,10));case 421:return function(e){let t;t="Q"===e[0]||"1"===e[0]?s1.Jx(i3.base58btc.decode(`z${e}`)).bytes:s0.k0.parse(e).multihash.bytes;let r=Uint8Array.from(tE.cv(t.length));return tA([r,t],r.length+t.length)}(t);case 444:return function(e){let t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=ow.base32.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");let i=oD(n);return tA([r,i],r.length+i.length)}(t);case 445:return function(e){let t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=ow.base32.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");let i=oD(n);return tA([r,i],r.length+i.length)}(t);case 466:return function(e){let t=oP.decode(e),r=Uint8Array.from(tE.cv(t.length));return tA([r,t],r.length+t.length)}(t);case 481:return oL(globalThis.decodeURIComponent(t));default:return(0,i2.m)(t,"base16")}}[[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"]].forEach(e=>{let t=function(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}(...e);o_[t.code]=t,oT[t.name]=t}),oR("ip4"),oR("ip6"),oR("ipcidr");let oB=Object.values(sZ.gh).map(e=>e.decoder),oP=(c=oB[0].or(oB[1]),oB.slice(2).forEach(e=>c=c.or(e)),c);function oD(e){let t=new ArrayBuffer(2),r=new DataView(t);return r.setUint16(0,e),new Uint8Array(t)}function oN(e){let t=new DataView(e.buffer);return t.getUint16(e.byteOffset)}function oL(e){let t=(0,i2.m)(e),r=Uint8Array.from(tE.cv(t.length));return tA([r,t],r.length+t.length)}function ox(e){let t=tE.Jx(e);if((e=e.slice(tE.P$(t))).length!==t)throw Error("inconsistent lengths");return(0,i5.B)(e)}function oO(e){let t=[],r=[],n=null,i=0;for(;i<e.length;){let s=tE.Jx(e,i),o=tE.P$(s),a=oR(s),l=function(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{let e=tE.Jx(t instanceof Uint8Array?t:Uint8Array.from(t));return e+tE.P$(e)}}(a,e.slice(i+o));if(0===l){t.push([s]),r.push([s]),i+=o;continue}let c=e.slice(i+o,i+o+l);if((i+=l+o)>e.length)throw oK("Invalid address Uint8Array: "+(0,i5.B)(e,"base16"));t.push([s,c]);let u=oC(s,c);if(r.push([s,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:oM(r),tuples:t,stringTuples:r,path:n}}function oM(e){let t=[];return e.map(e=>{let r=oR(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null}),oF(t.join("/"))}function oU(e){return tA(e.map(e=>{let t=oR(e[0]),r=Uint8Array.from(tE.cv(t.code));return e.length>1&&null!=e[1]&&(r=tA([r,e[1]])),r}))}function oF(e){return"/"+e.trim().split("/").filter(e=>e).join("/")}function oK(e){return Error("Error parsing address: "+e)}let oV=Symbol.for("nodejs.util.inspect.custom"),oH=Symbol.for("@multiformats/js-multiaddr/multiaddr"),o$=[oR("dns").code,oR("dns4").code,oR("dns6").code,oR("dnsaddr").code];class oq{bytes;#t;#r;#n;#i;[oH]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=oO(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw Error(`multiaddr "${e}" must start with a "/"`);t=function(e){e=oF(e);let t=[],r=[],n=null,i=e.split("/").slice(1);if(1===i.length&&""===i[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<i.length;s++){let o=i[s],a=oR(o);if(0===a.size){t.push([a.code]),r.push([a.code]);continue}if(++s>=i.length)throw oK("invalid address: "+e);if(!0===a.path){n=oF(i.slice(s).join("/")),t.push([a.code,ok(a.code,n)]),r.push([a.code,n]);break}let l=ok(a.code,i[s]);t.push([a.code,l]),r.push([a.code,oC(a.code,l)])}return{string:oM(r),bytes:oU(t),tuples:t,stringTuples:r,path:n}}(e)}else{var r;if(r=e,r?.[oH])t=oO(e.bytes);else throw Error("addr must be a string, Buffer, or another Multiaddr")}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#i=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n;let i="",s=oR("tcp"),o=oR("udp"),a=oR("ip4"),l=oR("ip6"),c=oR("dns6"),u=oR("ip6zone");for(let[h,d]of this.stringTuples())h===u.code&&(i=`%${d??""}`),o$.includes(h)&&(t=s.name,n=443,r=`${d??""}${i}`,e=h===c.code?6:4),(h===s.code||h===o.code)&&(t=oR(h).name,n=parseInt(d??"")),(h===a.code||h===l.code)&&(t=oR(h).name,r=`${d??""}${i}`,e=h===l.code?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');let h={family:e,host:r,transport:t,port:n};return h}protos(){return this.#r.map(([e])=>Object.assign({},oR(e)))}protoCodes(){return this.#r.map(([e])=>e)}protoNames(){return this.#r.map(([e])=>oR(e).name)}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new oq(e),new oq(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new oq(r.slice(0,n))}decapsulateCode(e){let t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new oq(oU(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([t,r])=>{t===oT.p2p.code&&e.push([t,r]),t===oT["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let e=t[1];if("Q"===e[0]||"1"===e[0])return(0,i5.B)(i3.base58btc.decode(`z${e}`),"base58btc");return(0,i5.B)(s0.k0.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#i}equals(e){return(0,tI.f)(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(e=>e.resolvable);if(null==t)return[this];let r=oz.get(t.name);if(null==r)throw new iJ(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");let n=await r(this,e);return n.map(e=>oG(e))}nodeAddress(){let e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw 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 2===t.length&&(4===t[0].code||41===t[0].code)&&(6===t[1].code||273===t[1].code)}[oV](){return`Multiaddr(${this.#t})`}}let oz=new Map;function oG(e){return new oq(e)}let oj=af("dns4"),oW=af("dns6"),oY=af("dnsaddr"),oQ=ap(af("dns"),oY,oj,oW),oX=ap(af("ip4"),af("ip6")),oJ=ap(ad(oX,af("tcp")),ad(oQ,af("tcp"))),oZ=ad(oX,af("udp")),o0=ad(oZ,af("utp")),o1=ad(oZ,af("quic")),o2=ad(oZ,af("quic-v1")),o3=ap(ad(oJ,af("ws")),ad(oQ,af("ws"))),o4=ap(ad(o3,af("p2p")),o3),o6=ap(ad(oJ,af("wss")),ad(oQ,af("wss")),ad(oJ,af("tls"),af("ws")),ad(oQ,af("tls"),af("ws"))),o5=ap(ad(o6,af("p2p")),o6),o8=ap(ad(oJ,af("http")),ad(oX,af("http")),ad(oQ,af("http"))),o9=ap(ad(oJ,af("https")),ad(oX,af("https")),ad(oQ,af("https"))),o7=ad(oZ,af("webrtc-direct"),af("certhash")),ae=ap(ad(o7,af("p2p")),o7),at=ad(o2,af("webtransport"),af("certhash"),af("certhash")),ar=ap(ad(at,af("p2p")),at),an=ap(ad(o4,af("p2p-webrtc-star"),af("p2p")),ad(o5,af("p2p-webrtc-star"),af("p2p")),ad(o4,af("p2p-webrtc-star")),ad(o5,af("p2p-webrtc-star")));ap(ad(o4,af("p2p-websocket-star"),af("p2p")),ad(o5,af("p2p-websocket-star"),af("p2p")),ad(o4,af("p2p-websocket-star")),ad(o5,af("p2p-websocket-star")));let ai=ap(ad(o8,af("p2p-webrtc-direct"),af("p2p")),ad(o9,af("p2p-webrtc-direct"),af("p2p")),ad(o8,af("p2p-webrtc-direct")),ad(o9,af("p2p-webrtc-direct"))),as=ap(o3,o6,o8,o9,an,ai,oJ,o0,o1,oQ,ae,ar);ap(ad(as,af("p2p-stardust"),af("p2p")),ad(as,af("p2p-stardust")));let ao=ap(ad(as,af("p2p")),an,ai,ae,ar,af("p2p")),aa=ap(ad(ao,af("p2p-circuit"),ao),ad(ao,af("p2p-circuit")),ad(af("p2p-circuit"),ao),ad(as,af("p2p-circuit")),ad(af("p2p-circuit"),as),af("p2p-circuit")),al=()=>ap(ad(aa,al),aa),ac=al(),au=ap(ad(ac,ao,ac),ad(ao,ac),ad(ac,ao),ac,ao);function ah(e){return function(t){let r;try{r=oG(t)}catch(e){return!1}let n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function ad(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some(e=>(Array.isArray(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t))&&(t=r),null===r)),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ah(t),partialMatch:t}}function ap(...e){function t(t){let r=null;return e.some(e=>{let n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)}),r}let r={toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ah(t),partialMatch:t};return r}function af(e){return{toString:function(){return e},matches:function(t){let r;try{r=oG(t)}catch(e){return!1}let n=r.protoNames();return 1===n.length&&n[0]===e},partialMatch:function(t){return 0===t.length?null:t[0]===e?t.slice(1):null}}}ap(ad(ac,af("webrtc"),af("p2p")),ad(ac,af("webrtc")),ad(as,af("webrtc"),af("p2p")),ad(as,af("webrtc")),af("webrtc"));class ag extends rI{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");for(let r of(super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[],t.list)){if(!au.matches(r)){this.log.error("Invalid multiaddr");continue}let e=oG(r),t=e.getPeerId();if(null==t){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let n={id:s9(t),multiaddrs:[e]};this.list.push(n)}this._init=t}[of]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[og]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL??12e4}}}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}let ay=Uint8Array.from([3,1]);(K=(F=eF||(eF={})).AddressInfo||(F.AddressInfo={})).codec=()=>(null==h&&(h=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r})),h),K.encode=e=>(0,ss.LE)(e,K.codec()),K.decode=e=>(0,ss.C6)(e,K.codec()),F.codec=()=>(null==u&&(u=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerId&&e.peerId.byteLength>0&&(t.uint32(10),t.bytes(e.peerId)),null!=e.seq&&0n!==e.seq&&(t.uint32(16),t.uint64(e.seq)),null!=e.addresses)for(let r of e.addresses)t.uint32(26),F.AddressInfo.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={peerId:new Uint8Array(0),seq:0n,addresses:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.peerId=e.bytes();break;case 2:r.seq=e.uint64();break;case 3:r.addresses.push(F.AddressInfo.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r})),u),F.encode=e=>(0,ss.LE)(e,F.codec()),F.decode=e=>(0,ss.C6)(e,F.codec());class am{static createFromProtobuf=e=>{let t=eF.decode(e),r=s7(t.peerId),n=(t.addresses??[]).map(e=>oG(e.multiaddr)),i=t.seq;return new am({peerId:r,multiaddrs:n,seqNumber:i})};static DOMAIN="libp2p-peer-record";static CODEC=ay;peerId;multiaddrs;seqNumber;domain=am.DOMAIN;codec=am.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=eF.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!!(e instanceof am&&this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&function(e,t){let r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every((e,r)=>t[r].equals(e)))}(this.multiaddrs,e.multiaddrs))}}function ab(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}function aw(e,t){let r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}var av={get(e=globalThis){let t=e.crypto;if(null==t||null==t.subtle)throw Object.assign(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 t}};let aE={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function aS(e,t){let r=function(e){let t=e?.algorithm??"AES-GCM",r=e?.keyLength??16,n=e?.nonceLength??12,i=e?.digest??"SHA-256",s=e?.saltLength??16,o=e?.iterations??32767,a=av.get();async function l(e,l){let c;let u=a.getRandomValues(new Uint8Array(s)),h=a.getRandomValues(new Uint8Array(n)),d={name:t,iv:h};if("string"==typeof l&&(l=(0,i2.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",aE,{name:"AES-GCM"},!0,["encrypt"]);try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}catch{c=await a.subtle.importKey("jwk",aE,{name:"AES-GCM"},!0,["encrypt"])}}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["encrypt"])}let p=await a.subtle.encrypt(d,c,e);return tA([u,d.iv,new Uint8Array(p)])}async function c(e,l){let c;let u=e.subarray(0,s),h=e.subarray(s,s+n),d=e.subarray(s+n);if("string"==typeof l&&(l=(0,i2.m)(l)),0===l.length)try{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}catch{c=await a.subtle.importKey("jwk",aE,{name:"AES-GCM"},!0,["decrypt"])}else{let e=await a.subtle.importKey("raw",l,{name:"PBKDF2"},!1,["deriveKey"]);c=await a.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:o,hash:{name:i}},e,{name:t,length:r},!0,["decrypt"])}let p=await a.subtle.decrypt({name:t,iv:h},c,d);return new Uint8Array(p)}return r*=8,{encrypt:l,decrypt:c}}(),n=await r.encrypt(e,t);return st.base64.encode(n)}(V=eK||(eK={})).RSA="RSA",V.Ed25519="Ed25519",V.Secp256k1="Secp256k1",(H=eV||(eV={}))[H.RSA=0]="RSA",H[H.Ed25519=1]="Ed25519",H[H.Secp256k1=2]="Secp256k1",(eK||(eK={})).codec=()=>(0,ss.Ji)(eV),($=eH||(eH={})).codec=()=>(null==d&&(d=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eK.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.Type=eK.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),d),$.encode=e=>(0,ss.LE)(e,$.codec()),$.decode=e=>(0,ss.C6)(e,$.codec()),(q=e$||(e$={})).codec=()=>(null==p&&(p=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eK.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.Type=eK.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),p),q.encode=e=>(0,ss.LE)(e,q.codec()),q.decode=e=>(0,ss.C6)(e,q.codec());class aA{_key;constructor(e){this._key=ak(e,32)}verify(e,t){var r;return r=this._key,iR.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return eH.encode({Type:eK.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return ab(e)?e.then(({bytes:e})=>e):e.bytes}}class aI{_key;_publicKey;constructor(e,t){this._key=ak(e,64),this._publicKey=ak(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return iR.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new aA(this._publicKey)}marshal(){return this._key}get bytes(){return e$.encode({Type:eK.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}async hash(){let e;let t=i6.sha256.digest(this.bytes);return ab(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=i4.identity.digest(this.public.bytes);return i3.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return aS(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function aT(e){if(e.length>64){e=ak(e,96);let t=e.subarray(0,64),r=e.subarray(64,e.length);return new aI(t,r)}e=ak(e,64);let t=e.subarray(0,64),r=e.subarray(32);return new aI(t,r)}function a_(e){return new aA(e=ak(e,32))}async function aR(){let{privateKey:e,publicKey:t}=function(){let e=iR.utils.randomPrivateKey(),t=iR.getPublicKey(e),r=aw(e,t);return{privateKey:r,publicKey:t}}();return new aI(e,t)}async function aC(e){let{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=iR.getPublicKey(e),r=aw(e,t);return{privateKey:r,publicKey:t}}(e);return new aI(t,r)}function ak(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new iJ(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function aB(e){let t=await av.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await aL(t);return{privateKey:r[0],publicKey:r[1]}}async function aP(e){let t=await av.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),r=[t,await ax(e)],n=await aL({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function aD(e,t){let r=await av.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await av.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function aN(e,t,r){let n=await av.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return av.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function aL(e){if(null==e.privateKey||null==e.publicKey)throw new iJ("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([av.get().subtle.exportKey("jwk",e.privateKey),av.get().subtle.exportKey("jwk",e.publicKey)])}async function ax(e){return av.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function aO(e){if("RSA"!==e.kty)throw new iJ("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new iJ("invalid key modulus","ERR_INVALID_KEY_MODULUS");let t=(0,i2.m)(e.n,"base64url");return 8*t.length}async function aM(e,t,r,n){var i;let s;let{c:o,dkLen:a,asyncTick:l,DK:c,PRF:u,PRFSalt:h}=function(e,t,r,n){(0,iK.vp)(e);let i=(0,nm.U5)({dkLen:32,asyncTick:10},n),{c:s,dkLen:o,asyncTick:a}=i;if((0,iK.Rx)(s),(0,iK.Rx)(o),(0,iK.Rx)(a),s<1)throw Error("PBKDF2: iterations (c) should be >= 1");let l=(0,nm.O0)(t),c=(0,nm.O0)(r),u=new Uint8Array(o),h=iH.create(e,l),d=h._cloneInto().update(c);return{c:s,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n),d=new Uint8Array(4),p=(0,nm.GL)(d),f=new Uint8Array(u.outputLen);for(let e=1,t=0;t<a;e++,t+=u.outputLen){let r=c.subarray(t,t+u.outputLen);p.setInt32(0,e,!1),(s=h._cloneInto(s)).update(d).digestInto(f),r.set(f.subarray(0,r.length)),await (0,nm.oY)(o-1,l,()=>{u._cloneInto(s).update(f).digestInto(f);for(let e=0;e<r.length;e++)r[e]^=f[e]})}return i=s,u.destroy(),h.destroy(),i&&i.destroy(),f.fill(0),c}var aU=r(3033);function aF(e,t){let r=0;if(1===e.length)return e[0];for(let n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function aK(e,t,r=-1){let n=e,i=0,s=Math.pow(2,t);for(let o=1;o<8;o++){if(e<s){let e;if(r<0)e=new ArrayBuffer(o),i=o;else{if(r<o)return new ArrayBuffer(0);e=new ArrayBuffer(r),i=r}let s=new Uint8Array(e);for(let e=o-1;e>=0;e--){let r=Math.pow(2,e*t);s[i-e-1]=Math.floor(n/r),n-=s[i-e-1]*r}return e}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function aV(...e){let t=0,r=0;for(let r of e)t+=r.length;let n=new ArrayBuffer(t),i=new Uint8Array(n);for(let t of e)i.set(t,r),r+=t.length;return i}function aH(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let t=255===e[0]&&128&e[1],r=0===e[0]&&(128&e[1])==0;(t||r)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];let n=aF(r,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)s[t]=e[t];s[0]&=127;let o=aF(s,8);return o-n}function a$(e,t){let r=e.toString(10);if(t<r.length)return"";let n=t-r.length,i=Array(n);for(let e=0;e<n;e++)i[e]="0";let s=i.join("");return s.concat(r)}/*!
|
|
* Copyright (c) 2014, GMO GlobalSign
|
|
* Copyright (c) 2015-2022, Peculiar Ventures
|
|
* All rights reserved.
|
|
*
|
|
* Author 2014-2019, Yury Strozhevsky
|
|
*
|
|
* Redistribution and use in source and binary forms, with or without modification,
|
|
* are permitted provided that the following conditions are met:
|
|
*
|
|
* * Redistributions of source code must retain the above copyright notice, this
|
|
* list of conditions and the following disclaimer.
|
|
*
|
|
* * Redistributions in binary form must reproduce the above copyright notice, this
|
|
* list of conditions and the following disclaimer in the documentation and/or
|
|
* other materials provided with the distribution.
|
|
*
|
|
* * Neither the name of the copyright holder nor the names of its
|
|
* contributors may be used to endorse or promote products derived from
|
|
* this software without specific prior written permission.
|
|
*
|
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
*
|
|
*/function aq(){if("undefined"==typeof BigInt)throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function az(e){let t=0,r=0;for(let r=0;r<e.length;r++){let n=e[r];t+=n.byteLength}let n=new Uint8Array(t);for(let t=0;t<e.length;t++){let i=e[t];n.set(new Uint8Array(i),r),r+=i.byteLength}return n.buffer}function aG(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class aj{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return az(this.items)}}let aW=[new Uint8Array([1])],aY="0123456789",aQ=new ArrayBuffer(0),aX=new Uint8Array(0),aJ="EndOfContent",aZ="OCTET STRING",a0="BIT STRING";function a1(e){var t;return(t=class extends e{constructor(...e){var t;super(...e);let r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?aU.vJ.toUint8Array(r.valueHex):aX}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}fromBER(e,t,r){let n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!aG(this,n,t,r))return -1;let i=t+r;return(this.valueHexView=n.subarray(t,i),this.valueHexView.length)?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?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",aQ)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:aU.ep.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class a2{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=aX}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=aU.vJ.toUint8Array(n)}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:aU.ep.ToHex(this.valueBeforeDecodeView)}}}a2.NAME="baseBlock";class a3 extends a2{fromBER(e,t,r){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'")}}a3.NAME="valueBlock";class a4 extends a1(a2){constructor({idBlock:e={}}={}){var t,r,n,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?aU.vJ.toUint8Array(e.valueHex):aX,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(n=e.tagNumber)&&void 0!==n?n:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(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",aQ}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){let r=aK(this.tagNumber,7),n=new Uint8Array(r),i=r.byteLength,s=new Uint8Array(i+1);if(s[0]=31|t,!e){for(let e=0;e<i-1;e++)s[e+1]=128|n[e];s[i]=n[i-1]}return s.buffer}let r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){let e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){let n=aU.vJ.toUint8Array(e);if(!aG(this,n,t,r))return -1;let i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;let s=192&i[0];switch(s){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=(32&i[0])==32,this.isHexOnly=!1;let o=31&i[0];if(31!==o)this.tagNumber=o,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&i[e];){if(t[e-1]=127&i[e],++e>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;let e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&i[e];let n=new Uint8Array(e);for(let r=0;r<e;r++)n[r]=t[r];(t=this.valueHexView=new Uint8Array(e)).set(n),this.blockLength<=9?this.tagNumber=aF(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&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}}}a4.NAME="identificationBlock";class a6 extends a2{constructor({lenBlock:e={}}={}){var t,r,n;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(n=e.length)&&void 0!==n?n:0}fromBER(e,t,r){let n=aU.vJ.toUint8Array(e);if(!aG(this,n,t,r))return -1;let i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;let s=127&i[0];if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let o=t+1,a=n.subarray(o,o+s);return 0===a[s-1]&&this.warnings.push("Needlessly long encoded length"),this.length=aF(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&((r=new Uint8Array(t))[0]=128),t;if(this.longFormUsed){let n=aK(this.length,8);if(n.byteLength>127)return this.error="Too big length",aQ;if(t=new ArrayBuffer(n.byteLength+1),e)return t;let i=new Uint8Array(n);(r=new Uint8Array(t))[0]=128|n.byteLength;for(let e=0;e<n.byteLength;e++)r[e+1]=i[e];return t}return t=new ArrayBuffer(1),!1===e&&((r=new Uint8Array(t))[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}a6.NAME="lengthBlock";let a5={};class a8 extends a2{constructor({name:e="",optional:t=!1,primitiveSchema:r,...n}={},i){super(n),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new a4(n),this.lenBlock=new a6(n),this.valueBlock=i?new i(n):new a3(n)}fromBER(e,t,r){let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return -1===n?this.error=this.valueBlock.error:(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)),n}toBER(e,t){let r=t||new aj;t||function e(t){if(t instanceof a5.Constructed)for(let r of t.valueBlock.value)e(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!t.lenBlock.isIndefiniteForm}(this);let n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{let t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;let n=this.lenBlock.toBER(e);r.write(n),r.write(t)}return t?aQ:r.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"ascii"===e?this.onAsciiEncoding():aU.ep.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${aU.ep.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),r=e.toBER();return function(e,t){if(e.byteLength!==t.byteLength)return!1;let r=new Uint8Array(e),n=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}(t,r)}}a8.NAME="BaseBlock";class a9 extends a8{constructor({value:e="",...t}={},r){super(t,r),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,r){let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return -1===n?this.error=this.valueBlock.error:(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)),n}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}a9.NAME="BaseStringBlock";class a7 extends a1(a3){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}a7.NAME="PrimitiveValueBlock";class le extends a8{constructor(e={}){super(e,a7),this.idBlock.isConstructed=!1}}function lt(e,t=0,r=e.length){let n=t,i=new a8({},a3),s=new a2;if(!aG(s,e,t,r))return i.error=s.error,{offset:-1,result:i};let o=e.subarray(t,t+r);if(!o.length)return i.error="Zero buffer length",{offset:-1,result:i};let a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let l=a8;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};l=a5.EndOfContent;break;case 1:l=a5.Boolean;break;case 2:l=a5.Integer;break;case 3:l=a5.BitString;break;case 4:l=a5.OctetString;break;case 5:l=a5.Null;break;case 6:l=a5.ObjectIdentifier;break;case 10:l=a5.Enumerated;break;case 12:l=a5.Utf8String;break;case 13:l=a5.RelativeObjectIdentifier;break;case 14:l=a5.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=a5.Sequence;break;case 17:l=a5.Set;break;case 18:l=a5.NumericString;break;case 19:l=a5.PrintableString;break;case 20:l=a5.TeletexString;break;case 21:l=a5.VideotexString;break;case 22:l=a5.IA5String;break;case 23:l=a5.UTCTime;break;case 24:l=a5.GeneralizedTime;break;case 25:l=a5.GraphicString;break;case 26:l=a5.VisibleString;break;case 27:l=a5.GeneralString;break;case 28:l=a5.UniversalString;break;case 29:l=a5.CharacterString;break;case 30:l=a5.BmpString;break;case 31:l=a5.DATE;break;case 32:l=a5.TimeOfDay;break;case 33:l=a5.DateTime;break;case 34:l=a5.Duration;break;default:{let e=i.idBlock.isConstructed?new a5.Constructed:new a5.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else l=i.idBlock.isConstructed?a5.Constructed:a5.Primitive;return a=(i=function(e,t){if(e instanceof t)return e;let r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,l)).fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(n,n+i.blockLength),{offset:a,result:i}}function lr(e){if(!e.byteLength){let e=new a8({},a3);return e.error="Input buffer has zero length",{offset:-1,result:e}}return lt(aU.vJ.toUint8Array(e).slice(),0,e.byteLength)}a5.Primitive=le,le.NAME="PRIMITIVE";class ln extends a3{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){var n,i;let s=aU.vJ.toUint8Array(e);if(!aG(this,s,t,r))return -1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let o=t;for(;n=this.isIndefiniteForm,i=r,(n?1:i)>0;){let e=lt(s,o,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(o=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===aJ)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===aJ?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){let r=t||new aj;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?aQ:r.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}}ln.NAME="ConstructedValueBlock";class li extends a8{constructor(e={}){super(e,ln),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return -1===n?this.error=this.valueBlock.error:(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)),n}onAsciiEncoding(){let e=[];for(let t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));let t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
${e.join("\n")}`:`${t} :`}}a5.Constructed=li,li.NAME="CONSTRUCTED";class ls extends a3{fromBER(e,t,r){return t}toBER(e){return aQ}}ls.override="EndOfContentValueBlock";class lo extends a8{constructor(e={}){super(e,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}a5.EndOfContent=lo,lo.NAME=aJ;class la extends a8{constructor(e={}){super(e,a3),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){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+=r,t+r>e.byteLength)?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){let r=new ArrayBuffer(2);if(!e){let e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}a5.Null=la,la.NAME="NULL";class ll extends a1(a3){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=aU.vJ.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,r){let n=aU.vJ.toUint8Array(e);return aG(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,aH.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ll.NAME="BooleanValueBlock";class lc extends a8{constructor(e={}){super(e,ll),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}`}}a5.Boolean=lc,lc.NAME="BOOLEAN";class lu extends a1(ln){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=ln.prototype.fromBER.call(this,e,t,r)))return n;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===aJ){if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;break}if(t!==aZ)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?ln.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}lu.NAME="OctetStringValueBlock";class lh extends a8{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,i;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},lu),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let n=e instanceof ArrayBuffer?new Uint8Array(e):e,i=n.subarray(t,t+r);try{if(i.byteLength){let e=lt(i,0,i.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?li.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${aU.ep.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 lh&&e.push(t.valueBlock.valueHexView);return aU.vJ.concat(e)}}a5.OctetString=lh,lh.NAME=aZ;class ld extends a1(ln){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let n=-1;if(this.isConstructed){if(-1===(n=ln.prototype.fromBER.call(this,e,t,r)))return n;for(let e of this.value){let t=e.constructor.NAME;if(t===aJ){if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1;break}if(t!==a0)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return n}let i=aU.vJ.toUint8Array(e);if(!aG(this,i,t,r))return -1;let s=i.subarray(t,t+r);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let e=s.subarray(1);try{if(e.byteLength){let t=lt(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+r}toBER(e,t){if(this.isConstructed)return ln.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return aQ;let r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}ld.NAME="BitStringValueBlock";class lp extends a8{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,i;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},ld),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return li.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let r of t)e.push(r.toString(2).padStart(8,"0"));let r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function lf(e){if(e>=aW.length)for(let t=aW.length;t<=e;t++){let e=new Uint8Array([0]),r=aW[t-1].slice(0);for(let t=r.length-1;t>=0;t--){let n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=aV(e,r)),aW.push(r)}return aW[e]}a5.BitString=lp,lp.NAME=a0;class lg extends a1(a3){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(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=aH.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){let t=e<0?-1*e:e,r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){let e=r-t,i=aK(e,8,n),s=new Uint8Array(i);return s[0]|=128,i}let i=aK(t,8,n),s=new Uint8Array(i);if(128&s[0]){let e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),s=new Uint8Array(i);for(let r=0;r<e.byteLength;r++)s[r+1]=t[r];s[0]=0}return i}r*=256}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,n=0){let i=this.fromBER(e,t,r);if(-1===i)return i;let s=this.valueHexView;return 0===s[0]&&(128&s[1])!=0?this.valueHexView=s.subarray(1):0!==n&&s.length<n&&(n-s.length>1&&(n=s.length+1),this.valueHexView=s.subarray(n-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(128&t[0])!=0:{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&(128&t[1])==0:this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){let n=super.fromBER(e,t,r);return -1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e;let t=8*this.valueHexView.length-1,r=new Uint8Array(8*this.valueHexView.length/3),n=0,i=this.valueHexView,s="",o=!1;for(let o=i.byteLength-1;o>=0;o--){e=i[o];for(let i=0;i<8;i++)(1&e)==1&&(n===t?(r=function(e,t){let r,n=0,i=new Uint8Array(e),s=new Uint8Array(t),o=i.slice(0),a=o.length-1,l=s.slice(0),c=l.length-1,u=0;for(let e=c;e>=0;e--,u++)!0==(r=o[a-u]-l[c-u]-n)<0?(n=1,o[a-u]=r+10):(n=0,o[a-u]=r);if(n>0)for(let e=a-c+1;e>=0;e--,u++)if((r=o[a-u]-n)<0)n=1,o[a-u]=r+10;else{n=0,o[a-u]=r;break}return o.slice()}(lf(n),r),s="-"):r=function(e,t){let r=new Uint8Array([0]),n=new Uint8Array(e),i=new Uint8Array(t),s=n.slice(0),o=s.length-1,a=i.slice(0),l=a.length-1,c=0,u=l<o?o:l,h=0;for(let e=u;e>=0;e--,h++)c=!0==h<a.length?s[o-h]+a[l-h]+r[0]:s[o-h]+r[0],(r[0]=c/10,!0==h>=s.length)?s=aV(new Uint8Array([c%10]),s):s[o-h]=c%10;return r[0]>0&&(s=aV(r,s)),s}(r,lf(n))),n++,e>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(s+=aY.charAt(r[e]));return!1===o&&(s+=aY.charAt(0)),s}}lg.NAME="IntegerValueBlock",Object.defineProperty(lg.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class ly extends a8{constructor(e={}){super(e,lg),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return aq(),BigInt(this.valueBlock.toString())}static fromBigInt(e){aq();let t=BigInt(e),r=new aj,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(aU.ep.FromHex(n));if(t<0){let e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;let n=BigInt(`0x${aU.ep.ToHex(e)}`),s=aU.vJ.toUint8Array(aU.ep.FromHex((n+t).toString(16)));s[0]|=128,r.write(s)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);let s=new ly({valueHex:r.final()});return s}convertToDER(){let e=new ly({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new ly({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}a5.Integer=ly,ly.NAME="INTEGER";class lm extends ly{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}a5.Enumerated=lm,lm.NAME="ENUMERATED";class lb extends a1(a3){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;let n=aU.vJ.toUint8Array(e);if(!aG(this,n,t,r))return -1;let i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,(128&i[e])!=0);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return(this.valueHexView=s,(128&i[this.blockLength-1])!=0)?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=aF(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){aq();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}let t=aK(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",aQ;let r=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r}toString(){let e="";if(this.isHexOnly)e=aU.ep.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}}}lb.NAME="sidBlock";class lw extends a3{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){let t=new lb;if(-1===(n=t.fromBER(e,n,r))){this.blockLength=0,this.error=t.error;break}0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){let t=[];for(let r=0;r<this.value.length;r++){let n=this.value[r].toBER(e);if(0===n.byteLength)return this.error=this.value[r].error,aQ;t.push(n)}return az(t)}fromString(e){this.value=[];let t=0,r=0,n="",i=!1;do if(n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1,i){let e=this.value[0],t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:this.value=[];return}let r=parseInt(n,10);if(isNaN(r))return;e.valueDec=r+t,i=!1}else{let e=new lb;if(n>Number.MAX_SAFE_INTEGER){aq();let t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?(n=`{${n}}`,this.value[r].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}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}}lw.NAME="ObjectIdentifierValueBlock";class lv extends a8{constructor(e={}){super(e,lw),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()}}}a5.ObjectIdentifier=lv,lv.NAME="OBJECT IDENTIFIER";class lE extends a1(a2){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;let n=aU.vJ.toUint8Array(e);if(!aG(this,n,t,r))return -1;let i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,(128&i[e])!=0);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return(this.valueHexView=s,(128&i[this.blockLength-1])!=0)?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=aF(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 t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}let t=aK(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",aQ;let r=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),n=t.byteLength-1;for(let t=0;t<n;t++)r[t]=128|e[t];r[n]=e[n]}return r.buffer}toString(){return this.isHexOnly?aU.ep.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}lE.NAME="relativeSidBlock";class lS extends a3{constructor({value:e="",...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let n=t;for(;r>0;){let t=new lE;if(-1===(n=t.fromBER(e,n,r))){this.blockLength=0,this.error=t.error;break}this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){let r=[];for(let t=0;t<this.value.length;t++){let n=this.value[t].toBER(e);if(0===n.byteLength)return this.error=this.value[t].error,aQ;r.push(n)}return az(r)}fromString(e){this.value=[];let t=0,r=0,n="";do{n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1;let i=new lE;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))break;this.value.push(i)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();0!==r&&(e=`${e}.`),t?e+=n=`{${n}}`:e+=n}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}}lS.NAME="RelativeObjectIdentifierValueBlock";class lA extends a8{constructor(e={}){super(e,lS),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()}}}a5.RelativeObjectIdentifier=lA,lA.NAME="RelativeObjectIdentifier";class lI extends li{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}a5.Sequence=lI,lI.NAME="SEQUENCE";class lT extends li{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}a5.Set=lT,lT.NAME="SET";class l_ extends a1(a3){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=""}toJSON(){return{...super.toJSON(),value:this.value}}}l_.NAME="StringValueBlock";class lR extends l_{}lR.NAME="SimpleStringValueBlock";class lC extends a9{constructor({...e}={}){super(e,lR)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,aU.vJ.toUint8Array(e))}fromString(e){let t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}lC.NAME="SIMPLE STRING";class lk extends lC{fromBuffer(e){this.valueBlock.valueHexView=aU.vJ.toUint8Array(e);try{this.valueBlock.value=aU.ep.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=aU.ep.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(aU.ep.FromUtf8String(e)),this.valueBlock.value=e}}lk.NAME="Utf8StringValueBlock";class lB extends lk{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}a5.Utf8String=lB,lB.NAME="UTF8String";class lP extends lC{fromBuffer(e){this.valueBlock.value=aU.ep.ToUtf16String(e),this.valueBlock.valueHexView=aU.vJ.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(aU.ep.FromUtf16String(e))}}lP.NAME="BmpStringValueBlock";class lD extends lP{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}a5.BmpString=lD,lD.NAME="BMPString";class lN extends lC{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let n=0;n<t;n++){let t=aK(e.charCodeAt(n),8),i=new Uint8Array(t);if(i.length>4)continue;let s=4-i.length;for(let e=i.length-1;e>=0;e--)r[4*n+e+s]=i[e]}this.valueBlock.value=e}}lN.NAME="UniversalStringValueBlock";class lL extends lN{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}a5.UniversalString=lL,lL.NAME="UniversalString";class lx extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}a5.NumericString=lx,lx.NAME="NumericString";class lO extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}a5.PrintableString=lO,lO.NAME="PrintableString";class lM extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}a5.TeletexString=lM,lM.NAME="TeletexString";class lU extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}a5.VideotexString=lU,lU.NAME="VideotexString";class lF extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}a5.IA5String=lF,lF.NAME="IA5String";class lK extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}a5.GraphicString=lK,lK.NAME="GraphicString";class lV extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}a5.VisibleString=lV,lV.NAME="VisibleString";class lH extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}a5.GeneralString=lH,lH.NAME="GeneralString";class l$ extends lC{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}a5.CharacterString=l$,l$.NAME="CharacterString";class lq extends lV{constructor({value:e,valueDate:t,...r}={}){if(super(r),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 t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}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,aU.vJ.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);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 t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(null===t){this.error="Wrong input string for conversion";return}let r=parseInt(t[1],10);r>=50?this.year=1900+r:this.year=2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){let e=Array(7);return e[0]=a$(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=a$(this.month,2),e[2]=a$(this.day,2),e[3]=a$(this.hour,2),e[4]=a$(this.minute,2),e[5]=a$(this.second,2),e[6]="Z",e.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}}}a5.UTCTime=lq,lq.NAME="UTCTime";class lz extends lq{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(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,r=!1,n="",i="",s=0,o=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{let t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+")||-1!==n.indexOf("-"))throw Error("Wrong input string for conversion")}else{let e=1,t=n.indexOf("+"),r="";if(-1===t&&(t=n.indexOf("-"),e=-1),-1!==t){if(r=n.substring(t+1),n=n.substring(0,t),2!==r.length&&4!==r.length)throw Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(isNaN((i=parseInt(r.substring(2,4),10)).valueOf()))throw Error("Wrong input string for conversion");a=e*i}}}let l=n.indexOf(".");if(-1===l&&(l=n.indexOf(",")),-1!==l){let e=new Number(`0${n.substring(l)}`);if(isNaN(e.valueOf()))throw Error("Wrong input string for conversion");s=e.valueOf(),i=n.substring(0,l)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/ig,-1!==l)throw Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=60*s;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=60*s;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==l){let e=1e3*s;this.millisecond=Math.floor(e)}break;default:throw Error("Wrong input string for conversion")}let c=t.exec(i);if(null===c)throw Error("Wrong input string for conversion");for(let e=1;e<c.length;e++)switch(e){case 1:this.year=parseInt(c[e],10);break;case 2:this.month=parseInt(c[e],10);break;case 3:this.day=parseInt(c[e],10);break;case 4:this.hour=parseInt(c[e],10)+o;break;case 5:this.minute=parseInt(c[e],10)+a;break;case 6:this.second=parseInt(c[e],10);break;default:throw Error("Wrong input string for conversion")}if(!1===r){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){let e=[];return e.push(a$(this.year,4)),e.push(a$(this.month,2)),e.push(a$(this.day,2)),e.push(a$(this.hour,2)),e.push(a$(this.minute,2)),e.push(a$(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(a$(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}a5.GeneralizedTime=lz,lz.NAME="GeneralizedTime";class lG extends lB{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}a5.DATE=lG,lG.NAME="DATE";class lj extends lB{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}a5.TimeOfDay=lj,lj.NAME="TimeOfDay";class lW extends lB{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}a5.DateTime=lW,lW.NAME="DateTime";class lY extends lB{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}a5.Duration=lY,lY.NAME="Duration";class lQ extends lB{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}function lX(e){if(isNaN(e)||e<=0)throw new iJ("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,nm.O6)(e)}function lJ(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);let r=t.length/2,n=new Uint8Array(r),i=0,s=0;for(;i<r;)n[i]=parseInt(t.slice(s,s+2),16),i+=1,s+=2;return n}function lZ(e){let t=[];return e.forEach(function(e){let r=e.toString(16);r.length%2>0&&(r=`0${r}`),t.push(r)}),BigInt("0x"+t.join(""))}async function l0(e,t){let r=av.get(),n=new lI({value:[new ly({value:0}),new lI({value:[new lv({value:"1.2.840.113549.1.1.1"}),new la]}),new lh({valueHex:e.marshal()})]}),i=n.toBER(),s=new Uint8Array(i,0,i.byteLength),o=lX(16),a=await aM(nA,t,o,{c:1e4,dkLen:32}),l=lX(16),c=await r.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await r.subtle.encrypt({name:"AES-CBC",iv:l},c,s),h=new lI({value:[new lh({valueHex:o}),new ly({value:1e4}),new ly({value:32}),new lI({value:[new lv({value:"1.2.840.113549.2.11"}),new la]})]}),d=new lI({value:[new lv({value:"1.2.840.113549.1.5.13"}),new lI({value:[new lI({value:[new lv({value:"1.2.840.113549.1.5.12"}),h]}),new lI({value:[new lv({value:"2.16.840.1.101.3.4.1.42"}),new lh({valueHex:l})]})]})]}),p=new lI({value:[d,new lh({valueHex:u})]}),f=p.toBER(),g=new Uint8Array(f,0,f.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...(0,i5.B)(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}a5.TIME=lQ,lQ.NAME="TIME";let l1=8192;class l2{_key;constructor(e){this._key=e}verify(e,t){return aN(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new iJ("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new lI({value:[new lI({value:[new lv({value:"1.2.840.113549.1.1.1"}),new la]}),new lp({valueHex:new lI({value:[ly.fromBigInt(lZ((0,i2.m)(e.n,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.e,"base64url")))]}).toBER()})]}),r=t.toBER();return new Uint8Array(r,0,r.byteLength)}(this._key)}get bytes(){return eH.encode({Type:eK.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return ab(e)?e.then(({bytes:e})=>e):e.bytes}}class l3{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return lX(16)}sign(e){return aD(this._key,e)}get public(){if(null==this._publicKey)throw new iJ("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new l2(this._publicKey)}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new iJ("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new lI({value:[new ly({value:0}),ly.fromBigInt(lZ((0,i2.m)(e.n,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.e,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.d,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.p,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.q,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.dp,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.dq,"base64url"))),ly.fromBigInt(lZ((0,i2.m)(e.qi,"base64url")))]}),r=t.toBER();return new Uint8Array(r,0,r.byteLength)}(this._key)}get bytes(){return e$.encode({Type:eK.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return ab(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,i5.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return l0(this,e);if("libp2p-key"===t)return aS(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function l4(e){let t=function(e){let{result:t}=lr(e),r=t.valueBlock.value,n={n:(0,i5.B)(lJ(r[1].toBigInt()),"base64url"),e:(0,i5.B)(lJ(r[2].toBigInt()),"base64url"),d:(0,i5.B)(lJ(r[3].toBigInt()),"base64url"),p:(0,i5.B)(lJ(r[4].toBigInt()),"base64url"),q:(0,i5.B)(lJ(r[5].toBigInt()),"base64url"),dp:(0,i5.B)(lJ(r[6].toBigInt()),"base64url"),dq:(0,i5.B)(lJ(r[7].toBigInt()),"base64url"),qi:(0,i5.B)(lJ(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"};return n}(e);if(aO(t)>l1)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await aP(t);return new l3(r.privateKey,r.publicKey)}function l6(e){let t=function(e){let{result:t}=lr(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:(0,i5.B)(lJ(r[0].toBigInt()),"base64url"),e:(0,i5.B)(lJ(r[1].toBigInt()),"base64url")}}(e);if(aO(t)>l1)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new l2(t)}async function l5(e){if(aO(e)>l1)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await aP(e);return new l3(t.privateKey,t.publicKey)}async function l8(e){if(e>l1)throw new iJ("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await aB(e);return new l3(t.privateKey,t.publicKey)}function l9(e){try{sV.ProjectivePoint.fromHex(e)}catch(e){throw new iJ(String(e),"ERR_INVALID_PUBLIC_KEY")}}class l7{_key;constructor(e){l9(e),this._key=e}verify(e,t){return function(e,t,r){let n=i6.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(ab(n))return n.then(({digest:r})=>sV.verify(t,r,e)).catch(e=>{throw new iJ(String(e),"ERR_INVALID_INPUT")});try{return sV.verify(t,n.digest,e)}catch(e){throw new iJ(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return function(e){let t=sV.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}get bytes(){return eH.encode({Type:eK.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}async hash(){let e;let t=i6.sha256.digest(this.bytes);return ab(t)?{bytes:e}=await t:e=t.bytes,e}}class ce{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return sV.getPublicKey(e,!0)}catch(e){throw new iJ(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{sV.getPublicKey(e,!0)}catch(e){throw new iJ(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),l9(this._publicKey)}sign(e){return function(e,t){let r=i6.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(ab(r))return r.then(({digest:t})=>sV.sign(t,e).toDERRawBytes()).catch(e=>{throw new iJ(String(e),"ERR_INVALID_INPUT")});try{return sV.sign(r.digest,e).toDERRawBytes()}catch(e){throw new iJ(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new l7(this._publicKey)}marshal(){return this._key}get bytes(){return e$.encode({Type:eK.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,tI.f)(this.bytes,e.bytes)}hash(){let e=i6.sha256.digest(this.bytes);return ab(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,i5.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return aS(this.bytes,e);throw new iJ(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function ct(e){return new ce(e)}function cr(e){return new l7(e)}async function cn(){let e=sV.utils.randomPrivateKey();return new ce(e)}let ci={rsa:tg,ed25519:tf,secp256k1:ty};function cs(e){let t=Object.keys(ci).join(" / ");return new iJ(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function co(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return ci[e];throw cs(e)}async function ca(e,t){return co(e).generateKeyPair(t??2048)}function cl(e){let t=eH.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eK.RSA:return ci.rsa.unmarshalRsaPublicKey(r);case eK.Ed25519:return ci.ed25519.unmarshalEd25519PublicKey(r);case eK.Secp256k1:return ci.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw cs(t.Type??"unknown")}}function cc(e,t){return co(t=(t??"rsa").toLowerCase()),e.bytes}async function cu(e){let t=e$.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case eK.RSA:return ci.rsa.unmarshalRsaPrivateKey(r);case eK.Ed25519:return ci.ed25519.unmarshalEd25519PrivateKey(r);case eK.Secp256k1:return ci.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw cs(t.Type??"RSA")}}let ch={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};(z=eq||(eq={})).codec=()=>(null==f&&(f=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r})),f),z.encode=e=>(0,ss.LE)(e,z.codec()),z.decode=e=>(0,ss.C6)(e,z.codec());class cd{static createFromProtobuf=async e=>{let t=eq.decode(e),r=await oe(t.publicKey);return new cd({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw Error("Missing private key");let r=e.domain,n=e.codec,i=e.marshal(),s=cp(r,n,i),o=await cu(t.privateKey),a=await o.sign(s.subarray());return new cd({peerId:t,payloadType:n,payload:i,signature:a})};static openAndCertify=async(e,t)=>{let r=await cd.createFromProtobuf(e),n=await r.validate(t);if(!n)throw new iJ("envelope signature is not valid for the given domain",ch.ERR_SIGNATURE_NOT_VALID);return r};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:r,payload:n,signature:i}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=i}marshal(){if(null==this.peerId.publicKey)throw Error("Missing public key");return null==this.marshaled&&(this.marshaled=eq.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return(0,tI.f)(this.marshal(),e.marshal())}async validate(e){let t=cp(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw Error("Missing public key");let r=cl(this.peerId.publicKey);return r.verify(t.subarray(),this.signature)}}let cp=(e,t,r)=>{let n=(0,i2.m)(e),i=tE.cv(n.byteLength),s=tE.cv(t.length),o=tE.cv(r.length);return new tC(i,n,s,t,o,r)},cf=e=>e.toString().split("/").slice(1),cg=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),cy=e=>({match:t=>cg(t=>t===e).match(t),pattern:e}),cm=()=>({match:e=>cg(e=>"string"==typeof e).match(e),pattern:"{string}"}),cb=()=>({match:e=>cg(e=>!isNaN(parseInt(e))).match(e),pattern:"{number}"}),cw=()=>({match:e=>{if(e.length<2||"p2p"!==e[0]&&"ipfs"!==e[0]||!(e[1].startsWith("Q")||e[1].startsWith("1")))return!1;try{i3.base58btc.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),cv=()=>({match:e=>{if(e.length<2||"certhash"!==e[0])return!1;try{st.base64url.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),cE=e=>({match:t=>{let r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),cS=(...e)=>({match:t=>{let r;for(let n of e){let e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map(e=>e.pattern).join(", ")})`}),cA=(...e)=>({match:t=>{for(let r of e){let e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map(e=>e.pattern).join(", ")})`});function cI(...e){function t(t){let r=cf(t);for(let t of e){let e=t.match(r);if(!1===e)return!1;r=e}return r}return{matches:function(e){let r=t(e);return!1!==r},exactMatch:function(e){let r=t(e);return!1!==r&&0===r.length}}}let cT=cA(cy("dns4"),cm()),c_=cA(cy("dns6"),cm()),cR=cA(cy("dnsaddr"),cm()),cC=cA(cy("dns"),cm());cI(cT),cI(c_),cI(cR),cI(cS(cC,cR,cT,c_));let ck=cA(cy("ip4"),cg(ov)),cB=cA(cy("ip6"),cg(oE)),cP=cS(ck,cB),cD=cS(cP,cC,cT,c_,cR),cN=cI(cD);cI(ck),cI(cB),cI(cP);let cL=cA(cD,cy("tcp"),cb()),cx=cA(cD,cy("udp"),cb());cI(cL),cI(cx);let cO=cA(cx,cy("quic")),cM=cA(cx,cy("quic-v1")),cU=cS(cO,cM);cI(cO),cI(cM);let cF=cS(cD,cL,cx,cO,cM),cK=cS(cA(cF,cy("ws"),cE(cw())));cI(cK);let cV=cS(cA(cF,cy("wss"),cE(cw())),cA(cF,cy("tls"),cy("ws"),cE(cw())));cI(cV);let cH=cA(cx,cy("webrtc-direct"),cE(cv()),cE(cv()),cE(cw()));cI(cH);let c$=cA(cM,cy("webtransport"),cE(cv()),cE(cv()),cE(cw()));cI(c$);let cq=cS(cK,cV,cA(cL,cE(cw())),cA(cU,cE(cw())),cA(cD,cE(cw())),cH,c$,cw());cI(cq);let cz=cA(cq,cy("p2p-circuit"),cw()),cG=cI(cz),cj=cS(cA(cq,cy("p2p-circuit"),cy("webrtc"),cE(cw())),cA(cq,cy("webrtc"),cE(cw())),cy("webrtc"));cI(cj);let cW=cS(cA(cD,cy("tcp"),cb(),cy("http"),cE(cw())),cA(cD,cy("http"),cE(cw())));cI(cW);let cY=cS(cA(cD,cy("tcp"),cS(cA(cy("443"),cy("http")),cA(cb(),cy("https"))),cE(cw())),cA(cD,cy("tls"),cy("http"),cE(cw())),cA(cD,cy("https"),cE(cw())));function cQ(e,t){let r=rF(e,t),n={read:async(e,t)=>{let n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map(e=>t.encode(e)),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}cI(cY);var cX=r(9598);let cJ="object"==typeof window&&"object"==typeof document&&9===document.nodeType,cZ=cX(),c0=cJ&&!cZ,c1=cZ&&!cJ,c2=cZ&&cJ,c3=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!cZ,c4="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV;let c6="undefined"!=typeof navigator&&"ReactNative"===navigator.product;(G=ez||(ez={})).codec=()=>(null==g&&(g=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(let r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(let r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r})),g),G.encode=e=>(0,ss.LE)(e,G.codec()),G.decode=e=>(0,ss.C6)(e,G.codec());let c5={protocolPrefix:"ipfs",timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0};class c8{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t={}){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.log=e.logger.forComponent("libp2p:identify"),this.identifyProtocolStr=`/${t.protocolPrefix??c5.protocolPrefix}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??c5.protocolPrefix}/id/push/1.0.0`,this.timeout=t.timeout??c5.timeout,this.maxInboundStreams=t.maxInboundStreams??c5.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??c5.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??c5.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??c5.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??c5.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??c5.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??c5.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??c5.protocolPrefix}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??c5.runOnConnectionOpen)&&e.events.addEventListener("connection:open",e=>{let t=e.detail;this.identify(t).catch(e=>{this.log.error("error during identify trigged by connection:open",e)})}),e.events.addEventListener("self:peer:update",e=>{this.push().catch(e=>{this.log.error(e)})}),this.host.agentVersion===`${e.nodeInfo.name}/${e.nodeInfo.version}`&&(c3||c1?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(c0||c4||c2||c6)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:(0,i2.m)(this.host.agentVersion),ProtocolVersion:(0,i2.m)(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(e=>e.decapsulateCode(oR("p2p").code)),r=new am({peerId:this.peerId,multiaddrs:t}),n=await cd.seal(r,this.peerId),i=this.registrar.getProtocols(),s=await this.peerStore.get(this.peerId),o=(0,i5.B)(s.metadata.get("AgentVersion")??(0,i2.m)(this.host.agentVersion)),a=(0,i5.B)(s.metadata.get("ProtocolVersion")??(0,i2.m)(this.host.protocolVersion)),l=e.map(async e=>{let r;let s=AbortSignal.timeout(this.timeout);rA(1/0,s);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:s,runOnTransientConnection:this.runOnTransientConnection});let l=cQ(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(ez);await l.write({listenAddrs:t.map(e=>e.bytes),signedPeerRecord:n.marshal(),protocols:i,agentVersion:o,protocolVersion:a},{signal:s}),await r.close({signal:s})}catch(e){this.log.error("could not push identify update to peer",e),r?.abort(e)}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{let r=await this.peerStore.get(t.remotePeer);if(!r.protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}})),await this.pushToConnections(e)}async _identify(e,t={}){let r;if(null==t.signal){let e=AbortSignal.timeout(this.timeout);rA(1/0,e),t={...t,signal:e}}try{r=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});let n=cQ(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(ez),i=await n.read(t);return await r.close(t),i}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){let r=await this._identify(e,t),{publicKey:n,protocols:i,observedAddr:s}=r;if(null==n)throw new iJ("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");let o=await oe(n);if(!e.remotePeer.equals(o))throw new iJ("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new iJ("identified peer is our own peer id?","ERR_INVALID_PEER");let a=function(e){if(null!=e&&e.length>0)try{return oG(e)}catch{}}(s);return this.log("identify completed for peer %p and protocols %o",o,i),this.log("our observed address is %a",a),null!=a&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",a),this.addressManager.addObservedAddr(a)),this.#s(e,r)}async _handleIdentify(e){let{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);rA(1/0,n);try{let e=this.peerId.publicKey??new Uint8Array(0),i=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map(e=>e.decapsulateCode(oR("p2p").code)),o=i.peerRecordEnvelope;if(s.length>0&&null==o){let e=new am({peerId:this.peerId,multiaddrs:s}),t=await cd.seal(e,this.peerId);o=t.marshal().subarray()}let a=t.remoteAddr.bytes;cN.matches(t.remoteAddr)||(a=void 0);let l=cQ(r).pb(ez);await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:s.map(e=>e.bytes),signedPeerRecord:o,observedAddr:a,protocols:i.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}async _handlePush(e){let{connection:t,stream:r}=e;try{if(this.peerId.equals(t.remotePeer))throw Error("received push from ourselves?");let e={signal:AbortSignal.timeout(this.timeout)},n=cQ(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(ez),i=await n.read(e);await r.close(e),await this.#s(t,i)}catch(e){this.log.error("received invalid message",e),r.abort(e);return}this.log("handled push from %p",t.remotePeer)}async #s(e,t){let r;if(this.log("received identify from %p",e.remotePeer),null==t)throw new iJ("message was null or undefined","ERR_INVALID_MESSAGE");let n={};if(t.listenAddrs.length>0&&(n.addresses=t.listenAddrs.map(e=>({isCertified:!1,multiaddr:oG(e)}))),t.protocols.length>0&&(n.protocols=t.protocols),null!=t.publicKey){n.publicKey=t.publicKey;let r=await oe(t.publicKey);if(!r.equals(e.remotePeer))throw new iJ("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY")}if(null!=t.signedPeerRecord){let i;this.log("received signedPeerRecord from %p",e.remotePeer);let s=t.signedPeerRecord,o=await cd.openAndCertify(s,am.DOMAIN),a=am.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new iJ("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new iJ("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{i=await this.peerStore.get(a.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=i&&(n.metadata=i.metadata,null!=i.peerRecordEnvelope)){let e=await cd.createFromProtobuf(i.peerRecordEnvelope),t=am.createFromProtobuf(e.payload);t.seqNumber>=a.seqNumber&&(this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),a=t,s=i.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(e=>({isCertified:!0,multiaddr:e})),r={seq:a.seqNumber,addresses:a.multiaddrs}}else this.log("%p did not send a signed peer record",e.remotePeer);if(this.log("patching %p with",e.remotePeer,n),await this.peerStore.patch(e.remotePeer,n),null!=t.agentVersion||null!=t.protocolVersion){let r={};null!=t.agentVersion&&(r.AgentVersion=(0,i2.m)(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=(0,i2.m)(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,r),await this.peerStore.merge(e.remotePeer,{metadata:r})}let i={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map(e=>oG(e)),observedAddr:null==t.observedAddr?void 0:oG(t.observedAddr),protocols:t.protocols,signedPeerRecord:r,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:i}),i}}function c9(e,t){let r=(function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")})(e).return?.();null!=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally&&r.catch(e=>{t.error("could not cause iterator to return",e)})}let c7=()=>{let e=Error("Delay aborted");return e.name="AbortError",e},ue=new WeakMap,ut=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:i}={})=>{let s,o,a;if(i?.aborted)return Promise.reject(c7());let l=e??clearTimeout,c=()=>{l(s),a(c7())},u=()=>{i&&i.removeEventListener("abort",c)},h=new Promise((e,i)=>{o=()=>{u(),e(n)},a=i,s=(t??setTimeout)(o,r)});return i&&i.addEventListener("abort",c,{once:!0}),ue.set(h,()=>{l(s),s=null,o()}),h}}();class ur{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??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new un}async consume(e,t=1,r={}){let n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(n,s.consumedPoints,this.blockDuration)),new iJ("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let e=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=s.consumedPoints*this.execEvenlyMinDelayMs),await ut(e)}return s}penalty(e,t=1,r={}){let n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,r={}){let n=this.getKey(e),i=this._getKeySecDuration(r),s=this.memoryStorage.incrby(n,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){let r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){let n=(r>=0?r:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return null!=t&&(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)}}class un{storage;constructor(){this.storage=new Map}incrby(e,t,r){let n=this.storage.get(e);if(null!=n){let e=null!=n.expiresAt?n.expiresAt.getTime()-new Date().getTime():-1;if(null==n.expiresAt||e>0)return n.value+=t,{remainingPoints:0,msBeforeNext:e,consumedPoints:n.value,isFirstInDuration:!1}}return this.set(e,t,r)}set(e,t,r){let n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,s),n>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(null!=t){let e=null!=t.expiresAt?t.expiresAt.getTime()-new Date().getTime():-1;return{remainingPoints:0,msBeforeNext:e,consumedPoints:t.value,isFirstInDuration:!1}}}delete(e){let t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}(j=eG||(eG={}))[j.NEW_STREAM=0]="NEW_STREAM",j[j.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",j[j.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",j[j.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",j[j.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",j[j.RESET_RECEIVER=5]="RESET_RECEIVER",j[j.RESET_INITIATOR=6]="RESET_INITIATOR";let ui=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),us=Object.freeze({NEW_STREAM:eG.NEW_STREAM,MESSAGE:eG.MESSAGE_INITIATOR,CLOSE:eG.CLOSE_INITIATOR,RESET:eG.RESET_INITIATOR}),uo=Object.freeze({MESSAGE:eG.MESSAGE_RECEIVER,CLOSE:eG.CLOSE_RECEIVER,RESET:eG.RESET_RECEIVER});class ua{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=1048576,t=4194304){this._buffer=new tC,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("ERR_MSG_TOO_BIG"===e.code)throw e;break}let{id:e,type:r,length:n,offset:i}=this._headerInfo,s=this._buffer.length-i;if(s<n)break;let o={id:e,type:r};(r===eG.NEW_STREAM||r===eG.MESSAGE_INITIATOR||r===eG.MESSAGE_RECEIVER)&&(o.data=this._buffer.sublist(i,i+n)),t.push(o),this._buffer.consume(i+n),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:r}=ul(e),{value:n,offset:i}=ul(e,r),s=7&t;if(null==ui[s])throw Error(`Invalid type received: ${s}`);if(n>this._maxMessageSize)throw Object.assign(Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:s,offset:r+i,length:n}}}function ul(e,t=0){let r,n=0,i=0,s=t,o=e.length;do{if(s>=o||i>49)throw t=0,RangeError("Could not decode varint");r=e.get(s++),n+=i<28?(127&r)<<i:(127&r)*Math.pow(2,i),i+=7}while(r>=128);return{value:n,offset:t=s-t}}class uc{_pool;_poolOffset;constructor(){this._pool=(0,tS.E)(10240),this._poolOffset=0}write(e,t){let r=this._pool,n=this._poolOffset;tE.cv(e.id<<3|e.type,r,n),n+=tE.P$(e.id<<3|e.type),(e.type===eG.NEW_STREAM||e.type===eG.MESSAGE_INITIATOR||e.type===eG.MESSAGE_RECEIVER)&&null!=e.data?(tE.cv(e.data.length,r,n),n+=tE.P$(e.data.length)):(tE.cv(0,r,n),n+=tE.P$(0));let i=r.subarray(this._poolOffset,n);10240-n<100?(this._pool=(0,tS.E)(10240),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===eG.NEW_STREAM||e.type===eG.MESSAGE_INITIATOR||e.type===eG.MESSAGE_RECEIVER)&&null!=e.data&&t.append(e.data)}}let uu=new uc;async function*uh(e){for await(let t of e){let e=new tC;uu.write(t,e),yield e}}function ud(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class up{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=tx(),this.closed=tx(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=tF({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new iJ(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if("outbound"===this.direction){let e=this.sendNewStream(t);ud(e)&&await e}let r=()=>{c9(e,this.log)};try{for await(let n of(this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source"),e)){n=n instanceof Uint8Array?new tC(n):n;let e=this.sendData(n,t);ud(e)&&(this.sendingData=tx(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await rL(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await rL(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await rL(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await rL(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();ud(t)&&t.catch(e=>{this.log.error("error sending reset message",e)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;let e=new iJ("stream reset","ERR_STREAM_RESET");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if("closing"===this.readStatus||"closed"===this.readStatus){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if("closing"===this.writeStatus||"closed"===this.writeStatus){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class uf extends up{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?us:uo,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:us.NEW_STREAM,data:new tC((0,i2.m)(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function ug(e){let t={...e,type:`${ui[e.type]} (${e.type})`};return e.type===eG.NEW_STREAM&&(t.data=(0,i5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray())),(e.type===eG.MESSAGE_INITIATOR||e.type===eG.MESSAGE_RECEIVER)&&(t.data=(0,i5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class uy{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=tF({objectMode:!0,onEnd:()=>{for(let e of this._streams.initiators.values())e.destroy();for(let e of this._streams.receivers.values())e.destroy()}}),this.source=tV(this._source,e=>uh(e)),this.closeController=new AbortController,this.rateLimiter=new ur({points:t.disconnectThreshold??5,duration:1})}[Symbol.toStringTag]="@libp2p/mplex";[og]=["@libp2p/stream-multiplexing"];get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw Error("Muxer already closed");let t=this._streamId++;e=null==e?t.toString():e.toString();let r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async e=>e.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){let{id:t,name:r,type:n,registry:i}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new iJ("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(i.has(t))throw Error(`${n} stream ${t} already exists!`);let s=async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,ug(e)),this._source.push(e)},o=function(e){let{id:t,name:r,send:n,onEnd:i,type:s="initiator",maxMsgSize:o=1048576}=e;return new uf({id:"initiator"===s?`i${t}`:`r${t}`,streamId:t,name:`${null==r?t:r}`,direction:"initiator"===s?"outbound":"inbound",maxDataSize:o,onEnd:i,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}({id:t,name:r,send:s,type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,o.protocol),i.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(o)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return i.set(t,o),o}_createSink(){let e=async e=>{let t=()=>{c9(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{let t=new ua(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let r of e)for(let e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}};return e}async _handleIncoming(e){let{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",ug(e)),e.type===eG.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:eG.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(Error("Too many open streams"))}return}let r=this._newReceiverStream({id:t,name:(0,i5.B)(e.data instanceof Uint8Array?e.data:e.data.subarray())});null!=this._init.onIncomingStream&&this._init.onIncomingStream(r);return}let n=(1&r)==1?this._streams.initiators:this._streams.receivers,i=n.get(t);if(null==i){this.log("missing stream %s for message type %s",t,ui[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(Error("Too many messages for missing streams"))}return}let s=this._init.maxStreamBufferSize??4194304;try{switch(r){case eG.MESSAGE_INITIATOR:case eG.MESSAGE_RECEIVER:if(i.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===eG.MESSAGE_INITIATOR?eG.RESET_RECEIVER:eG.RESET_INITIATOR}),new iJ("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");i.sourcePush(e.data);break;case eG.CLOSE_INITIATOR:case eG.CLOSE_RECEIVER:i.remoteCloseWrite();break;case eG.RESET_INITIATOR:case eG.RESET_RECEIVER:i.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),i.abort(e)}}}class um{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new uy(this.components,{...e,...this._init})}}var ub=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(let t of e)return t})();for(let t of e)return t};let uw="ERR_WRONG_PING_ACK";class uv{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnTransientConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnTransientConnection=t.runOnTransientConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);let{stream:t}=e,r=Date.now();tV(t,t).catch(t=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,t)}).finally(()=>{let t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)})}async ping(e,t={}){let r;this.log("pinging %p",e);let n=Date.now(),i=lX(32),s=await this.components.connectionManager.openConnection(e,t),o=()=>{};if(null==t.signal){let e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),o=()=>{r?.abort(new iJ("ping timeout",i0))},t.signal?.addEventListener("abort",o,{once:!0});let e=await tV([i],r,async e=>ub(e)),a=Date.now()-n;if(null==e)throw new iJ(`Did not receive a ping ack after ${a}ms`,uw);if(!(0,tI.f)(i,e.subarray()))throw new iJ(`Received wrong ping ack after ${a}ms`,uw);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),r?.abort(e),e}finally{t.signal?.removeEventListener("abort",o),null!=r&&await r.close()}}}let uE=Symbol.for("@libp2p/transport");(W=ej||(ej={}))[W.FATAL_ALL=0]="FATAL_ALL",W[W.NO_FATAL=1]="NO_FATAL";let uS=[oR("tcp").code,oR("dns").code,oR("dnsaddr").code,oR("dns4").code,oR("dns6").code];function uA(e){let t;try{t=oR("sni").code}catch(e){return null}for(let[r,n]of e)if(r===t&&void 0!==n)return n;return null}function uI(e){return e.some(([e,t])=>e===oR("tls").code)}function uT(e,t,r){let n=u_[oR(e).name];if(void 0===n)throw Error(`Can't interpret protocol ${oR(e).name}`);let i=n(t,r);return e===oR("ip6").code?`[${i}]`:i}let u_={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`tcp://${uT(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`udp://${uT(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${uT(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${uT(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{let r=uI(t),n=uA(t);if(r&&null!==n)return`https://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=uT(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${r?"https://":"http://"}${s}`},"http-path":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=uT(r[0],r[1]??"",t),i=decodeURIComponent(e);return`${n}/${i}`},tls:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return uT(r[0],r[1]??"",t)},sni:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return uT(r[0],r[1]??"",t)},https:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=uT(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{let r=uI(t),n=uA(t);if(r&&null!==n)return`wss://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=uT(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${r?"wss://":"ws://"}${s}`},wss:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=uT(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${uT(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${uT(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return`${uT(r[0],r[1]??"",t)}/p2p-webrtc-direct`}};var uR=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",s)}function i(){n(),t()}function s(t){n(),r(t.error??Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",i),e.addEventListener("error",s)})},uC=(e,t)=>{(t=t??{}).closeOnEnd=!1!==t.closeOnEnd;let r=async r=>{for await(let t of r){try{await uR(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise((t,r)=>{e.addEventListener("close",e=>{if(e.wasClean||1006===e.code)t();else{let t=Object.assign(Error("ws error"),{event:e});r(t)}}),setTimeout(()=>{e.close()})})};return r},uk=r(5986);function uB(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&"number"==typeof e?.byteLength}var uP=e=>{let t;e.binaryType="arraybuffer";let r=async()=>{await new Promise((r,n)=>{if(i){r();return}if(null!=t){n(t);return}let s=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{s(r)},a=t=>{s(()=>{n(t.error??Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",o),e.addEventListener("error",a)})},n=async function*(){let t=new uk.zN(({push:t,stop:r,fail:n})=>{let i=e=>{let r=null;"string"==typeof e.data&&(r=(0,i2.m)(e.data)),uB(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},s=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",i),e.addEventListener("error",s),e.addEventListener("close",r),()=>{e.removeEventListener("message",i),e.removeEventListener("error",s),e.removeEventListener("close",r)}},{highWaterMark:1/0});for await(let e of(await r(),t))yield uB(e)?new Uint8Array(e):e}(),i=1===e.readyState;return e.addEventListener("open",()=>{i=!0,t=null}),e.addEventListener("close",()=>{i=!1,t=null}),e.addEventListener("error",r=>{i||(t=r.error??Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(n,{connected:r})},uD=(e,t)=>{t=t??{};let r=uP(e),n=t.remoteAddress,i=t.remotePort;if(null!=e.url)try{let t=new URL(e.url);n=t.hostname,i=parseInt(t.port,10)}catch{}if(null==n||null==i)throw Error("Remote connection did not have address and/or port");let s={sink:uC(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(t=>{e.addEventListener("close",()=>{t()}),e.close()})},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:i,socket:e};return s},uN=WebSocket;let uL={"http:":"ws:","https:":"wss:"};var ux=(e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){let r=t.protocol??"ws:",n=t.host,i=null!=t.port&&n?.endsWith(`:${t.port}`)!==!0?`:${t.port}`:"";e=`${r}//${n}${i}${e}`}let r=new URL(e);for(let[e,t]of Object.entries(uL))r.protocol===e&&(r.protocol=t);return r};function uO(e){return e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return o5.matches(t)})}class uM{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[uE]=!0;[Symbol.toStringTag]="@libp2p/websockets";[og]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let r=await this._connect(e,t),n=function(e,t,r){let n=r.logger.forComponent("libp2p:websockets:maconn"),i={log:n,async sink(t){try{await e.sink(async function*(){for await(let e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){let r=Date.now();if(null==t.signal){let e=AbortSignal.timeout(500);t={...t,signal:e}}let s=()=>{let{host:e,port:t}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new iJ("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),i.timeline.close=Date.now()}},abort(t){let{host:r,port:s}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,s,t),e.destroy(),i.timeline.close=Date.now()}};return e.socket.addEventListener("close",()=>{null==i.timeline.close&&(i.timeline.close=Date.now())},{once:!0}),i}(r,e,{logger:this.logger});this.log("new outbound connection %s",n.remoteAddr);let i=await t.upgrader.upgradeOutbound(n);return this.log("outbound connection %s upgraded",n.remoteAddr),i}async _connect(e,t){let r;if(t?.signal?.aborted===!0)throw new iX;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=tx(),s=function(e,t){let r="undefined"==typeof window?void 0:window.location;t=t??{};let n=ux(e,r),i=new uN(n.toString(),t.websocket);return uD(i,t)}(function(e,t){let r=oG(e),n=r.stringTuples(),i=n.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=oR(i[0]),o=u_[s.name];if(null==o)throw Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return uS.includes(i[0])&&(a=a.replace(/^.*:\/\//,""),a="443"===i[1]?`https://${a}`:`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString()).endsWith("/")&&(a=a.substring(0,a.length-1)),a}(e),this.init);if(s.socket.addEventListener("error",()=>{let t=new iJ(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),i.reject(t)}),null==t.signal)return await Promise.race([s.connected(),i.promise]),this.log("connected %s",e),s;let o=new Promise((e,n)=>{if(r=()=>{n(new iX),s.close().catch(e=>{this.log.error("error closing raw socket",e)})},t?.signal?.aborted===!0){r();return}t?.signal?.addEventListener("abort",r)});try{await Promise.race([o,i.promise,s.connected()])}finally{null!=r&&t?.signal?.removeEventListener("abort",r)}return this.log("connected %s",e),s}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}({logger:this.logger},{...this.init,...e})}listenFilter(e){return(e=Array.isArray(e)?e:[e],this.init?.filter!=null)?this.init?.filter(e):c0||c4?uO(e):e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return o4.matches(t)||o5.matches(t)})}dialFilter(e){return this.listenFilter(e)}}let uU="StrictSign",uF="StrictNoSign";(Y=eW||(eW={})).Accept="accept",Y.Ignore="ignore",Y.Reject="reject";let uK="/floodsub/1.0.0",uV="/meshsub/1.0.0",uH="/meshsub/1.1.0",u$={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};(X=(Q=eY||(eY={})).SubOpts||(Q.SubOpts={})).codec=()=>(null==m&&(m=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&(t.uint32(18),t.string(e.topic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;default:e.skipType(7&t)}}return n})),m),X.encode=e=>(0,ss.LE)(e,X.codec()),X.decode=(e,t)=>(0,ss.C6)(e,X.codec(),t),(J=Q.Message||(Q.Message={})).codec=()=>(null==b&&(b=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.from&&(t.uint32(10),t.bytes(e.from)),null!=e.data&&(t.uint32(18),t.bytes(e.data)),null!=e.seqno&&(t.uint32(26),t.bytes(e.seqno)),null!=e.topic&&""!==e.topic&&(t.uint32(34),t.string(e.topic)),null!=e.signature&&(t.uint32(42),t.bytes(e.signature)),null!=e.key&&(t.uint32(50),t.bytes(e.key)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={topic:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.from=e.bytes();break;case 2:n.data=e.bytes();break;case 3:n.seqno=e.bytes();break;case 4:n.topic=e.string();break;case 5:n.signature=e.bytes();break;case 6:n.key=e.bytes();break;default:e.skipType(7&t)}}return n})),b),J.encode=e=>(0,ss.LE)(e,J.codec()),J.decode=(e,t)=>(0,ss.C6)(e,J.codec(),t),(Z=Q.ControlMessage||(Q.ControlMessage={})).codec=()=>(null==w&&(w=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.ihave)for(let r of e.ihave)t.uint32(10),Q.ControlIHave.codec().encode(r,t);if(null!=e.iwant)for(let r of e.iwant)t.uint32(18),Q.ControlIWant.codec().encode(r,t);if(null!=e.graft)for(let r of e.graft)t.uint32(26),Q.ControlGraft.codec().encode(r,t);if(null!=e.prune)for(let r of e.prune)t.uint32(34),Q.ControlPrune.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={ihave:[],iwant:[],graft:[],prune:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:if(r.limits?.ihave!=null&&n.ihave.length===r.limits.ihave)throw new ss.sv('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");n.ihave.push(Q.ControlIHave.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.iwant!=null&&n.iwant.length===r.limits.iwant)throw new ss.sv('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");n.iwant.push(Q.ControlIWant.codec().decode(e,e.uint32()));break;case 3:if(r.limits?.graft!=null&&n.graft.length===r.limits.graft)throw new ss.sv('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");n.graft.push(Q.ControlGraft.codec().decode(e,e.uint32()));break;case 4:if(r.limits?.prune!=null&&n.prune.length===r.limits.prune)throw new ss.sv('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");n.prune.push(Q.ControlPrune.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return n})),w),Z.encode=e=>(0,ss.LE)(e,Z.codec()),Z.decode=(e,t)=>(0,ss.C6)(e,Z.codec(),t),(ee=Q.ControlIHave||(Q.ControlIHave={})).codec=()=>(null==v&&(v=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(let r of e.messageIDs)t.uint32(18),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messageIDs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.topicID=e.string();break;case 2:if(r.limits?.messageIDs!=null&&n.messageIDs.length===r.limits.messageIDs)throw new ss.sv('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes());break;default:e.skipType(7&t)}}return n})),v),ee.encode=e=>(0,ss.LE)(e,ee.codec()),ee.decode=(e,t)=>(0,ss.C6)(e,ee.codec(),t),(et=Q.ControlIWant||(Q.ControlIWant={})).codec=()=>(null==E&&(E=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageIDs)for(let r of e.messageIDs)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messageIDs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();if(t>>>3==1){if(r.limits?.messageIDs!=null&&n.messageIDs.length===r.limits.messageIDs)throw new ss.sv('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes())}else e.skipType(7&t)}return n})),E),et.encode=e=>(0,ss.LE)(e,et.codec()),et.decode=(e,t)=>(0,ss.C6)(e,et.codec(),t),(er=Q.ControlGraft||(Q.ControlGraft={})).codec=()=>(null==S&&(S=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();t>>>3==1?n.topicID=e.string():e.skipType(7&t)}return n})),S),er.encode=e=>(0,ss.LE)(e,er.codec()),er.decode=(e,t)=>(0,ss.C6)(e,er.codec(),t),(en=Q.ControlPrune||(Q.ControlPrune={})).codec=()=>(null==A&&(A=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.peers)for(let r of e.peers)t.uint32(18),Q.PeerInfo.codec().encode(r,t);null!=e.backoff&&(t.uint32(24),t.uint64Number(e.backoff)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={peers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.topicID=e.string();break;case 2:if(r.limits?.peers!=null&&n.peers.length===r.limits.peers)throw new ss.sv('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");n.peers.push(Q.PeerInfo.codec().decode(e,e.uint32()));break;case 3:n.backoff=e.uint64Number();break;default:e.skipType(7&t)}}return n})),A),en.encode=e=>(0,ss.LE)(e,en.codec()),en.decode=(e,t)=>(0,ss.C6)(e,en.codec(),t),(ei=Q.PeerInfo||(Q.PeerInfo={})).codec=()=>(null==I&&(I=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.peerID&&(t.uint32(10),t.bytes(e.peerID)),null!=e.signedPeerRecord&&(t.uint32(18),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:n.peerID=e.bytes();break;case 2:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n})),I),ei.encode=e=>(0,ss.LE)(e,ei.codec()),ei.decode=(e,t)=>(0,ss.C6)(e,ei.codec(),t),Q.codec=()=>(null==y&&(y=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.subscriptions)for(let r of e.subscriptions)t.uint32(10),Q.SubOpts.codec().encode(r,t);if(null!=e.messages)for(let r of e.messages)t.uint32(18),Q.Message.codec().encode(r,t);null!=e.control&&(t.uint32(26),Q.ControlMessage.codec().encode(e.control,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={subscriptions:[],messages:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){let t=e.uint32();switch(t>>>3){case 1:if(r.limits?.subscriptions!=null&&n.subscriptions.length===r.limits.subscriptions)throw new ss.sv('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");n.subscriptions.push(Q.SubOpts.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new ss.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(Q.Message.codec().decode(e,e.uint32()));break;case 3:n.control=Q.ControlMessage.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return n})),y),Q.encode=e=>(0,ss.LE)(e,Q.codec()),Q.decode=(e,t)=>(0,ss.C6)(e,Q.codec(),t);class uq{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let e=0;e<t;e++)this.history[e]=[]}get size(){return this.msgs.size}put(e,t,r=!1){let{msgIdStr:n}=e;return!this.msgs.has(n)&&(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),!r&&this.notValidatedCount++,!0)}observeDuplicate(e,t){let r=this.msgs.get(e);null==r||r.validated||r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let r=this.msgs.get(e);if(null==r)return null;let n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){let t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach(r=>{let n=this.msgs.get(r.msgIdStr);if(n?.validated&&e.has(r.topic)){let e=t.get(r.topic);null==e&&(e=[],t.set(r.topic,e)),e.push(r.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(null==t)return null;!t.validated&&this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){let e=this.history[this.history.length-1];e.forEach(e=>{let t=this.msgs.get(e.msgIdStr);null!=t&&(this.msgs.delete(e.msgIdStr),!t.validated&&this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function uz(e){switch(e){case eW.Ignore:return eJ.Ignore;case eW.Reject:return eJ.Reject;default:throw Error("Unreachable")}}(es=eQ||(eQ={})).StrictSign="StrictSign",es.StrictNoSign="StrictNoSign",(eo=eX||(eX={}))[eo.Signing=0]="Signing",eo[eo.Anonymous=1]="Anonymous",(ea=eJ||(eJ={})).Error="error",ea.Ignore="ignore",ea.Reject="reject",ea.Blacklisted="blacklisted",(el=eZ||(eZ={})).InvalidSignature="invalid_signature",el.InvalidSeqno="invalid_seqno",el.InvalidPeerId="invalid_peerid",el.SignaturePresent="signature_present",el.SeqnoPresent="seqno_present",el.FromPresent="from_present",el.TransformFailed="transform_failed",(ec=e0||(e0={})).duplicate="duplicate",ec.invalid="invalid",ec.valid="valid",(eu=e1||(e1={})).forward="forward",eu.publish="publish",(eh=e2||(e2={})).Fanout="fanout",eh.Random="random",eh.Subscribed="subscribed",eh.Outbound="outbound",eh.NotEnough="not_enough",eh.Opportunistic="opportunistic",(ed=e3||(e3={})).Dc="disconnected",ed.BadScore="bad_score",ed.Prune="prune",ed.Excess="excess",(ep=e4||(e4={})).GraftBackoff="graft_backoff",ep.BrokenPromise="broken_promise",ep.MessageDeficit="message_deficit",ep.IPColocation="IP_colocation",(ef=e6||(e6={})).LowScore="low_score",ef.MaxIhave="max_ihave",ef.MaxIasked="max_iasked",(eg=e5||(e5={})).graylist="graylist",eg.publish="publish",eg.gossip="gossip",eg.mesh="mesh";let uG="ERR_INVALID_PEER_SCORE_PARAMS",uj={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:36e5},uW={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3},uY={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function uQ(e,t,r=()=>!0){let n=new Set;if(t<=0)return n;for(let i of e){if(n.size>=t)break;r(i)&&(n.add(i),e.delete(i))}return n}class uX extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return void 0===t&&(t=this.getDefault(),this.set(e,t)),t}}function uJ(e,t,r,n){let i=0;Object.entries(t.topics).forEach(([e,t])=>{let n=r.topics[e];if(void 0===n)return;let s=0;if(t.inMesh){let e=t.meshTime/n.timeInMeshQuantum;e>n.timeInMeshCap&&(e=n.timeInMeshCap),s+=e*n.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>n.firstMessageDeliveriesCap&&(o=n.firstMessageDeliveriesCap),s+=o*n.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<n.meshMessageDeliveriesThreshold){let e=n.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;s+=e*e*n.meshMessageDeliveriesWeight}let a=t.meshFailurePenalty;s+=a*n.meshFailurePenaltyWeight;let l=t.invalidMessageDeliveries*t.invalidMessageDeliveries;s+=l*n.invalidMessageDeliveriesWeight,i+=s*n.topicWeight}),r.topicScoreCap>0&&i>r.topicScoreCap&&(i=r.topicScoreCap);let s=r.appSpecificScore(e);if(i+=s*r.appSpecificWeight,t.knownIPs.forEach(e=>{if(r.IPColocationFactorWhitelist.has(e))return;let t=n.get(e),s=null!=t?t.size:0;if(s>r.IPColocationFactorThreshold){let e=s-r.IPColocationFactorThreshold;i+=e*e*r.IPColocationFactorWeight}}),t.behaviourPenalty>r.behaviourPenaltyThreshold){let e=t.behaviourPenalty-r.behaviourPenaltyThreshold;i+=e*e*r.behaviourPenaltyWeight}return i}var uZ=r(2185);(ey=e8||(e8={}))[ey.unknown=0]="unknown",ey[ey.valid=1]="valid",ey[ey.invalid=2]="invalid",ey[ey.ignored=3]="ignored";class u0{records;queue;constructor(){this.records=new Map,this.queue=new uZ}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:e8.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;null!=t&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}}class u1{params;metrics;peerStats=new Map;peerIPs=new uX(()=>new Set);scoreCache=new Map;deliveryRecords=new u0;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,function(e){for(let[t,r]of Object.entries(e.topics))try{(function(e){if(e.topicWeight<0)throw new iJ("invalid topic weight; must be >= 0",uG);if(0===e.timeInMeshQuantum)throw new iJ("invalid TimeInMeshQuantum; must be non zero",uG);if(e.timeInMeshWeight<0)throw new iJ("invalid TimeInMeshWeight; must be positive (or 0 to disable)",uG);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new iJ("invalid TimeInMeshQuantum; must be positive",uG);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new iJ("invalid TimeInMeshCap; must be positive",uG);if(e.firstMessageDeliveriesWeight<0)throw new iJ("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",uG);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new iJ("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",uG);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new iJ("invalid FirstMessageDeliveriesCap; must be positive",uG);if(e.meshMessageDeliveriesWeight>0)throw new iJ("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",uG);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new iJ("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",uG);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new iJ("invalid MeshMessageDeliveriesCap; must be positive",uG);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new iJ("invalid MeshMessageDeliveriesThreshold; must be positive",uG);if(e.meshMessageDeliveriesWindow<0)throw new iJ("invalid MeshMessageDeliveriesWindow; must be non-negative",uG);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new iJ("invalid MeshMessageDeliveriesActivation; must be at least 1s",uG);if(e.meshFailurePenaltyWeight>0)throw new iJ("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",uG);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new iJ("invalid MeshFailurePenaltyDecay; must be between 0 and 1",uG);if(e.invalidMessageDeliveriesWeight>0)throw new iJ("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",uG);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new iJ("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",uG)})(r)}catch(e){throw new iJ(`invalid score parameters for topic ${t}: ${e.message}`,uG)}if(e.topicScoreCap<0)throw new iJ("invalid topic score cap; must be positive (or 0 for no cap)",uG);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new iJ("missing application specific score function",uG);if(e.IPColocationFactorWeight>0)throw new iJ("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",uG);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new iJ("invalid IPColocationFactorThreshold; must be at least 1",uG);if(e.behaviourPenaltyWeight>0)throw new iJ("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",uG);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new iJ("invalid BehaviourPenaltyDecay; must be between 0 and 1",uG);if(e.decayInterval<1e3)throw new iJ("invalid DecayInterval; must be at least 1s",uG);if(e.decayToZero<=0||e.decayToZero>=1)throw new iJ("invalid DecayToZero; must be between 0 and 1",uG)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??uJ,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(null!=this._backgroundInterval){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(null==this._backgroundInterval){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([r,n])=>{let i=this.params.topics[r];void 0!==i&&(n.firstMessageDeliveries*=i.firstMessageDeliveriesDecay,n.firstMessageDeliveries<t&&(n.firstMessageDeliveries=0),n.meshMessageDeliveries*=i.meshMessageDeliveriesDecay,n.meshMessageDeliveries<t&&(n.meshMessageDeliveries=0),n.meshFailurePenalty*=i.meshFailurePenaltyDecay,n.meshFailurePenalty<t&&(n.meshFailurePenalty=0),n.invalidMessageDeliveries*=i.invalidMessageDeliveriesDecay,n.invalidMessageDeliveries<t&&(n.invalidMessageDeliveries=0),n.inMesh&&(n.meshTime=e-n.graftTime,n.meshTime>i.meshMessageDeliveriesActivation&&(n.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(null==t)return 0;let r=Date.now(),n=this.scoreCache.get(e);if(null!=n&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),s=r+this.scoreCacheValidityMs;return null!=n?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=s):this.scoreCache.set(e,{score:i,cacheUntil:s}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);null!=n&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);null!=r&&r.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);null!=r&&r.knownIPs.delete(t);let n=this.peerIPs.get(t);null!=n&&(n.delete(e),0===n.size&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([e,t])=>{t.firstMessageDeliveries=0;let r=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<r){let e=r-t.meshMessageDeliveries;t.meshFailurePenalty+=e*e}t.inMesh=!1,t.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);null!=e&&(e.inMesh=!0,e.graftTime=Date.now(),e.meshTime=0,e.meshMessageDeliveriesActive=!1)}}prune(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);if(null!=e){let r=this.params.topics[t].meshMessageDeliveriesThreshold;if(e.meshMessageDeliveriesActive&&e.meshMessageDeliveries<r){let t=r-e.meshMessageDeliveries;e.meshFailurePenalty+=t*t}e.meshMessageDeliveriesActive=!1,e.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);let n=this.deliveryRecords.ensureRecord(t),i=Date.now();if(n.status!==e8.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,e8[n.status]);return}n.status=e8.valid,n.validated=i,n.peers.forEach(t=>{t!==e.toString()&&this.markDuplicateMessageDelivery(t,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case eJ.Error:this.markInvalidMessageDelivery(e,r);return;case eJ.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==e8.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,e8[i.status]);return}if(n===eJ.Ignore){i.status=e8.ignored,i.peers.clear();return}i.status=e8.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(e=>{this.markInvalidMessageDelivery(e,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case e8.unknown:n.peers.add(e);break;case e8.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case e8.invalid:this.markInvalidMessageDelivery(e,r);case e8.ignored:}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(null!=r){let e=this.getPtopicStats(r,t);if(null!=e){let r=this.params.topics[t].firstMessageDeliveriesCap;e.firstMessageDeliveries=Math.min(r,e.firstMessageDeliveries+1),e.inMesh&&(r=this.params.topics[t].meshMessageDeliveriesCap,e.meshMessageDeliveries=Math.min(r,e.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(null!=n){let e=void 0!==r?Date.now():0,i=this.getPtopicStats(n,t);if(null!=i&&i.inMesh){let n=this.params.topics[t];if(void 0!==r){let i=e-r,s=i>n.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,i,s),s)return}let s=n.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(s,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let t=this.peerIPs.get(r);null!=t&&(t.delete(e),0===t.size&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return void 0!==r?r:void 0!==this.params.topics[t]?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}}class u2{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=tF(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(t=>{e.abort(t)})}),tV(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(tP.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}}class u3{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(t=>{e.abort(t)})}),this.source=tV(this.rawStream,e=>tL(e,t))}async close(){this.closeController.abort()}}class u4{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),s=this.promises.get(i);null==s&&(s=new Map,this.promises.set(i,s));let o=Date.now();s.has(e)||(s.set(e,o+this.gossipsubIWantFollowupMs),null==this.metrics||(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,o)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((i,s)=>{i<e&&(t.set(s,(t.get(s)??0)+1),n.delete(s),r++)}),0===n.size&&this.promises.delete(i)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);null!=r&&(this.promises.delete(e),null!=this.metrics&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==eJ.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(null!=this.metrics){let t=this.requestMsByMsg.get(e);void 0!==t&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}}let u6=(0,i2.m)("libp2p-pubsub:");async function u5(e,t,r,n){switch(e.type){case eX.Signing:{let i={from:e.author.toBytes(),data:n,seqno:lX(8),topic:t,signature:void 0,key:void 0},s=tA([u6,eY.Message.encode(i)]);i.signature=await e.privateKey.sign(s),i.key=e.key;let o={type:"signed",from:e.author,data:r,sequenceNumber:BigInt(`0x${(0,i5.B)(i.seqno,"base16")}`),topic:t,signature:i.signature,key:i.key};return{raw:i,msg:o}}case eX.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:t,signature:void 0,key:void 0},msg:{type:"unsigned",data:r,topic:t}};default:throw Error("Unreachable")}}async function u8(e,t){switch(e){case uF:if(null!=t.signature)return{valid:!1,error:eZ.SignaturePresent};if(null!=t.seqno)return{valid:!1,error:eZ.SeqnoPresent};if(null!=t.key)return{valid:!1,error:eZ.FromPresent};return{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case uU:{let e,r;if(null==t.seqno||8!==t.seqno.length)return{valid:!1,error:eZ.InvalidSeqno};if(null==t.signature)return{valid:!1,error:eZ.InvalidSignature};if(null==t.from)return{valid:!1,error:eZ.InvalidPeerId};try{e=s7(t.from)}catch(e){return{valid:!1,error:eZ.InvalidPeerId}}if(null!=t.key){if(r=cl(t.key),void 0!==e.publicKey&&!(0,tI.f)(r.bytes,e.publicKey))return{valid:!1,error:eZ.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:eZ.InvalidPeerId};r=cl(e.publicKey)}let n={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},i=tA([u6,eY.Message.encode(n)]);if(!await r.verify(i,t.signature))return{valid:!1,error:eZ.InvalidSignature};return{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${(0,i5.B)(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??cc(r)}}}default:throw Error("Unreachable")}}function u9(e=[],t){return{subscriptions:[],messages:e,control:void 0!==t?{graft:t.graft??[],prune:t.prune??[],ihave:t.ihave??[],iwant:t.iwant??[]}:void 0}}function u7(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function he(e){return(0,i5.B)(e,"base64")}function ht(e){if(e.length<=1)return e;let t=()=>Math.floor(Math.random()*Math.floor(e.length));for(let r=0;r<e.length;r++){let n=t(),i=e[r];e[r]=e[n],e[n]=i}return e}let hr=(e,t)=>{let r=(0,i2.m)(t.toString(16).padStart(16,"0"),"base16"),n=new Uint8Array(e.length+r.length);return n.set(e,0),n.set(r,e.length),n};function hn(e){if("signed"!==e.type)throw Error("expected signed message type");if(null==e.sequenceNumber)throw Error("missing seqno field");return hr(e.from.toBytes(),e.sequenceNumber)}async function hi(e){return i6.sha256.encode(e.data)}async function hs(e,t){switch(e){case uU:{if(null==t)throw Error("Must provide PeerId");if(null==t.privateKey)throw Error("Cannot sign message, no private key present");if(null==t.publicKey)throw Error("Cannot sign message, no public key present");let e=await cu(t.privateKey);return{type:eX.Signing,author:t,key:t.publicKey,privateKey:e}}case uF:return{type:eX.Anonymous};default:throw Error(`Unknown signature policy "${e}"`)}}(em=e9||(e9={}))[em.ip4=4]="ip4",em[em.ip6=41]="ip6";class ho{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return!!this.entries.has(e)||(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return null!=t&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}}(eb=e7||(e7={}))[eb.started=0]="started",eb[eb.stopped=1]="stopped";class ha extends rI{globalSignaturePolicy;multicodecs=[uH,uV];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=tF({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;components;directPeerInitial=null;static multicodec=uH;opts;decodeRpcLimits;metrics;status={code:e7.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...t,scoreParams:function(e={}){return{...uj,...e,topics:null!=e.topics?Object.entries(e.topics).reduce((e,[t,r])=>(e[t]=function(e={}){return{...uW,...e}}(r),e),{}):{}}}(t.scoreParams),scoreThresholds:function(e={}){return{...uY,...e}}(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??u$,this.globalSignaturePolicy=r.globalSignaturePolicy??uU,r.fallbackToFloodsub&&this.multicodecs.push(uK),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(e=>e.id.toString())),this.seenCache=new ho({validityMs:r.seenTTL}),this.publishedMessageIds=new ho({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case uU:this.msgIdFn=hn;break;case uF:this.msgIdFn=hi;break;default:throw Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new ho({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??he,this.mcache=t.messageCache??new uq(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){var n,i,s;if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");let e=Math.max(...Object.values(r.scoreParams.topics).map(e=>e.meshMessageDeliveriesWindow),1e3),o=(n=t.metricsRegister,i=t.metricsTopicStrToLabel,s={gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3},{protocolsEnabled:n.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:n.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:n.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:n.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:n.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:n.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:n.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:n.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:n.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:n.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:n.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:n.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:n.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:n.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:n.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:n.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:n.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:n.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:n.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:n.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:n.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:n.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:n.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:n.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:n.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:n.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:n.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:n.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:n.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:n.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:n.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:n.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:n.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:n.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:n.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:n.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:n.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:n.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:n.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:n.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:n.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:n.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:n.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:n.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:n.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:n.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:n.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:n.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:n.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:n.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:n.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:n.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:n.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:n.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:n.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:n.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:n.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:n.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:n.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:n.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*s.maxMeshMessageDeliveriesWindowSec,.5*s.maxMeshMessageDeliveriesWindowSec,Number(s.maxMeshMessageDeliveriesWindowSec),2*s.maxMeshMessageDeliveriesWindowSec,4*s.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:n.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:n.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:n.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:n.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:n.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:n.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:n.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:n.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:n.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:n.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:n.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*s.behaviourPenaltyThreshold,.5*s.behaviourPenaltyThreshold,Number(s.behaviourPenaltyThreshold),2*s.behaviourPenaltyThreshold,4*s.behaviourPenaltyThreshold]}),ihaveRcvIgnored:n.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:n.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:n.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:n.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:n.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:n.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:n.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:n.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:n.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:n.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:n.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:n.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*s.gossipPromiseExpireSec,Number(s.gossipPromiseExpireSec),2*s.gossipPromiseExpireSec,4*s.gossipPromiseExpireSec]}),iwantPromiseUntracked:n.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:n.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:n.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:n.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:n.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:n.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:n.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:i,toTopic(e){return this.topicStrToLabel.get(e)??e},onJoin(e){this.topicSubscriptionStatus.set({topicStr:e},1),this.meshPeerCounts.set({topicStr:e},0)},onLeave(e){this.topicSubscriptionStatus.set({topicStr:e},0),this.meshPeerCounts.set({topicStr:e},0)},onAddToMesh(e,t,r){let n=this.toTopic(e);switch(t){case e2.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case e2.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case e2.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case e2.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case e2.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case e2.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:n},r);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:n},r)}},onRemoveFromMesh(e,t,r){let n=this.toTopic(e);switch(t){case e3.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case e3.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case e3.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case e3.Excess:this.meshPeerChurnEventsExcess.inc({topic:n},r);break;default:this.meshPeerChurnEventsUnknown.inc({topic:n},r)}},onReportValidation(e,t,r){if(this.asyncValidationMcacheHit.inc({hit:null!=e?"hit":"miss"}),null!=e){let r=this.toTopic(e.message.topic);switch(t){case eW.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case eW.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case eW.Reject:this.rejectedMessagesTotal.inc({topic:r});break;default:this.unknownValidationResultsTotal.inc({topic:r})}}null!=r?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-r)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(e){this.scoringPenalties.inc({penalty:e},1)},onIhaveRcv(e,t,r){let n=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:n},t),this.ihaveRcvNotSeenMsgids.inc({topic:n},r)},onIwantRcv(e,t){for(let[t,r]of e){let e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},r)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){let r=this.toTopic(e);this.msgForwardCount.inc({topic:r},1),this.msgForwardPeers.inc({topic:r},t)},onPublishMsg(e,t,r,n,i){let s=this.toTopic(e);this.msgPublishCount.inc({topic:s},1),this.msgPublishBytes.inc({topic:s},r*n),this.msgPublishPeersByTopic.inc({topic:s},r),this.directPeersPublishedTotal.inc({topic:s},t.direct),this.floodsubPeersPublishedTotal.inc({topic:s},t.floodsub),this.meshPeersPublishedTotal.inc({topic:s},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:s},t.fanout),this.msgPublishTime.observe({topic:s},i/1e3)},onMsgRecvPreValidation(e){let t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){let t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){let r=this.toTopic(e);switch(t){case e0.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case e0.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case e0.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){let r=this.toTopic(e),n=t.reason===eJ.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:n},1),this.msgReceivedInvalidByTopic.inc({topic:r},1)},onDuplicateMsgDelivery(e,t,r){let n=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:n},t/1e3),r&&this.duplicateMsgLateDelivery.inc({topic:n},1)},onPublishDuplicateMsg(e){let t=this.toTopic(e);this.duplicateMsgIgnored.inc({topic:t},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(e,t){this.rpcRecvBytes.inc(t),this.rpcRecvCount.inc(1),null!=e.subscriptions&&this.rpcRecvSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcRecvMessage.inc(e.messages.length),null!=e.control&&(this.rpcRecvControl.inc(1),null!=e.control.ihave&&this.rpcRecvIHave.inc(e.control.ihave.length),null!=e.control.iwant&&this.rpcRecvIWant.inc(e.control.iwant.length),null!=e.control.graft&&this.rpcRecvGraft.inc(e.control.graft.length),null!=e.control.prune&&this.rpcRecvPrune.inc(e.control.prune.length))},onRpcSent(e,t){if(this.rpcSentBytes.inc(t),this.rpcSentCount.inc(1),null!=e.subscriptions&&this.rpcSentSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcSentMessage.inc(e.messages.length),null!=e.control){let t=e.control.ihave?.length??0,r=e.control.iwant?.length??0,n=e.control.graft?.length??0,i=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),r>0&&this.rpcSentIWant.inc(r),n>0&&this.rpcSentGraft.inc(n),i>0&&this.rpcSentPrune.inc(i),(t>0||r>0||n>0||i>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let r=0,n=0,i=0,s=0;for(let o of e)o>=t.graylistThreshold&&r++,o>=t.publishThreshold&&n++,o>=t.gossipThreshold&&i++,o>=0&&s++;this.peersByScoreThreshold.set({threshold:e5.graylist},r),this.peersByScoreThreshold.set({threshold:e5.publish},n),this.peersByScoreThreshold.set({threshold:e5.gossip},i),this.peersByScoreThreshold.set({threshold:e5.mesh},s),this.score.set(e)},registerScoreWeights(e){for(let[t,r]of e.byTopic)this.scoreWeights.set({topic:t,p:"p1"},r.p1w),this.scoreWeights.set({topic:t,p:"p2"},r.p2w),this.scoreWeights.set({topic:t,p:"p3"},r.p3w),this.scoreWeights.set({topic:t,p:"p3b"},r.p3bw),this.scoreWeights.set({topic:t,p:"p4"},r.p4w);this.scoreWeights.set({p:"p5"},e.p5w),this.scoreWeights.set({p:"p6"},e.p6w),this.scoreWeights.set({p:"p7"},e.p7w)},registerScorePerMesh(e,t){let r=new Map;for(let[n,i]of(e.forEach((e,t)=>{let n=this.topicStrToLabel.get(t)??"unknown",i=r.get(n);null==i&&(i=new Set,r.set(n,i)),e.forEach(e=>i?.add(e))}),r)){let e=[];i.forEach(r=>{e.push(t.get(r)??0)}),this.scorePerMesh.set({topic:n},e)}}});for(let e of(o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)}),this.multicodecs))o.protocolsEnabled.set({protocol:e},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new u4(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new u1(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnTransientConnection=t.runOnTransientConnection,this.allowedTopics=null!=r.allowedTopics?new Set(r.allowedTopics):null}getPeers(){return[...this.peers.keys()].map(e=>s9(e))}isStarted(){return this.status.code===e7.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await hs(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=tF({objectMode:!0}),tV(this.outboundInflightQueue,async e=>{for await(let{peerId:t,connection:r}of e)await this.createOutboundStream(t,r)}).catch(e=>{this.log.error("outbound inflight queue error",e)}),await Promise.all(this.opts.directPeers.map(async e=>{await this.components.peerStore.merge(e.id,{multiaddrs:e.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async t=>e.handle(t,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnTransient:this.runOnTransientConnection},r=await Promise.all(this.multicodecs.map(async r=>e.register(r,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:e7.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async e=>this.connect(e)))}).catch(e=>{this.log(e)})},1e3),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==e7.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:e7.stopped};let t=this.components.registrar;await Promise.all(this.multicodecs.map(async e=>t.unhandle(e))),e.forEach(e=>{t.unregister(e)}),this.outboundInflightQueue.end();let r=[];for(let e of this.streamsOutbound.values())r.push(e.close());for(let e of(this.streamsOutbound.clear(),this.streamsInbound.values()))r.push(e.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),null!=this.heartbeatTimer&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),null!=this.fastMsgIdCache&&this.fastMsgIdCache.clear(),null!=this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),this.isStarted()&&"open"===t.status&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!(!this.peers.has(r)||this.streamsOutbound.has(r)))try{let n=new u2(await t.newStream(this.multicodecs,{runOnTransientConnection:this.runOnTransientConnection}),e=>{this.log.error("outbound pipe error",e)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);let i=n.protocol;i===uK&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:i},1),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(e){this.log.error("createOutboundStream error",e)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);void 0!==n&&(this.log("replacing existing inbound steam %s",r),n.close().catch(e=>{this.log.error(e)})),this.log("create inbound stream %s",r);let i=new u3(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(e=>{this.log(e)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.add(n),this.score.addPeer(n);let i=function(e){for(let t of e.tuples())switch(t[0]){case e9.ip4:case e9.ip6:return oC(t[0],t[1])}return null}(r);null!==i?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,"outbound"===t)}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);for(let e of(null!=r&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(e=>{this.log.error(e)}),n?.close().catch(e=>{this.log.error(e)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t),this.topics.values()))e.delete(t);for(let[e,r]of this.mesh)r.delete(t)&&this.metrics?.onRemoveFromMesh(e,e3.Dc,1);for(let e of this.fanout.values())e.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===e7.started}getMeshPeers(e){let t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(null!=t?Array.from(t):[]).map(e=>s9(e))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await tV(t,async t=>{for await(let r of t)try{let t=r.subarray(),n=eY.decode(t,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos}}}});if(this.metrics?.onRpcRecv(n,t.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,n)}catch(e){this.metrics?.onRpcRecvError(),this.log(e)}else this.handleReceivedRpc(e,n).catch(e=>{this.metrics?.onRpcRecvError(),this.log(e)})}catch(e){this.metrics?.onRpcDataError(),this.log(e)}})}catch(t){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(t,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=null!=t.subscriptions?t.subscriptions.length:0,n=null!=t.messages?t.messages.length:0,i=0,s=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(i=t.control.ihave.length),null!=t.control.iwant&&(s=t.control.iwant.length),null!=t.control.graft&&(o=t.control.graft.length),null!=t.control.prune&&(a=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${s} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){let r=[];t.subscriptions.forEach(t=>{let n=t.topic,i=!0===t.subscribe;if(null!=n){if(null!=this.allowedTopics&&!this.allowedTopics.has(n))return;this.handleReceivedSubscription(e,n,i),r.push({topic:n,subscribe:i})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:r}})}for(let r of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(r.topic))continue;let t=this.handleReceivedMessage(e,r).catch(e=>{this.metrics?.onMsgRecvError(r.topic),this.log(e)});this.opts.awaitRpcMessageHandler&&await t}null!=t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);null==n&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case e0.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case e0.invalid:if(null!=r.msgIdStr){let n=r.msgIdStr;this.score.rejectMessage(e.toString(),n,t.topic,r.reason),this.gossipTracer.rejectMessage(n,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case e0.valid:if(this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)){let t=this.components.peerId.equals(e);(!t||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg})))}this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=void 0!==r?this.fastMsgIdCache?.get(r):void 0;if(null!=n)return{code:e0.duplicate,msgIdStr:n};let i=await u8(this.globalSignaturePolicy,t);if(!i.valid)return{code:e0.invalid,reason:eJ.Error,error:i.error};let s=i.message;try{null!=this.dataTransform&&(s.data=this.dataTransform.inboundTransform(t.topic,s.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:e0.invalid,reason:eJ.Error,error:eZ.TransformFailed}}let o=await this.msgIdFn(s),a=this.msgIdToStrFn(o);if(void 0!==r&&null!=this.fastMsgIdCache){let e=this.fastMsgIdCache.put(r,a);e&&this.metrics?.fastMsgIdCacheCollision.inc()}if(this.seenCache.has(a))return{code:e0.duplicate,msgIdStr:a};this.seenCache.put(a);let l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,s)}catch(r){let e=r.code;"ERR_TOPIC_VALIDATOR_IGNORE"===e&&(t=eW.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===e?eW.Reject:eW.Ignore}if(t!==eW.Accept)return{code:e0.invalid,reason:uz(t),msgIdStr:a}}return{code:e0.valid,messageId:{msgId:o,msgIdStr:a},msg:s}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(e=>({topic:e,subscribe:r})),messages:[]})}async handleControlMessage(e,t){if(void 0===t)return;let r=null!=t.ihave?this.handleIHave(e,t.ihave):[],n=null!=t.iwant?this.handleIWant(e,t.iwant):[],i=null!=t.graft?await this.handleGraft(e,t.graft):[];if(null!=t.prune&&await this.handlePrune(e,t.prune),0===r.length&&0===n.length&&0===i.length)return;let s=this.sendRpc(e,u9(n,{iwant:r,prune:i})),o=r[0]?.messageIDs;null!=o&&(s?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(null!=r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(0===t.length)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:e6.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:e6.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:e6.MaxIasked}),[];let s=new Map;if(t.forEach(({topicID:e,messageIDs:t})=>{if(null==e||null==t||!this.mesh.has(e))return;let r=0;t.forEach(e=>{let t=this.msgIdToStrFn(e);!this.seenCache.has(t)&&(s.set(t,e),r++)}),this.metrics?.onIhaveRcv(e,t.length,r)}),0===s.size)return[];let o=s.size;o+i>5e3&&(o=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",o,s.size,e);let a=Array.from(s.values());return ht(a),a=a.slice(0,o),this.iasked.set(e,i+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=new Map,i=new Map,s=0;return(t.forEach(({messageIDs:t})=>{t?.forEach(t=>{let r=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(r,e);if(null==o){s++;return}if(i.set(o.msg.topic,1+(i.get(o.msg.topic)??0)),o.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,t);return}n.set(r,o.msg)})}),this.metrics?.onIwantRcv(i,s),0===n.size)?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),s=this.opts.doPX;return(t.forEach(({topicID:t})=>{if(null==t)return;let o=this.mesh.get(t);if(null==o){s=!1;return}if(o.has(e))return;if(this.direct.has(e)){this.log("GRAFT: ignoring request from direct peer %s",e),r.push(t),s=!1;return}let a=this.backoff.get(t)?.get(e);if("number"==typeof a&&i<a){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,e4.GraftBackoff),s=!1;let n=a+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<n&&this.score.addPenalty(e,1,e4.GraftBackoff),this.addBackoff(e,t),r.push(t);return}if(n<0){this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,t),r.push(t),s=!1,this.addBackoff(e,t);return}if(o.size>=this.opts.Dhi&&!this.outbound.get(e)){r.push(t),this.addBackoff(e,t);return}this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),this.metrics?.onAddToMesh(t,e2.Subscribed,1)}),0===r.length)?[]:Promise.all(r.map(async t=>this.makePrune(e,t,s,!1)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:s}of t){if(null==n)continue;let t=this.mesh.get(n);if(null==t)return;if(this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),t.has(e)&&(t.delete(e),this.metrics?.onRemoveFromMesh(n,e3.Prune,1)),"number"==typeof i&&i>0?this.doAddBackoff(e,n,1e3*i):this.addBackoff(e,n),null!=s&&s.length>0){if(r<this.opts.scoreThresholds.acceptPXThreshold){this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n);continue}await this.pxConnect(s)}}}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,r){let n=this.backoff.get(t);null==n&&(n=new Map,this.backoff.set(t,n));let i=Date.now()+r,s=n.get(e)??0;s<i&&n.set(e,i)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,e4.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!=0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((r,n)=>{r+1*this.opts.heartbeatInterval<e&&t.delete(n)}),0===t.size&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async e=>this.connect(e)))}async pxConnect(e){e.length>this.opts.prunePeers&&(ht(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async e=>{if(null==e.peerID)return;let r=s7(e.peerID),n=r.toString();if(!this.peers.has(n)){if(null==e.signedPeerRecord){t.push(n);return}try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,r)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(n)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),0!==t.length&&await Promise.all(t.map(async e=>this.connect(e)))}async connect(e){this.log("Initiating connection with %s",e);let t=s9(e),r=await this.components.connectionManager.openConnection(t);for(let e of this.multicodecs)for(let n of this.components.registrar.getTopologies(e))n.onConnect?.(t,r)}subscribe(e){if(this.status.code!==e7.started)throw Error("Pubsub has not started");if(!this.subscriptions.has(e))for(let t of(this.subscriptions.add(e),this.peers.keys()))this.sendSubscriptions(t,[e],!0);this.join(e)}unsubscribe(e){if(this.status.code!==e7.started)throw Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==e7.started)throw Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(null!=n&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(e=>{!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e))&&t.add(e)}),this.metrics?.onAddToMesh(e,e2.Fanout,t.size)),t.size<this.opts.D){let n=t.size,i=this.getRandomGossipPeers(e,this.opts.D,e=>!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e)));i.forEach(e=>{t.add(e)}),this.metrics?.onAddToMesh(e,e2.Random,t.size-n)}this.mesh.set(e,t),t.forEach(t=>{this.log("JOIN: Add mesh link to %s in %s",t,e),this.sendGraft(t,e)})}leave(e){if(this.status.code!==e7.started)throw Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);null!=t&&(Promise.all(Array.from(t).map(async t=>{this.log("LEAVE: Remove mesh link to %s in %s",t,e),await this.sendPrune(t,e)})).catch(e=>{this.log("Error sending prunes to mesh peers",e)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);null!=i&&(this.direct.forEach(e=>{i.has(e)&&t!==e&&!r?.has(e)&&n.add(e)}),this.floodsubPeers.forEach(e=>{i.has(e)&&t!==e&&!r?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&n.add(e)}));let s=this.mesh.get(e);return null!=s&&s.size>0&&s.forEach(e=>{t===e||r?.has(e)||n.add(e)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(null!=n){if(this.opts.floodPublish)n.forEach(e=>{this.direct.has(e)?(t.add(e),r.direct++):this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)});else{this.direct.forEach(e=>{n.has(e)&&(t.add(e),r.direct++)}),this.floodsubPeers.forEach(e=>{n.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),r.floodsub++)});let i=this.mesh.get(e);if(null!=i&&i.size>0)i.forEach(e=>{t.add(e),r.mesh++});else{let n=this.fanout.get(e);if(null!=n&&n.size>0)n.forEach(e=>{t.add(e),r.fanout++});else{let n=this.getRandomGossipPeers(e,this.opts.D,e=>this.score.score(e)>=this.opts.scoreThresholds.publishThreshold);n.size>0&&(this.fanout.set(e,n),n.forEach(e=>{t.add(e),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){null!=r&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(e=>{this.sendRpc(e,u9([t]))}),this.metrics?.onForwardMsg(t.topic,i.size)}async publish(e,t,r){let n=Date.now(),i=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");let{raw:s,msg:o}=await u5(this.publishConfig,e,t,i),a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),c=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(c)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:u,tosendCount:h}=this.selectPeersToPublish(e),d=this.opts.emitSelf&&this.subscriptions.has(e),p=r?.allowPublishToZeroPeers??this.opts.allowPublishToZeroPeers;if(0===u.size&&!p&&!d)throw Error("PublishError.InsufficientPeers");this.seenCache.put(l),this.mcache.put({msgId:a,msgIdStr:l},s,!0),this.publishedMessageIds.put(l);let f=r?.batchPublish??this.opts.batchPublish,g=u9([s]);if(f)this.sendRpcInBatch(u,g);else for(let e of u){let t=this.sendRpc(e,g);t||u.delete(e)}let y=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=s.data?s.data.length:0,y),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:o}})),super.dispatchEvent(new CustomEvent("message",{detail:o}))),{recipients:Array.from(u.values()).map(e=>s9(e))}}sendRpcInBatch(e,t){let r=eY.encode(t),n=tP.single(r);for(let i of e){let s=this.streamsOutbound.get(i);if(null==s){this.log(`Cannot send RPC to ${i} as there is no open stream to it available`),e.delete(i);continue}try{s.pushPrefixed(n)}catch(t){e.delete(i),this.log.error(`Cannot send rpc to ${i}`,t)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===eW.Accept){if(null!=(n=this.mcache.validate(e))){let{message:r,originatingPeers:i}=n;this.score.deliverMessage(t,e,r.topic),this.forwardMessage(e,n.message,t,i)}}else if(null!=(n=this.mcache.remove(e))){let i=uz(r),{message:s,originatingPeers:o}=n;for(let r of(this.score.rejectMessage(t,e,s.topic,i),o))this.score.rejectMessage(r,e,s.topic,i)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=u9([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){let r=[await this.makePrune(e,t,this.opts.doPX,!0)],n=u9([],{prune:r});this.sendRpc(e,n)}sendRpc(e,t){let r=this.streamsOutbound.get(e);if(null==r)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);null!=n&&(this.piggybackControl(e,t,n),this.control.delete(e));let i=this.gossip.get(e);null!=i&&(this.piggybackGossip(e,t,i),this.gossip.delete(e));let s=eY.encode(t);try{r.push(s)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=n&&this.control.set(e,n),null!=i&&this.gossip.set(e,i),!1}return this.metrics?.onRpcSent(t,s.length),!0}piggybackControl(e,t,r){let n=u7(t);for(let t of r.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&n.control.graft.push(t);for(let t of r.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||n.control.prune.push(t)}piggybackGossip(e,t,r){let n=u7(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX;for(let[i,s]of e){let e=s.map(e=>({topicID:e})),o=[],a=t.get(i);null!=a&&(o=await Promise.all(a.map(async e=>this.makePrune(i,e,n&&!r.get(i),!1))),t.delete(i)),this.sendRpc(i,u9([],{graft:e,prune:o}))}for(let[e,i]of t){let t=await Promise.all(i.map(async t=>this.makePrune(e,t,n&&!r.get(e),!1)));this.sendRpc(e,u9([],{prune:t}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(0===r.length||(ht(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),0===t.size))return;let n=this.opts.Dlazy,i=.25*t.size,s=t;i>n&&(n=i),n>s.size?n=s.size:s=ht(Array.from(s)).slice(0,n),s.forEach(t=>{let n=r;r.length>5e3&&(n=ht(n.slice()).slice(0,5e3)),this.pushGossip(t,{topicID:e,messageIDs:n})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,u9([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=u9([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===uV)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,s=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:s};let o=this.getRandomGossipPeers(t,this.opts.prunePeers,t=>t!==e&&this.score.score(t)>=0),a=await Promise.all(Array.from(o).map(async e=>{let t;let r=s9(e);try{t=await this.components.peerStore.get(r)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:r.toBytes(),signedPeerRecord:t?.peerRecordEnvelope}}));return{topicID:t,peers:a,backoff:s}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(e=>{this.log("Error running heartbeat",e)}).finally(()=>{if(null!=e&&e(),this.status.code===e7.started){clearTimeout(this.status.heartbeatTimeout);let e=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;e<.25*this.opts.heartbeatInterval&&(e+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,e)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:s}=this.opts;this.heartbeatTicks++;let o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},l=new Map,c=new Map,u=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks==0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let h=new Map;this.mesh.forEach((s,o)=>{let d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){let e=ht(Array.from(d)),t=this.backoff.get(o);for(let r of e){let e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!s.has(r)&&!this.direct.has(r)){let e=a(r);(null==t||!t.has(r))&&e>=0&&p.add(r),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(r)}}}let g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),s.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);let r=c.get(e);null==r?c.set(e,[o]):r.push(o)},y=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),s.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);let r=l.get(e);null==r?l.set(e,[o]):r.push(o)};if(s.forEach(e=>{let t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,e3.BadScore),u.set(e,!0))}),s.size<t){let t=e-s.size,r=uQ(p,t,()=>!0);r.forEach(e=>{y(e,e2.NotEnough)})}if(s.size>r){let t=Array.from(s);t.sort((e,t)=>a(t)-a(e));let r=0;if((t=t.slice(0,n).concat(ht(t.slice(n)))).slice(0,e).forEach(e=>{this.outbound.get(e)&&r++}),r<i){let n=e=>{let r=t[e];for(let r=e;r>0;r--)t[r]=t[r-1];t[0]=r};if(r>0){let i=r;for(let r=1;r<e&&i>0;r++)this.outbound.get(t[r])&&(n(r),i--)}let i=e-r;for(let r=e;r<t.length&&i>0;r++)this.outbound.get(t[r])&&(n(r),i--)}t.slice(e).forEach(e=>{g(e,e3.Excess)})}if(s.size>=t){let e=0;if(s.forEach(t=>{this.outbound.get(t)&&e++}),e<i){let t=i-e,r=uQ(p,t,e=>!0===this.outbound.get(e));r.forEach(e=>{y(e,e2.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&s.size>1){let e=Array.from(s).sort((e,t)=>a(e)-a(t)),t=Math.floor(s.size/2),r=a(e[t]);if(r<this.opts.scoreThresholds.opportunisticGraftThreshold){let e=this.opts.opportunisticGraftPeers,t=uQ(p,e,e=>a(e)>r);for(let e of t)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",e,o),y(e,e2.Opportunistic)}}});let d=Date.now();this.fanoutLastpub.forEach((e,t)=>{e+s<d&&(this.fanout.delete(t),this.fanoutLastpub.delete(t))}),this.fanout.forEach((t,r)=>{let n=this.topics.get(r);t.forEach(e=>{(!n?.has(e)||a(e)<this.opts.scoreThresholds.publishThreshold)&&t.delete(e)});let i=this.topics.get(r),s=[],o=new Set;if(h.set(r,o),null!=i){let e=ht(Array.from(i));for(let r of e){let e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!t.has(r)&&!this.direct.has(r)){let e=a(r);e>=this.opts.scoreThresholds.publishThreshold&&s.push(r),e>=this.opts.scoreThresholds.gossipThreshold&&o.add(r)}}}if(t.size<e){let r=e-t.size;s.slice(0,r).forEach(e=>{t.add(e),o?.delete(e)})}}),this.emitGossip(h),await this.sendGraftPrune(l,c,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(null==n)return new Set;let i=[];return n.forEach(e=>{let t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&r(e)&&i.push(e)}),i=ht(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();for(let n of(e.connectedPeersBackoffSec.reset(),this.backoff.values()))for(let[i,s]of(t+=n.size,n.entries()))this.peers.has(i)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-r)/1e3);for(let[r,n]of(e.cacheSize.set({cache:"backoff"},t),this.topics))e.topicPeersCount.set({topicStr:r},n.size);for(let[t,r]of this.mesh)e.meshPeerCounts.set({topicStr:t},r.size);let n=[],i=new Map;for(let t of(e.behaviourPenalty.reset(),this.peers.keys())){let r=this.score.score(t);n.push(r),i.set(t,r),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let s=function(e,t,r,n,i){let s={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of e){let e=t.get(o);if(null!=e){let t=function(e,t,r,n,i){let s=0,o=new Map;if(Object.entries(t.topics).forEach(([e,t])=>{let n=i.get(e)??"unknown",a=r.topics[e];if(void 0===a)return;let l=o.get(n);null==l&&(l={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(n,l));let c=0,u=0,h=0,d=0,p=0;if(t.inMesh){let e=Math.max(t.meshTime/a.timeInMeshQuantum,a.timeInMeshCap);c+=e*a.timeInMeshWeight}let f=t.firstMessageDeliveries;if(f>a.firstMessageDeliveriesCap&&(f=a.firstMessageDeliveriesCap),u+=f*a.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<a.meshMessageDeliveriesThreshold){let e=a.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;h+=e*e*a.meshMessageDeliveriesWeight}let g=t.meshFailurePenalty;d+=g*a.meshFailurePenaltyWeight;let y=t.invalidMessageDeliveries*t.invalidMessageDeliveries;p+=y*a.invalidMessageDeliveriesWeight,s+=(c+u+h+d+p)*a.topicWeight,l.p1w+=c,l.p2w+=u,l.p3w+=h,l.p3bw+=d,l.p4w+=p}),r.topicScoreCap>0&&s>r.topicScoreCap){s=r.topicScoreCap;let e=r.topicScoreCap/s;for(let t of o.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let a=0,l=0,c=0,u=r.appSpecificScore(e);a+=u*r.appSpecificWeight,t.knownIPs.forEach(e=>{if(r.IPColocationFactorWhitelist.has(e))return;let t=n.get(e),i=null!=t?t.size:0;if(i>r.IPColocationFactorThreshold){let e=i-r.IPColocationFactorThreshold;l+=e*e*r.IPColocationFactorWeight}});let h=t.behaviourPenalty*t.behaviourPenalty;return c+=h*r.behaviourPenaltyWeight,s+=a+l+c,{byTopic:o,p5w:a,p6w:l,p7w:c,score:s}}(o,e,r,n,i);for(let[e,r]of t.byTopic){let t=s.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},s.byTopic.set(e,t)),t.p1w.push(r.p1w),t.p2w.push(r.p2w),t.p3w.push(r.p3w),t.p3bw.push(r.p3bw),t.p4w.push(r.p4w)}s.p5w.push(t.p5w),s.p6w.push(t.p6w),s.p7w.push(t.p7w),s.score.push(t.score)}else s.p5w.push(0),s.p6w.push(0),s.p7w.push(0),s.score.push(0)}return s}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(s)}}let hl=["/vac/waku/relay/2.0.0"],hc=new tw.Yd("relay");function hu(e,t){let r=performance.now();hc.info(`validating message from ${e} received on ${t.topic}`);let n=eW.Accept;try{let e=t0.u.H.decode(t.data);e.contentTopic&&e.contentTopic.length&&e.payload&&e.payload.length||(n=eW.Reject)}catch(e){n=eW.Reject}let i=performance.now(),s=i-r;return s>100?hc.warn(`message validation took ${s}ms for peer ${e} on topic ${t.topic}. This should be less than 100ms.`):hc.info(`message validation took ${s}ms for peer ${e} on topic ${t.topic}`),n}class hh{pubsubTopic;proto;payload=new Uint8Array;rateLimitProof;timestamp;meta;ephemeral;constructor(e,t){this.pubsubTopic=e,this.proto=t}get contentTopic(){return this.proto.contentTopic}}class hd{pubsubTopic=tb.nf;contentTopic="";fromWireToProtoObj(e){let t=t0.aF.decode(e);return Promise.resolve({contentTopic:t.contentTopic,payload:new Uint8Array,rateLimitProof:void 0,timestamp:void 0,meta:void 0,version:void 0,ephemeral:void 0})}async fromProtoObj(e,t){return new hh(e,t)}}let hp=new tw.Yd("relay");class hf{pubsubTopics;defaultDecoder;static multicodec="/vac/waku/relay/2.0.0";gossipSub;observers;constructor(e,t){if(!this.isRelayPubsub(e.services.pubsub))throw Error(`Failed to initialize Relay. libp2p.pubsub does not support ${hf.multicodec}`);this.gossipSub=e.services.pubsub,this.pubsubTopics=new Set(t),this.gossipSub.isStarted()&&this.subscribeToAllTopics(),this.observers=new Map,this.defaultDecoder=new hd}async start(){if(this.gossipSub.isStarted())throw Error("GossipSub already started.");await this.gossipSub.start(),this.subscribeToAllTopics()}async send(e,t){let r=[],{pubsubTopic:n}=e;if(!this.pubsubTopics.has(n))return hp.error("Failed to send waku relay: topic not configured"),{successes:r,failures:[{error:tb.K1.TOPIC_NOT_CONFIGURED}]};let i=await e.toWire(t);if(!i)return hp.error("Failed to encode message, aborting publish"),{successes:r,failures:[{error:tb.K1.ENCODE_FAILED}]};if(!(0,tw.qc)(i))return hp.error("Failed to send waku relay: message is bigger that 1MB"),{successes:r,failures:[{error:tb.K1.SIZE_TOO_BIG}]};let{recipients:s}=await this.gossipSub.publish(n,i);return{successes:s,failures:[]}}subscribe(e,t){let r=[];for(let n of Array.isArray(e)?e:[e]){let{pubsubTopic:e}=n,i=this.observers.get(e)??new Map,s={pubsubTopic:e,decoder:n,callback:t};(0,tw.IC)(i,n.contentTopic,s),this.observers.set(e,i),r.push([e,s])}return()=>{this.removeObservers(r)}}removeObservers(e){for(let[t,r]of e){let e=this.observers.get(t);if(!e)continue;let n=r.decoder.contentTopic,i=e.get(n);i&&(i.delete(r),e.set(n,i),this.observers.set(t,e))}}toSubscriptionIterator(e){return(0,tw.B2)(this,e)}getActiveSubscriptions(){let e=new Map;for(let t of this.pubsubTopics)e.set(t,Array.from(this.observers.keys()));return e}getMeshPeers(e=tb.nf){return this.gossipSub.getMeshPeers(e)}subscribeToAllTopics(){for(let e of this.pubsubTopics)this.gossipSubSubscribe(e)}async processIncomingMessage(e,t){let r=await this.defaultDecoder.fromWireToProtoObj(t);if(!r||!r.contentTopic){hp.warn("Message does not have a content topic, skipping");return}let n=this.observers.get(e);if(!n)return;let i=n.get(r.contentTopic);i&&await Promise.all(Array.from(i).map(({decoder:n,callback:i})=>(async()=>{try{let s=await n.fromWireToProtoObj(t);if(!s){hp.error("Internal error: message previously decoded failed on 2nd pass.");return}let o=await n.fromProtoObj(e,s);o?await i(o):hp.error("Failed to decode messages on",r.contentTopic)}catch(e){hp.error("Error while decoding message:",e)}})()))}gossipSubSubscribe(e){this.gossipSub.addEventListener("gossipsub:message",t=>{t.detail.msg.topic===e&&this.processIncomingMessage(t.detail.msg.topic,t.detail.msg.data).catch(e=>hp.error("Failed to process incoming message",e))}),this.gossipSub.topicValidators.set(e,hu),this.gossipSub.subscribe(e)}isRelayPubsub(e){return e?.multicodecs?.includes(hf.multicodec)??!1}}let hg=Symbol.for("@libp2p/content-routing"),hy=Symbol.for("@libp2p/peer-routing");var hm=r(4461);function hb(){return{forComponent:e=>{let t;return t=function(e){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`),hm.enabled(`${e}:trace`)&&null!=hm.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(t=hm(`${e}:trace`)),Object.assign(hm(e),{error:hm(`${e}:error`),trace:t})}}}function hw(e,t){let r={[Symbol.iterator]:()=>r,next:()=>{let r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}hm.formatters.b=e=>null==e?"undefined":i3.base58btc.baseEncode(e),hm.formatters.t=e=>null==e?"undefined":ow.base32.baseEncode(e),hm.formatters.m=e=>null==e?"undefined":st.base64.baseEncode(e),hm.formatters.p=e=>null==e?"undefined":e.toString(),hm.formatters.c=e=>null==e?"undefined":e.toString(),hm.formatters.k=e=>null==e?"undefined":e.toString(),hm.formatters.a=e=>null==e?"undefined":e.toString();class hv{set;constructor(e){if(this.set=new Set,null!=e)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 hw(this.set.entries(),e=>{let t=s9(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let r=s9(t);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return hw(this.set.values(),e=>s9(e))}intersection(e){let t=new hv;for(let r of e)this.has(r)&&t.add(r);return t}difference(e){let t=new hv;for(let r of this)e.has(r)||t.add(r);return t}union(e){let t=new hv;for(let r of e)t.add(r);for(let e of this)t.add(e);return t}}let hE=async()=>{let e=await ca("Ed25519"),t=await hA(e);if("Ed25519"===t.type)return t;throw Error(`Generated unexpected PeerId type "${t.type}"`)};async function hS(e){return oe(cc(e))}async function hA(e){var t;return oe(cc(e.public),(co(t=(t??"rsa").toLowerCase()),e.bytes))}async function hI(e){return hT((0,i2.m)(e.id,"base58btc"),null!=e.privKey?(0,i2.m)(e.privKey,"base64pad"):void 0,null!=e.pubKey?(0,i2.m)(e.pubKey,"base64pad"):void 0)}async function hT(e,t,r){if(null!=t){let e=await cu(t);return hA(e)}if(null!=r){let e=cl(r);return hS(e)}return s7(e)}class h_{map;constructor(e){if(this.map=new Map,null!=e)for(let[t,r]of e.entries())this.map.set(t.toString(),r)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return hw(this.map.entries(),e=>[s9(e[0]),e[1]])}forEach(e){this.map.forEach((t,r)=>{e(t,s9(r),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 hw(this.map.keys(),e=>s9(e))}values(){return this.map.values()}get size(){return this.map.size}}var hR=r(8729);class hC{#o=[];enqueue(e,t){t={priority:0,...t};let r={priority:t.priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority){this.#o.push(r);return}let n=function(e,t,r){let n=0,i=e.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;0>=r(e[o],t)?(n=++o,i-=s+1):i=s}return n}(this.#o,r,(e,t)=>t.priority-e.priority);this.#o.splice(n,0,r)}dequeue(){let e=this.#o.shift();return e?.run}filter(e){return this.#o.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#o.length}}class hk extends hR{#a;#l;#c=0;#u;#h;#d=0;#p;#f;#o;#g;#y=0;#m;#b;#w;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:hC,...e}).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#a=e.carryoverConcurrencyCount,this.#l=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#u=e.intervalCap,this.#h=e.interval,this.#o=new e.queueClass,this.#g=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#w=!0===e.throwOnTimeout,this.#b=!1===e.autoStart}get #v(){return this.#l||this.#c<this.#u}get #E(){return this.#y<this.#m}#S(){this.#y--,this.#A(),this.emit("next")}#I(){this.#T(),this.#_(),this.#f=void 0}get #R(){let e=Date.now();if(void 0===this.#p){let t=this.#d-e;if(!(t<0))return void 0===this.#f&&(this.#f=setTimeout(()=>{this.#I()},t)),!0;this.#c=this.#a?this.#y:0}return!1}#A(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#y&&this.emit("idle"),!1;if(!this.#b){let e=!this.#R;if(this.#v&&this.#E){let t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#_(),!0)}}return!1}#_(){this.#l||void 0!==this.#p||(this.#p=setInterval(()=>{this.#T()},this.#h),this.#d=Date.now()+this.#h)}#T(){0===this.#c&&0===this.#y&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#c=this.#a?this.#y:0,this.#C()}#C(){for(;this.#A(););}get concurrency(){return this.#m}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#m=e,this.#C()}async #k(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#w,...t},new Promise((r,n)=>{this.#o.enqueue(async()=>{this.#y++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=rg(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));let i=await n;r(i),this.emit("completed",i)}catch(e){if(e instanceof rh&&!t.throwOnTimeout){r();return}n(e),this.emit("error",e)}finally{this.#S()}},t),this.emit("add"),this.#A()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#b&&(this.#b=!1,this.#C()),this}pause(){this.#b=!0}clear(){this.#o=new this.#g}async onEmpty(){0!==this.#o.size&&await this.#B("empty")}async onSizeLessThan(e){this.#o.size<e||await this.#B("next",()=>this.#o.size<e)}async onIdle(){(0!==this.#y||0!==this.#o.size)&&await this.#B("idle")}async #B(e,t){return new Promise(r=>{let n=()=>{(!t||t())&&(this.off(e,n),r())};this.on(e,n)})}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#y}get isPaused(){return this.#b}}let hB={},hP=e=>{e.addEventListener("message",t=>{hP.dispatchEvent("message",e,t)}),null!=e.port&&e.port.addEventListener("message",t=>{hP.dispatchEvent("message",e,t)})};hP.addEventListener=(e,t)=>{null==hB[e]&&(hB[e]=[]),hB[e].push(t)},hP.removeEventListener=(e,t)=>{null!=hB[e]&&(hB[e]=hB[e].filter(e=>e===t))},hP.dispatchEvent=function(e,t,r){null!=hB[e]&&hB[e].forEach(e=>e(t,r))};let hD="lock:worker:request-read",hN="lock:worker:release-read",hL="lock:master:grant-read",hx="lock:worker:request-write",hO="lock:worker:release-write",hM="lock:master:grant-write",hU=(e=21)=>Math.random().toString().substring(2),hF=(e,t,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(e=>{let t=r=>{if(null==r||null==r.data)return;let i={type:r.data.type,name:r.data.name,identifier:r.data.identifier};i.type===n&&i.identifier===a.identifier&&(s.removeEventListener("message",t),e())};s.addEventListener("message",t)})}}}))},hK=(e,t,r,n)=>async()=>{let i=hU();return globalThis.postMessage({type:t,identifier:i,name:e}),new Promise(t=>{let s=o=>{if(null==o||null==o.data)return;let a={type:o.data.type,identifier:o.data.identifier};a.type===r&&a.identifier===i&&(globalThis.removeEventListener("message",s),t(()=>{globalThis.postMessage({type:n,identifier:i,name:e})}))};globalThis.addEventListener("message",s)})},hV={singleProcess:!1};var hH=e=>{e=Object.assign({},hV,e);let t=!!globalThis.document||e.singleProcess;if(t){let e=new EventTarget;return hP.addEventListener("message",hF(e,"requestReadLock",hD,hN,hL)),hP.addEventListener("message",hF(e,"requestWriteLock",hx,hO,hM)),e}return{isWorker:!0,readLock:e=>hK(e,hD,hL,hN),writeLock:e=>hK(e,hx,hM,hO)}};let h$={};async function hq(e,t){let r;let n=new Promise(e=>{r=e});return e.add(async()=>rg((async()=>{await new Promise(e=>{r(()=>{e()})})})(),{milliseconds:t.timeout})),n}let hz=(e,t)=>{let r;if(!0===i.isWorker)return{readLock:i.readLock(e,t),writeLock:i.writeLock(e,t)};let n=new hk({concurrency:1});return{async readLock(){if(null!=r)return hq(r,t);r=new hk({concurrency:t.concurrency,autoStart:!1});let e=r,i=hq(r,t);return n.add(async()=>{e.start(),await e.onIdle().then(()=>{r===e&&(r=null)})}),i},writeLock:async()=>(r=null,hq(n,t))}},hG={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1},hj={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};function hW(e,t){let r=te.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new s6(e);if("Ed25519"===e.type)return new s5(e);if("secp256k1"===e.type)return new s8(e);throw new iJ("Not a PeerId","ERR_INVALID_PARAMETERS")}({...e,publicKey:e.publicKey}));let n=new Map,i=BigInt(Date.now());for(let[e,t]of r.tags.entries())null!=t.expiry&&t.expiry<i||n.set(e,t);return{...r,id:e,addresses:r.addresses.map(({multiaddr:e,isCertified:t})=>({multiaddr:oG(e),isCertified:t??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}(ev=(ew=te||(te={})).Peer$metadataEntry||(ew.Peer$metadataEntry={})).codec=()=>(null==_&&(_=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r})),_),ev.encode=e=>(0,ss.LE)(e,ev.codec()),ev.decode=e=>(0,ss.C6)(e,ev.codec()),(eE=ew.Peer$tagsEntry||(ew.Peer$tagsEntry={})).codec=()=>(null==R&&(R=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),tr.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=tr.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),R),eE.encode=e=>(0,ss.LE)(e,eE.codec()),eE.decode=e=>(0,ss.C6)(e,eE.codec()),ew.codec=()=>(null==T&&(T=(0,ss.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.addresses)for(let r of e.addresses)t.uint32(10),tt.codec().encode(r,t);if(null!=e.protocols)for(let r of e.protocols)t.uint32(18),t.string(r);if(null!=e.publicKey&&(t.uint32(34),t.bytes(e.publicKey)),null!=e.peerRecordEnvelope&&(t.uint32(42),t.bytes(e.peerRecordEnvelope)),null!=e.metadata&&0!==e.metadata.size)for(let[r,n]of e.metadata.entries())t.uint32(50),ew.Peer$metadataEntry.codec().encode({key:r,value:n},t);if(null!=e.tags&&0!==e.tags.size)for(let[r,n]of e.tags.entries())t.uint32(58),ew.Peer$tagsEntry.codec().encode({key:r,value:n},t);!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={addresses:[],protocols:[],metadata:new Map,tags:new Map},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.addresses.push(tt.codec().decode(e,e.uint32()));break;case 2:r.protocols.push(e.string());break;case 4:r.publicKey=e.bytes();break;case 5:r.peerRecordEnvelope=e.bytes();break;case 6:{let t=ew.Peer$metadataEntry.codec().decode(e,e.uint32());r.metadata.set(t.key,t.value);break}case 7:{let t=ew.Peer$tagsEntry.codec().decode(e,e.uint32());r.tags.set(t.key,t.value);break}default:e.skipType(7&t)}}return r})),T),ew.encode=e=>(0,ss.LE)(e,ew.codec()),ew.decode=e=>(0,ss.C6)(e,ew.codec()),(eS=tt||(tt={})).codec=()=>(null==C&&(C=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r})),C),eS.encode=e=>(0,ss.LE)(e,eS.codec()),eS.decode=e=>(0,ss.C6)(e,eS.codec()),(eA=tr||(tr={})).codec=()=>(null==k&&(k=(0,ss.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){let t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r})),k),eA.encode=e=>(0,ss.LE)(e,eA.codec()),eA.decode=e=>(0,ss.C6)(e,eA.codec());let hY=new TextEncoder().encode("/"),hQ=hY[0];class hX{_buf;constructor(e,t){if("string"==typeof e)this._buf=(0,i2.m)(e);else if(e instanceof Uint8Array)this._buf=e;else throw Error("Invalid key, should be String of Uint8Array");if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==hQ)throw Error("Invalid key")}toString(e="utf8"){return(0,i5.B)(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new hX(e.join("/"))}static random(){return new hX(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new hX(e):"function"==typeof e.uint8Array?new hX(e.uint8Array()):null}clean(){if((null==this._buf||0===this._buf.byteLength)&&(this._buf=hY),this._buf[0]!==hQ){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hQ,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hQ;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;let n=t[e],i=r[e];if(n<i)return!0;if(n>i)return!1}return t.length<r.length}reverse(){return hX.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split("/").slice(1)}type(){return function(e){let t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){let t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new hX(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith("/")||(e+="/"),new hX(e+=this.type())}parent(){let e=this.list();return new hX(1===e.length?"/":e.slice(0,-1).join("/"))}child(e){return"/"===this.toString()?e:"/"===e.toString()?this:new hX(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return hX.withNamespaces([...this.namespaces(),...[].concat(...e.map(e=>e.namespaces()))])}}let hJ="/peers/";function hZ(e){if(!sJ(e)||null==e.type)throw new iJ("Invalid PeerId",hj.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new hX(`${hJ}${t}`)}async function h0(e,t,r){let n=new Map;for(let s of r){var i;if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=oG(s.multiaddr)),i=s.multiaddr,!i?.[oH])throw new iJ("Multiaddr was invalid",hj.ERR_INVALID_PARAMETERS);if(!await t(e,s.multiaddr))continue;let r=s.isCertified??!1,o=s.multiaddr.toString(),a=n.get(o);null!=a?s.isCertified=a.isCertified||r:n.set(o,{multiaddr:s.multiaddr,isCertified:r})}return[...n.values()].sort((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString())).map(({isCertified:e,multiaddr:t})=>({isCertified:e,multiaddr:t.bytes}))}async function h1(e,t,r,n){if(null==t)throw new iJ("Invalid PeerData",hj.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!(0,tI.f)(t.publicKey,e.publicKey))throw new iJ("publicKey bytes do not match peer id publicKey bytes",hj.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(null!=i&&!e.equals(i.id))throw new iJ("peer id did not match existing peer id",hj.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,l=i?.tags??new Map,c=i?.peerRecordEnvelope;if("patch"===r){if((null!=t.multiaddrs||null!=t.addresses)&&(s=[],null!=t.multiaddrs&&s.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&s.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata){let e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=h2(e,{validate:h3})}if(null!=t.tags){let e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);l=h2(e,{validate:h4,map:h6})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}if("merge"===r){if(null!=t.multiaddrs&&s.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&s.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){let e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[t,r]of e)null==r?a.delete(t):a.set(t,r);a=h2([...a.entries()],{validate:h3})}if(null!=t.tags){let e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(let[t,n]of e)null==n?r.delete(t):r.set(t,n);l=h2([...r.entries()],{validate:h4,map:h6})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}let u={addresses:await h0(e,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((e,t)=>e.localeCompare(t)),metadata:a,tags:l,publicKey:i?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:c};return"RSA"!==e.type&&delete u.publicKey,u}function h2(e,t){let r=new Map;for(let[r,n]of e)null!=n&&t.validate(r,n);for(let[n,i]of e.sort(([e],[t])=>e.localeCompare(t)))null!=i&&r.set(n,t.map?.(n,i)??i);return r}function h3(e,t){if("string"!=typeof e)throw new iJ("Metadata key must be a string",hj.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new iJ("Metadata value must be a Uint8Array",hj.ERR_INVALID_PARAMETERS)}function h4(e,t){if("string"!=typeof e)throw new iJ("Tag name must be a string",hj.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new iJ("Tag value must be an integer",hj.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new iJ("Tag value must be between 0-100",hj.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new iJ("Tag ttl must be an integer",hj.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new iJ("Tag ttl must be between greater than 0",hj.ERR_INVALID_PARAMETERS)}}function h6(e,t){let r;return null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function h5(e,t,r){let n=e.toString().split("/")[2],i=ow.base32.decode(n),s=s7(i),o=r.get(s);if(null!=o)return o;let a=hW(s,t);return r.set(s,a),a}class h8{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){let t=Object.assign({},hG,e);return null==i&&!0!==(i=hH(t)).isWorker&&(i.addEventListener("requestReadLock",e=>{null!=h$[e.data.name]&&h$[e.data.name].readLock().then(async t=>e.data.handler().finally(()=>{t()}))}),i.addEventListener("requestWriteLock",async e=>{null!=h$[e.data.name]&&h$[e.data.name].writeLock().then(async t=>e.data.handler().finally(()=>{t()}))})),null==h$[t.name]&&(h$[t.name]=hz(t.name,t)),h$[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(hZ(e))}async delete(e){if(this.peerId.equals(e))throw new iJ("Cannot delete self peer",hj.ERR_INVALID_PARAMETERS);await this.datastore.delete(hZ(e))}async load(e){let t=await this.datastore.get(hZ(e));return hW(e,t)}async save(e,t){let{existingBuf:r,existingPeer:n}=await this.#P(e),i=await h1(e,t,"patch",{addressFilter:this.addressFilter});return this.#D(e,i,r,n)}async patch(e,t){let{existingBuf:r,existingPeer:n}=await this.#P(e),i=await h1(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,i,r,n)}async merge(e,t){let{existingBuf:r,existingPeer:n}=await this.#P(e),i=await h1(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,i,r,n)}async *all(e){var t;let r=new h_;for await(let{key:n,value:i}of this.datastore.query(null==(t=e??{})?{}:{prefix:hJ,filters:(t.filters??[]).map(e=>({key:t,value:n})=>e(h5(t,n,r))),orders:(t.orders??[]).map(e=>(t,n)=>e(h5(t.key,t.value,r),h5(n.key,n.value,r)))})){let e=h5(n,i,r);e.id.equals(this.peerId)||(yield e)}}async #P(e){try{let t=await this.datastore.get(hZ(e)),r=hW(e,t);return{existingBuf:t,existingPeer:r}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async #D(e,t,r,n){let i=te.encode(t);return null!=r&&(0,tI.f)(i,r)?{peer:hW(e,i),previous:n,updated:!1}:(await this.datastore.put(hZ(e),i),{peer:hW(e,i),previous:n,updated:!0})}}class h9{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 h8(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let r of this.store.all(t))e(r)}finally{this.log.trace("forEach release read lock"),r()}}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 tv(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 r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let r=await this.store.save(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("save release write lock"),r()}}async patch(e,t){this.log.trace("patch await write lock");let r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let r=await this.store.patch(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("patch release write lock"),r()}}async merge(e,t){this.log.trace("merge await write lock");let r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let r=await this.store.merge(e,t);return this.#N(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){let r;let n=await cd.openAndCertify(e,am.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 i=am.createFromProtobuf(n.payload);try{r=await this.get(n.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(r?.peerRecordEnvelope!=null){let e=await cd.createFromProtobuf(r.peerRecordEnvelope),t=am.createFromProtobuf(e.payload);if(t.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))}),!0}#N(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}var h7=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(let t of e);})();for(let t of e);},de=function(e){let[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}},dt=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(let n of e)await t(n,r++)&&(yield n)}();let n=de(e),{value:i,done:s}=n.next();if(!0===s)return function*(){}();let o=t(i,r++);return"function"==typeof o.then?async function*(){for await(let e of(await o&&(yield i),n))await t(e,r++)&&(yield e)}():function*(){for(let e of(!0===o&&(yield i),n))t(e,r++)&&(yield e)}()},dr=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=await tv(e);yield*r.sort(t)}():function*(){let r=tv(e);yield*r.sort(t)}()},dn=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1)){for await(let n of e)if(yield n,++r===t)return}}():function*(){let r=0;if(!(t<1)){for(let n of e)if(yield n,++r===t)return}}()};class di{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async *putMany(e,t={}){for await(let{key:r,value:n}of e)await this.put(r,n,t),yield r}async *getMany(e,t={}){for await(let r of e)yield{key:r,value:await this.get(r,t)}}async *deleteMany(e,t={}){for await(let r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await h7(this.putMany(e,r)),e=[],await h7(this.deleteMany(t,r)),t=[]}}}async *_all(e,t){throw Error("._all is not implemented")}async *_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){let t=e.prefix;r=dt(r,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>dt(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>dr(e,t),r)),null!=e.offset){let t=0,n=e.offset;r=dt(r,()=>t++>=n)}return null!=e.limit&&(r=dn(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){let t=e.prefix;r=dt(r,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>dt(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>dr(e,t),r)),null!=e.offset){let t=e.offset,n=0;r=dt(r,()=>n++>=t)}return null!=e.limit&&(r=dn(r,e.limit)),r}}class ds extends di{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(null==t){var r;throw tD(r=r??Error("Not Found"),"ERR_NOT_FOUND")}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 hX(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new hX(e)}}let da=e=>e;function dl(e,t){let r=e.getPeerId();if(null!=r){let n=s9(r);n.equals(t)&&(e=e.decapsulate(oG(`/p2p/${t.toString()}`)))}return e}class dc{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){var r;let n;let{listen:i=[],announce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=i.map(e=>e.toString()),this.announce=new Set(s.map(e=>e.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??da,this._updatePeerStoreAddresses=(r=this._updatePeerStoreAddresses.bind(this),function(){clearTimeout(n),n=setTimeout(function(){n=void 0,r()},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(([e,t])=>t.confident).map(([e])=>oG(e))).map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(e=>oG(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>oG(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>oG(e))}addObservedAddr(e){e=dl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=dl(e,this.components.peerId);let t=e.toString(),r=this.observed.get(t)??{confident:!1},n=r.confident;this.observed.set(t,{confident:!0}),n||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=dl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(e=>e.toString());0===e.length&&(e=this.components.transportManager.getAddrs().map(e=>e.toString())),e=e.concat(Array.from(this.observed).filter(([e,t])=>t.confident).map(([e])=>e));let t=new Set(e);return this.announceFilter(Array.from(t).map(e=>oG(e))).map(e=>e.protos().pop()?.path===!0||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`))}}class du{components={};_started=!1;constructor(e={}){for(let[t,r]of(this.components={},Object.entries(e)))this.components[t]=r;null==this.components.logger&&(this.components.logger=hb())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>null!=e&&"function"==typeof e.start&&"function"==typeof e.stop).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")}}let dh=["metrics","connectionProtector","dns"],dd=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var dp=r(5194);let df=["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"].map(e=>new dp.Netmask(e));function dg(e){return ov(e)?function(e){for(let t of df)if(t.contains(e))return!0;return!1}(e):oE(e)?/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^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(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e):void 0}function dy(e){try{let{address:t}=e.nodeAddress();return!!dg(t)}catch{return!0}}function dm(e,t){let r=function(e,t){let r=dy(e.multiaddr),n=dy(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;let n=function(e,t){let r=cG.exactMatch(e.multiaddr),n=cG.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==n)return n;let i=e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0;return i}class db extends Event{constructor(e,t){super(e),this.detail=t}}function dw(e){let t=[tn.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function dv(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map(e=>({name:e.name,type:tn[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:tn[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?(0,i5.B)(e.data):e.data}))}}function dE(e,t={}){let r=new hk({concurrency:t.queryConcurrency??4});return async(t,n={})=>{let i=new URLSearchParams;i.set("name",t),dw(n.types).forEach(e=>{i.append("type",tn[e])}),n.onProgress?.(new db("dns:query",{detail:t}));let s=await r.add(async()=>{let t=await fetch(`${e}?${i}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);let r=dv(await t.json());return n.onProgress?.(new db("dns:response",{detail:r})),r},{signal:n.signal});if(null==s)throw Error("No DNS response received");return s}}var dS=r(3746);class dA{lru;constructor(e){this.lru=dS(e)}get(e,t){let r=!0,n=[];for(let i of t){let t=this.getAnswers(e,i);if(0===t.length){r=!1;break}n.push(...t)}if(r)return dv({answers:n})}getAnswers(e,t){let r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){let e=n.filter(e=>e.expires>Date.now()).map(({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:tn[t.type]}));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){let r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+(t.TTL??60)*1e3,value:t}),this.lru.set(r,n)}remove(e,t){let r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class dI{resolvers;cache;constructor(e){this.resolvers={},this.cache=new dA(e.cacheSize??1e3),Object.entries(e.resolvers??{}).forEach(([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t}),null==this.resolvers["."]&&(this.resolvers["."]=[dE("https://cloudflare-dns.com/dns-query"),dE("https://dns.google/resolve")])}async query(e,t={}){let r=dw(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new db("dns:cache",{detail:n})),n;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];for(let n of s){if(t.signal?.aborted===!0)break;try{let i=await n(e,{...t,types:r});for(let t of i.Answer)this.cache.add(e,t);return i}catch(e){o.push(e),t.onProgress?.(new db("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(eI=tn||(tn={}))[eI.A=1]="A",eI[eI.CNAME=5]="CNAME",eI[eI.TXT=16]="TXT",eI[eI.AAAA=28]="AAAA";let{code:dT}=oR("dnsaddr"),d_=async function(e,t={}){let r=t.maxRecursiveDepth??32;if(0===r)throw new iJ("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,n]=e.stringTuples().find(([e])=>e===dT)??[],i=t?.dns??function(e={}){return new dI(e)}(),s=await i.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[tn.TXT]}),o=e.getPeerId(),a=[];for(let e of s.Answer){let n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n||null!=o&&!n.includes(o))continue;let i=oG(n);if(n.startsWith("/dnsaddr")){let e=await i.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map(e=>e.toString()))}else a.push(i.toString())}return a};var dR=r(3498);(eT=ti||(ti={})).NOT_STARTED_YET="The libp2p node is not started yet",eT.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",eT.NOT_FOUND="Not found",(e_=ts||(ts={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e_.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e_.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e_.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e_.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e_.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e_.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e_.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e_.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e_.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e_.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e_.ERR_DIALED_SELF="ERR_DIALED_SELF",e_.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e_.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e_.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e_.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e_.ERR_INVALID_KEY="ERR_INVALID_KEY",e_.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e_.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e_.ERR_INVALID_PEER="ERR_INVALID_PEER",e_.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e_.ERR_NOT_FOUND="ERR_NOT_FOUND",e_.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e_.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e_.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e_.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e_.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e_.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e_.ERR_FIND_SELF="ERR_FIND_SELF",e_.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e_.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e_.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e_.ERR_INVALID_CMS="ERR_INVALID_CMS",e_.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e_.ERR_NO_KEY="ERR_NO_KEY",e_.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e_.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e_.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e_.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e_.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e_.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e_.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e_.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e_.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e_.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e_.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e_.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e_.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e_.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e_.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e_.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e_.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e_.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e_.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e_.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e_.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e_.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e_.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e_.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";let dC={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:d_},addressSorter:dm},transportManager:{faultTolerance:ej.FATAL_ALL}};async function dk(e){let t=dR(dC,e);if(null===t.connectionProtector&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new iJ(ti.ERR_PROTECTOR_REQUIRED,ts.ERR_PROTECTOR_REQUIRED);if(null!=t.privateKey&&!(await oe(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new iJ("Private key doesn't match peer id",ts.ERR_INVALID_KEY);return t}function dB(e){let t;if(sJ(e))return{peerId:e,multiaddrs:[]};if(Array.isArray(e)||(e=[e]),e.length>0){let r=e[0].getPeerId();t=null==r?void 0:s9(r),e.forEach(e=>{if(!e?.[oH])throw new iJ("Invalid Multiaddr",ts.ERR_INVALID_MULTIADDR);let r=e.getPeerId();if(null==r){if(null!=t)throw new iJ("Multiaddrs must all have the same peer id or have no peer id",ts.ERR_INVALID_PARAMETERS)}else{let e=s9(r);if(null==t||!t.equals(e))throw new iJ("Multiaddrs must all have the same peer id or have no peer id",ts.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}class dP 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 dD(e,t,r,n){let i=new dP(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(i):new Promise((s,o)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,l),n?.errorEvent!=null&&e.removeEventListener(n.errorEvent,c)}let l=e=>{try{if(n?.filter?.(e)===!1)return}catch(e){a(),o(e);return}a(),s(e)},c=e=>{a(),o(e.detail)},u=()=>{a(),o(i)};r?.addEventListener("abort",u),e.addEventListener(t,l),n?.errorEvent!=null&&e.addEventListener(n.errorEvent,c)})}class dN{deferred;signal;constructor(e){this.signal=e,this.deferred=tx(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new iX)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class dL{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,rA(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){let e=this.recipients.reduce((e,t)=>e&&t.signal?.aborted===!0,!0);e&&(this.controller.abort(new iX),this.cleanup())}async join(e={}){let t=new dN(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 rL(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)})}}class dx extends rI{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&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(0===this.size)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),0===this.running&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(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),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let r=new dL(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then(e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e)).catch(e=>{if("queued"===r.status){for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}}throw this.safeDispatchEvent("error",{detail:e}),this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new iX)}),this.clear()}async onEmpty(e){0!==this.size&&await dD(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await dD(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){(0!==this.pending||0!==this.size)&&await dD(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=tF({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},i=e=>{r(e.detail)},s=()=>{r()},o=()=>{r(new iJ("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),r()}}}class dO extends dx{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}let dM="last-dial-failure",dU={minConnections:5,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:42e4,autoDialDiscoveredPeersDebounce:10};class dF{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){let r;this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??dU.minConnections,this.autoDialPriority=t.autoDialPriority??dU.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??dU.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??dU.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??dU.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??dU.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new dO({concurrency:t.autoDialConcurrency??dU.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",e=>{this.log.error("error during auto-dial",e.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(e=>{this.log.error(e)})}),e.events.addEventListener("peer:discovery",()=>{clearTimeout(r),r=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error(e)})},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 r=new hv(this.connectionManager.getDialQueue().map(e=>e.peerId).filter(Boolean)),n=await this.peerStore.all({filters:[t=>0===t.addresses.length?(this.log.trace("not autodialing %p because they have no addresses",t.id),!1):e.has(t.id)?(this.log.trace("not autodialing %p because they are already connected",t.id),!1):r.has(t.id)?(this.log.trace("not autodialing %p because they are already being dialed",t.id),!1):!this.queue.has(t.id)||(this.log.trace("not autodialing %p because they are already being autodialed",t.id),!1)]}),i=n.sort(()=>Math.random()>.5?1:-1),s=new h_;for(let e of i)s.has(e.id)||s.set(e.id,[...e.tags.values()].reduce((e,t)=>e+t.value,0));let o=i.sort((e,t)=>{let r=s.get(e.id)??0,n=s.get(t.id)??0;return r>n?-1:r<n?1:0}),a=o.filter(e=>{let t=e.metadata.get(dM);if(null==t)return!0;let r=parseInt((0,i5.B)(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs});for(let e of(this.log("selected %d/%d peers to dial",a.length,n.length),a))this.queue.add(async()=>{let t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections){this.log("got enough connections now %d/%d",t,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",e.id),await this.connectionManager.openConnection(e.id,{priority:this.autoDialPriority})},{peerId:e.id}).catch(e=>{this.log.error("could not connect to peerStore stored peer",e)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}}let dK=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function dV(e,t){let r=e?.streams?.map(e=>e.protocol)??[],n=t?.closableProtocols??dK;if(!(r.filter(e=>null!=e&&!n.includes(e)).length>0))try{await e?.close(t)}catch(t){e?.abort(t)}}let dH={maxConnections:100,allow:[]};class d${maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??dH.maxConnections,this.allow=t.allow??dH.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(e=>{this.log.error(e)})})}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 r=new h_;for(let t of e){let e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{let t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce((e,t)=>e+t.value,0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}let n=this.sortConnections(e,r),i=Math.max(t-this.maxConnections,0),s=[];for(let e of n){this.log("too many connections open - closing a connection to %p",e.remotePeer);let t=this.allow.some(t=>e.remoteAddr.toString().startsWith(t.toString()));if(t||s.push(e),s.length===i)break}await Promise.all(s.map(async e=>{await dV(e,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((e,t)=>{let r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0}).sort((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0).sort((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0).sort((e,r)=>{let n=t.get(e.remotePeer)??0,i=t.get(r.remotePeer)??0;return n>i?1:n<i?-1:0})}}class dq extends dx{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function dz(e){let t=new globalThis.AbortController;function r(){for(let n of(t.abort(),e))n?.removeEventListener!=null&&n.removeEventListener("abort",r)}for(let t of e){if(t?.aborted===!0){r();break}t?.addEventListener!=null&&t.addEventListener("abort",r)}let n=t.signal;return n.clear=function(){for(let t of e)t?.removeEventListener!=null&&t.removeEventListener("abort",r)},n}async function dG(e,t){let r=!1;for(let t of oz.keys())if(r=e.protoNames().includes(t))break;if(!r)return[e];let n=await e.resolve(t);return t.log("resolved %s to",e,n.map(e=>e.toString())),n}let dj={addressSorter:dm,maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3};class dW{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){for(let[r,n]of(this.addressSorter=t.addressSorter??dj.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??dj.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??dj.maxDialQueueLength,this.dialTimeout=t.dialTimeout??dj.dialTimeout,this.connections=t.connections??new h_,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,rA(1/0,this.shutDownController.signal),Object.entries(t.resolvers??{})))oz.set(r,n);this.queue=new dq({concurrency:t.maxParallelDials??dj.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",e=>{this.log.error("error in dial queue",e.detail)})}start(){this.shutDownController=new AbortController,rA(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:r,multiaddrs:n}=dB(e),i=Array.from(this.connections.values()).flat().find(e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find(t=>t.equals(e.remoteAddr))));if(null!=i)return this.log("already connected to %a",i.remoteAddr),i;let s=this.queue.queue.find(e=>{if(r?.equals(e.options.peerId)===!0)return!0;let t=e.options.multiaddrs;if(null==t)return!1;for(let e of n)if(t.has(e.toString()))return!0;return!1});if(null!=s){for(let e of(this.log("joining existing dial target for %p",r),n))s.options.multiaddrs.add(e.toString());return s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new iJ("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",r,n.map(e=>e.toString())),this.queue.add(async e=>{let t;let n=this.createDialAbortController(e?.signal);try{(t=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:n})).map(({multiaddr:e})=>e.toString()).forEach(t=>{e?.multiaddrs.add(t)})}catch(e){throw n.clear(),e}try{let i=0,s=[];for(let o of t){if(i===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",i,r),new iJ("Peer had more than maxPeerAddrsToDial",ts.ERR_TOO_MANY_ADDRESSES);i++;try{let t=await this.components.transportManager.dial(o.multiaddr,{...e,signal:n});return this.log("dial to %a succeeded",o.multiaddr),t}catch(e){if(this.log.error("dial failed to %a",o.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[dM]:(0,i2.m)(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(n.aborted)throw new iJ(e.message,i0);s.push(e)}}if(1===s.length)throw s[0];throw new iZ(s,"All multiaddr dials failed",ts.ERR_TRANSPORT_DIAL_FAILED)}finally{n.clear()}},{peerId:r,priority:t.priority??dY,multiaddrs:new Set(n.map(e=>e.toString())),signal:t.signal})}createDialAbortController(e){let t=dz([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return rA(1/0,t),t}async calculateMultiaddrs(e,t=new Set,r={}){let n=[...t].map(e=>({multiaddr:oG(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new iJ("Tried to dial self",ts.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new iJ("The dial request is blocked by gater.allowDialPeer",ts.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{let t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:e})=>e.toString()))}catch(e){if(e.code!==ts.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{let t=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:e})=>e.toString())),n.push(...t.multiaddrs.map(e=>({multiaddr:e,isCertified:!1})))}catch(t){t.code!==ts.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let i=(await Promise.all(n.map(async e=>{let t=await dG(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map(e=>({multiaddr:e,isCertified:!1}))}))).flat();if(null!=e){let t=`/p2p/${e.toString()}`;i=i.map(e=>{let r=e.multiaddr.protos().pop();return r?.path===!0?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e})}let s=i.filter(t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;let r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)}),o=new Map;for(let e of s){let t=e.multiaddr.toString(),r=o.get(t);if(null!=r){r.isCertified=r.isCertified||e.isCertified||!1;continue}o.set(t,e)}let a=[...o.values()];if(0===a.length)throw new iJ("The dial request has no valid addresses",ts.ERR_NO_VALID_ADDRESSES);let l=[];for(let e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||l.push(e);let c=l.sort(this.addressSorter);if(0===c.length)throw new iJ("The connection gater denied all addresses in the dial request",ts.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:e})=>e.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",c.map(({multiaddr:e})=>e.toString())),c}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let r=await this.calculateMultiaddrs(void 0,new Set(e.map(e=>e.toString())),t);if(!1===t.runOnTransientConnection)return null!=r.find(e=>!cG.matches(e.multiaddr));return!0}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}let dY=50,dQ={minConnections:5,maxConnections:100,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:42e4,autoDialDiscoveredPeersDebounce:10};class dX{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??dQ.maxConnections;let r=t.minConnections??dQ.minConnections;if(this.maxConnections<r)throw new iJ("Connection Manager maxConnections must be greater than minConnections",ts.ERR_INVALID_PARAMETERS);this.connections=new h_,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(e=>oG(e)),this.deny=(t.deny??[]).map(e=>oG(e)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??dQ.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new ur({points:t.inboundConnectionThreshold??dQ.inboundConnectionThreshold,duration:1}),this.autoDial=new dF({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??dQ.autoDialConcurrency,autoDialPriority:t.autoDialPriority??dQ.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??dQ.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??dQ.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??dQ.autoDialMaxQueueLength}),this.connectionPruner=new d$({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new dW(e,{addressSorter:t.addressSorter??dm,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:d_},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 r of t)"inbound"===r.direction?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 r of t)for(let t of r.streams){let r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let r of t){let t={};for(let e of r.streams){let r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(let[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}let t={};for(let[r,n]of Object.entries(e)){n=n.sort((e,t)=>e-t);let e=Math.floor(.9*n.length);t[r]=n[e]}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:[e=>e.tags.has("keep-alive")]});await Promise.all(e.map(async e=>{await this.openConnection(e.id).catch(e=>{this.log.error(e)})}))}).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 r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(e=>{this.log.error(e)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let r=t.remotePeer,n=this.connections.get(r),i=!1;null!=n?n.push(t):(i=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),i&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let r=t.remotePeer,n=this.connections.get(r);null!=n&&n.length>1?(n=n.filter(e=>e.id!==t.id),this.connections.set(r,n)):null!=n&&(this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(let e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new iJ("Not started",ts.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:r}=dB(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);let e=this.getConnections(r).find(e=>!e.transient);if(null!=e)return this.log("had an existing non-transient connection to %p",r),e}let n=await this.dialQueue.dial(e,{...t,priority:t.priority??dY}),i=this.connections.get(n.remotePeer);null==i&&(i=[],this.connections.set(n.remotePeer,i));let s=!1;for(let e of i)e.id===n.id&&(s=!0);return s||i.push(n),n}async closeConnections(e,t={}){let r=this.connections.get(e)??[];await Promise.all(r.map(async e=>{try{await e.close(t)}catch(t){e.abort(t)}}))}async acceptIncomingConnection(e){let t=this.deny.some(t=>e.remoteAddr.toString().startsWith(t.toString()));if(t)return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;let r=this.allow.some(t=>e.remoteAddr.toString().startsWith(t.toString()));if(r)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 t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!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(e=>oG(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class dJ{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(0===this.routers.length)throw new iJ("No content routers available",ts.ERR_NO_ROUTERS_AVAILABLE);let r=new hv;for await(let n of tK(...this.routers.map(r=>r.findProviders(e,t))))null!=n&&(n.multiaddrs.length>0&&await this.components.peerStore.merge(n.id,{multiaddrs:n.multiaddrs}),r.has(n.id)||(r.add(n.id),yield n))}async provide(e,t={}){if(0===this.routers.length)throw new iJ("No content routers available",ts.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async r=>{await r.provide(e,t)}))}async put(e,t,r){if(!this.isStarted())throw new iJ(ti.NOT_STARTED_YET,ts.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async n=>{await n.put(e,t,r)}))}async get(e,t){if(!this.isStarted())throw new iJ(ti.NOT_STARTED_YET,ts.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async r=>r.get(e,t)))}}class dZ{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw TypeError("Invalid Fingerprint Size");let i=t.hashV(e,r),s=(0,tS.u)(n);for(let e=0;e<s.length;e++)s[e]=i[e];0===s.length&&(s[0]=7),this.fp=s,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&(0,tI.f)(this.fp,e.fp)}}function d0(e,t){return Math.floor(Math.random()*(t-e))+e}class d1{contents;constructor(e){this.contents=Array(e).fill(null)}has(e){if(!(e instanceof dZ))throw TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof dZ))throw TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t]){this.contents[t]=e;break}return!0}swap(e){if(!(e instanceof dZ))throw TypeError("Invalid Fingerprint");let t=d0(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof dZ))throw TypeError("Invalid Fingerprint");let t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}let d2={32:16777619n,64:1099511628211n,128:0x1000000000000000000013bn,256:0x1000000000000000000000000000000000000000163n,512:0x100000000000000000000000000000000000000000000000000000000000000000000000000000000000157n,1024:0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018dn},d3={32:2166136261n,64:0xcbf29ce484222325n,128:0x6c62272e07bb014262b821756295c58dn,256:0xdd268dbcaac550362d98c384c4e576ccc8b1536847b6bbb31023b4c8caee0535n,512:0xb86db0b1171f4416dca1e50f309990acac87d059c90000000000000000000d21e948f68a34c192f62ea79bc942dbe7ce182036415f56e34bac982aac4afe9fd9n,1024:0x5f7a76758ecc4d32e56d5a591028b74b29fc4223fdada16c3bf34eda3674da9a21d9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004c6d7eb6e73802734510a555f256cc005ae556bde8cc9c6a93b21aff4b16c71ee90b3n},d4=new globalThis.TextEncoder;r(7176);let d6={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!d2[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");let n=d2[t],i=d3[t],s=e;for(;s.length>0;){let e=d4.encodeInto(s,r);s=s.slice(e.read);for(let s=0;s<e.written;s++)i^=BigInt(r[s]),i=BigInt.asUintN(t,i*n)}return i}(e,t,r);e=d4.encode(e)}return function(e,t){let r=d2[t],n=d3[t];for(let i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>{let r;return(r=d6.hash(e,t).toString(16)).length%2==1&&(r=`0${r}`),(0,i2.m)(r,"base16")}};class d5{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??d6,this.seed=e.seed??d0(0,1024)}add(e){"string"==typeof e&&(e=(0,i2.m)(e));let t=new dZ(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new d1(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new d1(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;let i=[r,n],s=i[d0(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new d1(this.bucketSize));for(let e=0;e<500;e++){let e=this.buckets[s].swap(t);if(null!=e){if(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new d1(this.bucketSize)),this.buckets[s].add(e))return this.count++,!0;continue}}return!1}has(e){"string"==typeof e&&(e=(0,i2.m)(e));let t=new dZ(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;let i=(r^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){"string"==typeof e&&(e=(0,i2.m)(e));let t=new dZ(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;let i=(r^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return 95>=Math.floor(100*(this.count/this.filterSize))}}let d8={1:.5,2:.84,4:.95,8:.98};class d9{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??262144/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??d6,this.seed=e.seed??d0(0,1024),this.filterSeries=[new d5({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=(0,i2.m)(e)),this.has(e))return!0;let t=this.filterSeries.find(e=>e.reliable);if(null==t){let e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new d5({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=(0,i2.m)(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=(0,i2.m)(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)}}let d7=globalThis.CustomEvent??Event;async function*pe(e,t={}){let r,n=t.concurrency??1/0;n<1&&(n=1/0);let i=null!=t.ordered&&t.ordered,s=new EventTarget,o=[],a=tx(),l=tx(),c=!1,u=!1;function h(){return i?o[0]?.done:!!o.find(e=>e.done)}for(s.addEventListener("task-complete",()=>{l.resolve()}),Promise.resolve().then(async()=>{try{for await(let t of e){if(o.length===n&&(a=tx(),await a.promise),u)break;let e={done:!1};o.push(e),t().then(t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new d7("task-complete"))},t=>{e.done=!0,e.err=t,s.dispatchEvent(new d7("task-complete"))})}c=!0,s.dispatchEvent(new d7("task-complete"))}catch(e){r=e,s.dispatchEvent(new d7("task-complete"))}});;){if(h()||(l=tx(),await l.promise),null!=r)throw r;if(i?yield*function*(){for(;o.length>0&&o[0].done;){let e=o[0];if(o.shift(),e.ok)yield e.value;else throw u=!0,a.resolve(),e.err;a.resolve()}}():yield*function*(){for(;h();)for(let e=0;e<o.length;e++)if(o[e].done){let t=o[e];if(o.splice(e,1),e--,t.ok)yield t.value;else throw u=!0,a.resolve(),t.err;a.resolve()}}(),c&&0===o.length)break}}class pt{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(0===this.routers.length)throw new iJ("No peer routers available",ts.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new iJ("Should not try to find self",ts.ERR_FIND_SELF);let r=this,n=tK(...this.routers.map(n=>(async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}})()));for await(let e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new iJ(ti.NOT_FOUND,ts.ERR_NOT_FOUND)}async *getClosestPeers(e,t={}){if(0===this.routers.length)throw new iJ("No peer routers available",ts.ERR_NO_ROUTERS_AVAILABLE);let r=this,n=function(e,t=.001,r){return new d9({...function(e,t=.001){let r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=d8[r],i=Math.round(1024/n);return{filterSize:i,bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log(i/r))+2,64)}}(0,t),...(void 0)??{}})}(0);for await(let i of pe(async function*(){let n=tK(...r.routers.map(r=>r.getClosestPeers(e,t)));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){r.log.error("could not find peer multiaddrs",e);return}return e}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),n.has(i.id.toBytes())||(n.add(i.id.toBytes()),yield i))}}class pr extends rI{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,rA(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,rA(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async *walk(e){this.walking||this.startWalk(),this.walkers++;let t=dz([this.shutdownController.signal,e?.signal]);rA(1/0,t);try{for(;;){this.needNext?.resolve(),this.needNext=tx();let e=await dD(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,rA(1/0,this.walkController.signal);let e=dz([this.walkController.signal,this.shutdownController.signal]);rA(1/0,e);let t=Date.now(),r=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let t=lX(32),n=Date.now();for await(let i of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:i}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await rL(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")}).catch(e=>{this.log.error("randomwalk errored",e)}).finally(()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1})}}class pn{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(null==t)throw new iJ(`No handler registered for protocol ${e}`,ts.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new iJ(`Handler already registered for protocol ${e}`,ts.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let n=dR.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(e=>{this.handlers.delete(e)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(null==t)throw new iJ("invalid topology",ts.ERR_INVALID_PARAMETERS);let r=`${(1e9*Math.random()).toString(36)}${Date.now()}`,n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(let[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(e=>{for(let r of e.protocols){let e=this.topologies.get(r);if(null!=e)for(let r of e.values())r.filter?.has(t)!==!1&&(r.filter?.remove(t),r.onDisconnect?.(t))}}).catch(e=>{e.code!==ts.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)})}_onPeerUpdate(e){let{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter(e=>!t.protocols.includes(e));for(let e of n){let r=this.topologies.get(e);if(null!=r)for(let e of r.values())e.filter?.has(t.id)!==!1&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(let e of t){let t=this.topologies.get(e);if(null!=t)for(let e of t.values())r.transient&&!0!==e.notifyOnTransient||e.filter?.has(n)===!0||(e.filter?.add(n),e.onConnect?.(n,r))}}}class pi extends Map{metric;constructor(e){super();let{name:t,metrics:r}=e;this.metric=r.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)}}class ps{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=function(e){let{name:t,metrics:r}=e;return null!=r?new pi({name:t,metrics:r}):new Map}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ej.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(null==t)throw new iJ("Transport must have a valid tag",ts.ERR_INVALID_KEY);if(this.transports.has(t))throw new iJ(`There is already a transport with the tag ${t}`,ts.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,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){let t=r.pop();null!=t&&e.push(t.close())}for(let t of(await Promise.all(e),this.log("all listeners closed"),this.listeners.keys()))this.listeners.set(t,[]);this.started=!1}async dial(e,t){let r=this.dialTransportForMultiaddr(e);if(null==r)throw new iJ(`No transport available for address ${String(e)}`,ts.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=ts.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let r of t)e=[...e,...r.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()){let r=t.dialFilter([e]);if(r.length>0)return t}}listenTransportForMultiaddr(e){for(let t of this.transports.values()){let r=t.listenFilter([e]);if(r.length>0)return t}}async listen(e){if(!this.isStarted())throw new iJ("Not started",ts.ERR_NODE_NOT_STARTED);if(null==e||0===e.length){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[r,n]of this.transports.entries()){let i=n.listenFilter(e),s=[];for(let e of i){this.log("creating listener for %s on %a",r,e);let t=n.createListener({upgrader:this.components.upgrader}),i=this.listeners.get(r)??[];null==i&&(i=[],this.listeners.set(r,i)),i.push(t),t.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})}),t.addEventListener("close",()=>{let e=i.findIndex(e=>e===t);i.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})}),s.push(t.listen(e))}if(0===s.length){t.push(r);continue}let o=await Promise.allSettled(s),a=o.find(e=>"fulfilled"===e.status);if(null==a&&this.faultTolerance!==ej.NO_FATAL)throw new iJ(`Transport (${r}) could not listen on any available address`,ts.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===ej.FATAL_ALL)throw new iJ(e,ts.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),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)}}let po="/multistream/1.0.0",pa=(0,i2.m)("\n");async function pl(e,t,r){await e.write(t,r)}async function pc(e,t,r){await e.writeV(t,r)}async function pu(e,t){let r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==pa[0])throw t.log.error("Invalid mss message - missing newline",r),new iJ("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function ph(e,t){let r=await pu(e,t);return(0,i5.B)(r.subarray())}async function pd(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);let n=rF(e,{...r,maxDataLength:1024,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");let e=await ph(n,r);if(r.log.trace('handle: read "%s"',e),e===po){r.log.trace('handle: respond with "%s" for "%s"',po,e),await pl(n,(0,i2.m)(`${po}
|
|
`),r),r.log.trace('handle: responded with "%s" for "%s"',po,e);continue}if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await pl(n,(0,i2.m)(`${e}
|
|
`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"===e){let i=new tC(...t.map(e=>tP.single((0,i2.m)(`${e}
|
|
`))),(0,i2.m)("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await pl(n,i,r),r.log.trace('handle: responded with "%s" for %s',t,e);continue}r.log('handle: respond with "na" for "%s"',e),await pl(n,(0,i2.m)("na\n"),r),r.log('handle: responded with "na" for "%s"',e)}}async function pp(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){let n=e.sink.bind(e),i=e.source,s=!1,o=!1,a=tx(),l=!1,c=!1,u=tx(),h=!1,d=!1,p=tx(),f=rF({sink:n,source:i},{...r,maxDataLength:1024});async function g(){if(o){r.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}o=!0;try{l||(r.log.trace("optimistic: doing send protocol for %s stream",t),await y()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await m())}finally{o=!1,s=!0,a.resolve()}}async function y(){if(c){await u.promise;return}c=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',po,t),await f.writeV([(0,i2.m)(`${po}
|
|
`),(0,i2.m)(`${t}
|
|
`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',po,t)}finally{l=!0,c=!1,u.resolve()}}async function m(){if(d){await p.promise;return}d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await ph(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===po&&(e=await ph(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new iJ("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}if(e.sink=async e=>{let{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(let i of e){if(c&&await u.promise,l)yield i;else{c=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',po,t,i.byteLength);let e=`${t}
|
|
`;yield new tC(Uint8Array.from([19]),(0,i2.m)(`${po}
|
|
`),tE.cv(e.length),(0,i2.m)(e),i).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',po,t,i.byteLength),l=!0,c=!1,u.resolve(),g().catch(e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)})}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){let t=e.closeRead.bind(e);e.closeRead=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close read",e)}),await t(e)}}if(null!=e.closeWrite){let t=e.closeWrite.bind(e);e.closeWrite=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close write",e)}),await t(e)}}if(null!=e.close){let t=e.close.bind(e);e.close=async e=>{let r=[];c&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await rL(Promise.all(r),e?.signal):(s=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);let n=rF(e,{...r,maxDataLength:1024}),i=t.shift();if(null==i)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',po,i);let s=(0,i2.m)(`${po}
|
|
`),o=(0,i2.m)(`${i}
|
|
`);await pc(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await ph(n,r);if(r.log.trace('select: read "%s"',a),a===po&&(r.log.trace("select: reading protocol response"),a=await ph(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let e of t){r.log.trace('select: write "%s"',e),await pl(n,(0,i2.m)(`${e}
|
|
`),r),r.log.trace("select: reading protocol response");let t=await ph(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new iJ("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}let pf=Symbol.for("@libp2p/connection");class pg{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:r,newStream:n,close:i,abort:s,getStreams:o}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,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}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=i,this._abort=s,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[pf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new iJ("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new iJ("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new iJ("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){let t=AbortSignal.timeout(500);rA(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(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}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 py(e,t,r){let n=0;return r.streams.forEach(r=>{r.direction===t&&r.protocol===e&&n++}),n}class pm{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(e=>{this.connectionEncryption.set(e.protocol,e)}),this.muxers=new Map,t.muxers.forEach(e=>{this.muxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,r){let n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new iJ(`The multiaddr connection is blocked by gater.${r}`,ts.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){let r,n,i,s,o;let a=await this.components.connectionManager.acceptIncomingConnection(e);if(!a)throw new iJ("connection denied",ts.ERR_CONNECTION_DENIED);let l=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new iJ("inbound upgrade timeout",i0))};l.addEventListener("abort",c,{once:!0}),rA(1/0,l);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new iJ("The multiaddr connection is blocked by gater.acceptConnection",ts.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(t?.skipProtection!==!0){let t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,t?.skipEncryption!==!0){({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(a));let e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{let t=e.remoteAddr.getPeerId();if(null==t)throw new iJ("inbound connection that skipped encryption must have a peer id",ts.ERR_INVALID_MULTIADDR);let r=s9(t);o="native",n=r}if(i=r,t?.muxerFactory!=null)s=t.muxerFactory;else if(this.muxers.size>0){let e=await this._multiplexInbound({...a,...r},this.muxers);s=e.muxerFactory,i=e.stream}}catch(t){throw e.log.error("failed to upgrade inbound connection",t),t}return await this.shouldBlockConnection(n,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:o,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:s,remotePeer:n,transient:t?.transient})}finally{l.removeEventListener("abort",c),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let r,n,i,s,o,a;let l=e.remoteAddr.getPeerId();null!=l&&(r=s9(l),await this.shouldBlockConnection(r,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let c=e;if(t?.skipProtection!==!0){let t=this.components.connectionProtector;null!=t&&(c=await t.protect(e))}try{if(n=c,t?.skipEncryption!==!0){({conn:n,remotePeer:i,protocol:o}=await this._encryptOutbound(c,r));let e={...c,...n};await this.shouldBlockConnection(i,e,"denyOutboundEncryptedConnection")}else{if(null==r)throw new iJ("Encryption was skipped but no peer id was passed",ts.ERR_INVALID_PEER);o="native",i=r}if(s=n,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let e=await this._multiplexOutbound({...c,...n},this.muxers);a=e.muxerFactory,s=e.stream}}catch(t){throw e.log.error("failed to upgrade outbound connection",t),await e.close(t),t}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:o,direction:"outbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,transient:t?.transient})}_createConnection(e){let t,r,n;let{cryptoProtocol:i,direction:s,maConn:o,upgradedConn:a,remotePeer:l,muxerFactory:c,transient:u}=e;null!=c&&(t=c.createStreamMuxer({direction:s,onIncomingStream:e=>{null!=n&&Promise.resolve().then(async()=>{let t=this.components.registrar.getProtocols(),{stream:r,protocol:i}=await pd(e,t,{log:e.log,yieldBytes:!1});if(null==n)return;n.log("incoming stream opened on %s",i);let s=function(e,t){try{let{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==ts.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(i,this.components.registrar),o=py(i,"inbound",n);if(o===s){let t=new iJ(`Too many inbound protocol streams for protocol "${i}" - limit ${s}`,ts.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=i,null!=r.closeWrite&&(e.closeWrite=r.closeWrite),null!=r.closeRead&&(e.closeRead=r.closeRead),null!=r.close&&(e.close=r.close),await this.components.peerStore.merge(l,{protocols:[i]}),this.components.metrics?.trackProtocolStream(e,n),this._onStream({connection:n,stream:e,protocol:i})}).catch(async t=>{n.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()})}}),r=async(e,r={})=>{if(null==t)throw new iJ("Stream is not multiplexed",ts.ERR_MUXER_UNAVAILABLE);n.log("starting new stream for protocols %s",e);let i=await t.newStream();n.log.trace("started new stream %s for protocols %s",i.id,e);try{if(null==r.signal){i.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let t=AbortSignal.timeout(3e4);rA(1/0,t),r={...r,signal:t}}i.log.trace("selecting protocol from protocols %s",e);let{stream:t,protocol:s}=await pp(i,e,{...r,log:i.log,yieldBytes:!0});i.log("selected protocol %s",s);let o=function(e,t,r={}){try{let{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==ts.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,r),a=py(s,"outbound",n);if(a>=o){let e=new iJ(`Too many outbound protocol streams for protocol "${s}" - ${a}/${o}`,ts.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw i.abort(e),e}return await this.components.peerStore.merge(l,{protocols:[s]}),i.source=t.source,i.sink=t.sink,i.protocol=s,null!=t.closeWrite&&(i.closeWrite=t.closeWrite),null!=t.closeRead&&(i.closeRead=t.closeRead),null!=t.close&&(i.close=t.close),this.components.metrics?.trackProtocolStream(i,n),i}catch(t){if(n.log.error("could not create new stream for protocols %s",e,t),null==i.timeline.close&&i.abort(t),null!=t.code)throw t;throw new iJ(String(t),ts.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([t.sink(a.source),a.sink(t.source)]).catch(e=>{n.log.error("error piping data through muxer",e)}));let h=o.timeline;return o.timeline=new Proxy(h,{set:(...e)=>(null!=n&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===n.status&&await n.close()}catch(e){n.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:n})}})().catch(e=>{n.log.error("error thrown while dispatching connection:close event",e)}),Reflect.set(...e))}),o.timeline.upgraded=Date.now(),n=new pg({remoteAddr:o.remoteAddr,remotePeer:l,status:"open",direction:s,timeline:o.timeline,multiplexer:t?.protocol,encryption:i,transient:u,logger:this.components.logger,newStream:r??(()=>{throw new iJ("connection is not multiplexed",ts.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=t?t.streams:[],close:async e=>{null!=t&&(n.log.trace("close muxer"),await t.close(e)),n.log.trace("close maconn"),await o.close(e),n.log.trace("closed maconn")},abort:e=>{o.abort(e),null!=t&&t.abort(e)}}),this.events.safeDispatchEvent("connection:open",{detail:n}),n}_onStream(e){let{connection:t,stream:r,protocol:n}=e,{handler:i,options:s}=this.components.registrar.getHandler(n);if(t.transient&&!0!==s.runOnTransientConnection)throw new iJ("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");i({connection:t,stream:r})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:r,protocol:n}=await pd(e,t,{log:e.log}),i=this.connectionEncryption.get(n);if(null==i)throw Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await i.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new iJ(t.message,ts.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);let{stream:n,protocol:i}=await pp(e,r,{log:e.log,yieldBytes:!0}),s=this.connectionEncryption.get(i);if(null==s)throw Error(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %p using %s",t,s),{...await s.secureOutbound(this.components.peerId,n,t),protocol:i}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new iJ(r.message,ts.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);let{stream:n,protocol:i}=await pp(e,r,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let s=t.get(i);return{stream:n,muxerFactory:s}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new iJ(String(t),ts.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{let{stream:n,protocol:i}=await pd(e,r,{log:e.log}),s=t.get(i);return{stream:n,muxerFactory:s}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new iJ(String(t),ts.ERR_MUXER_UNAVAILABLE)}}}class pb extends rI{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new rI,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{let t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},rA(1/0,t),this.peerId=e.peerId,this.logger=e.logger??hb(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=this.components=function(e={}){let t=new du(e),r=new Proxy(t,{get(e,r,n){if("string"==typeof r&&!dd.includes(r)){let e=t.components[r];if(null==e&&!dh.includes(r))throw new iJ(`${r} not set`,"ERR_SERVICE_MISSING");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)});return r}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.7.0"},logger:this.logger,events:t,datastore:e.datastore??new ds,connectionGater:function(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!dg(`${t[0][1]}`)},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new h9(n,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),n.events.addEventListener("peer:update",e=>{if(null==e.detail.previous){let t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map(e=>e.multiaddr)};n.events.safeDispatchEvent("peer:discovery",{detail:t})}}),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(n)),this.components.upgrader=new pm(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components))),muxers:(e.streamMuxers??[]).map((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ps(this.components,e.transportManager)),this.configureComponent("connectionManager",new dX(this.components,e.connectionManager)),this.configureComponent("registrar",new pn(this.components)),this.configureComponent("addressManager",new dc(this.components,e.addresses));let i=(e.peerRouters??[]).map((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new pt(this.components,{routers:i}));let s=(e.contentRouters??[]).map((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new dJ(this.components,{routers:s})),this.configureComponent("randomWalk",new pr(this.components)),(e.peerDiscovery??[]).forEach((e,t)=>{let r=this.configureComponent(`peer-discovery-${t}`,e(this.components));r.addEventListener("peer",e=>{this.#L(e)})}),e.transports?.forEach((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))}),null!=e.services)for(let t of Object.keys(e.services)){let r=e.services[t],n=r(this.components);if(null==n){this.log.error("service factory %s returned null or undefined instance",t);continue}this.services[t]=n,this.configureComponent(t,n),null!=n[hg]&&(this.log("registering service %s for content routing",t),s.push(n[hg])),null!=n[hy]&&(this.log("registering service %s for peer routing",t),i.push(n[hy])),null!=n[of]&&(this.log("registering service %s for peer discovery",t),n[of].addEventListener?.("peer",e=>{this.#L(e)}))}!function(e){let t={};for(let r of Object.values(e.components))for(let e of Array.isArray(r?.[og])?r[og]:[])t[e]=!0;for(let r of Object.values(e.components))for(let e of Array.isArray(r?.[oy])?r[oy]:[])if(!0!==t[e])throw new iJ(`Service "${r?.[Symbol.toStringTag]??r?.toString()??"unknown"}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}(n)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){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(){"started"===this.status&&(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 hv;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,r={}){if(null==t||0===(t=Array.isArray(t)?t:[t]).length)throw new iJ("no protocols were provided to open a stream",ts.ERR_INVALID_PROTOCOLS_FOR_STREAM);let n=await this.dial(e,r);return n.newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){var r;r=e,r?.[oH]&&(e=s9(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{let t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==ts.ERR_NOT_FOUND)throw e}let r=tA([(0,i2.m)("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return cl(n),await this.peerStore.patch(e,{publicKey:n}),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.handle(e,t,r)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.unhandle(e)}))}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)}#L(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(Error(ts.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error(e)})}}async function pw(e={}){let t=e.peerId??=await hE();if(null==t.privateKey)throw new iJ("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await cu(t.privateKey),new pb(await dk(e))}async function pv(e={}){let t=await pw(e);return!1!==e.start&&await t.start(),t}class pE{core;connectionManager;numPeersToUse;peers=[];maintainPeersIntervalId=null;log;maintainPeersLock=!1;constructor(e,t,r){this.core=e,this.connectionManager=t,this.log=new tw.Yd(`sdk:${e.multicodec}`),this.numPeersToUse=r?.numPeersToUse??3;let n=r?.maintainPeersInterval??3e4;this.startMaintainPeersInterval(n)}get connectedPeers(){return this.peers}async renewPeer(e){this.log.info(`Renewing peer ${e}`);try{await this.connectionManager.dropConnection(e),this.peers=this.peers.filter(t=>t.id!==e),this.log.info(`Peer ${e} disconnected and removed from the peer list`),await this.findAndAddPeers(1)}catch(e){this.log.info("Peer renewal failed, relying on the interval to find a new peer")}}stopMaintainPeersInterval(){this.maintainPeersIntervalId&&(clearInterval(this.maintainPeersIntervalId),this.maintainPeersIntervalId=null,this.log.info("Maintain peers interval stopped"))}hasPeers=async(e={})=>{let{autoRetry:t=!1,forceUseAllPeers:r=!1,initialDelay:n=10,maxAttempts:i=3,maxDelay:s=100}=e;if(!r&&this.connectedPeers.length>0)return!0;let o=0;for(;o<i;){if(o++,await this.maintainPeers())return this.peers.length<this.numPeersToUse&&this.log.warn(`Found only ${this.peers.length} peers, expected ${this.numPeersToUse}`),!0;if(!t)return!1;let e=Math.min(n*Math.pow(2,o-1),s);await (0,tw.gw)(e)}return this.log.error("Failed to find peers to send message to"),!1};async startMaintainPeersInterval(e){this.log.info("Starting maintain peers interval");try{await this.maintainPeers(),this.maintainPeersIntervalId=setInterval(()=>{this.maintainPeers().catch(e=>{this.log.error("Error during maintain peers interval:",e)})},e),this.log.info(`Maintain peers interval started with interval ${e}ms`)}catch(e){throw this.log.error("Error starting maintain peers interval:",e),e}}async maintainPeers(){if(this.maintainPeersLock)return!1;this.maintainPeersLock=!0,this.log.info(`Maintaining peers, current count: ${this.peers.length}`);try{let e=this.numPeersToUse-this.peers.length;e>0&&await this.findAndAddPeers(e),this.log.info(`Peer maintenance completed, current count: ${this.peers.length}`)}finally{this.maintainPeersLock=!1}return!0}async findAndAddPeers(e){this.log.info(`Finding and adding ${e} new peers`);try{let t=await this.findAdditionalPeers(e);this.peers=[...this.peers,...t],this.log.info(`Added ${t.length} new peers, total peers: ${this.peers.length}`)}catch(e){throw this.log.error("Error finding and adding new peers:",e),e}}async findAdditionalPeers(e){this.log.info(`Finding ${e} additional peers`);try{let t=await this.core.getPeers({maxBootstrapPeers:0,numPeers:e});return 0===t.length&&(this.log.warn("No new peers found, trying with bootstrap peers"),t=await this.core.getPeers({maxBootstrapPeers:e,numPeers:e})),t=t.filter(e=>!1===this.peers.some(t=>t.id===e.id))}catch(e){throw this.log.error("Error finding additional peers:",e),e}}}let pS=new tw.Yd("sdk:filter"),pA={keepAlive:6e4};class pI{protocol;pubsubTopic;peers;receivedMessagesHashStr=[];keepAliveTimer=null;subscriptionCallbacks;constructor(e,t,r){this.protocol=r,this.peers=t,this.pubsubTopic=e,this.subscriptionCallbacks=new Map}async subscribe(e,t,r=pA){let n=Array.isArray(e)?e:[e];for(let e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:tb.K1.TOPIC_DECODER_MISMATCH}],successes:[]};let i=(0,tw.p3)(n),s=Array.from(i.keys()),o=this.peers.map(async e=>this.protocol.subscribe(this.pubsubTopic,e,s)),a=await Promise.allSettled(o),l=this.handleResult(a,"subscribe");return i.forEach((e,r)=>{this.subscriptionCallbacks.set(r,{decoders:e,callback:t})}),r?.keepAlive&&this.startKeepAlivePings(r.keepAlive),l}async unsubscribe(e){let t=this.peers.map(async t=>{let r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach(e=>{this.subscriptionCallbacks.delete(e)}),r}),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.keepAliveTimer&&this.stopKeepAlivePings(),n}async ping(){let e=this.peers.map(async e=>this.protocol.ping(e)),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){let e=this.peers.map(async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e)),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();let r=this.handleResult(t,"unsubscribeAll");return this.keepAliveTimer&&this.stopKeepAlivePings(),r}async processIncomingMessage(e){let t=function(e,t){let r=function(e,t){let r=(0,tj.iY)(e),n=(0,tj.iY)(t.contentTopic),i=function(e){if(e)return(0,tj.hL)(e.valueOf())}(t.timestamp),s=(0,tj.zo)([r,t.payload,n,t.meta,i].filter(tw.$K));return(0,iz.J)(s)}(e,t),n=(0,tj.Md)(r);return n}(this.pubsubTopic,e);if(this.receivedMessagesHashStr.includes(t)){pS.info("Message already received, skipping");return}this.receivedMessagesHashStr.push(t);let{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);if(!n){pS.error("No subscription callback available for ",r);return}pS.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await p_(n,this.pubsubTopic,e)}handleResult(e,t){let r={failures:[],successes:[]};for(let n of e)if("rejected"===n.status)pS.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:tb.K1.GENERIC_FAIL});else{let e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}startKeepAlivePings(e){if(this.keepAliveTimer){pS.info("Recurring pings already set up.");return}this.keepAliveTimer=setInterval(()=>{let e=async()=>{try{pS.info("Recurring ping to peers."),await this.ping()}catch(e){pS.error("Stopping recurring pings due to failure",e),this.stopKeepAlivePings()}};e()},e)}stopKeepAlivePings(){if(!this.keepAliveTimer){pS.info("Already stopped recurring pings.");return}pS.info("Stopping recurring pings."),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null}}class pT extends pE{protocol;activeSubscriptions=new Map;constructor(e,t,r){super(new rt(async(e,t)=>{let r=this.getActiveSubscription(e);if(!r){pS.error(`No subscription locally registered for topic ${e}`);return}await r.processIncomingMessage(t)},t,r),e,{numPeersToUse:r?.numPeersToUse}),this.protocol=this.core,this.activeSubscriptions=new Map}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}async createSubscription(e){let t="string"==typeof e?e:tw.yf(e)?.[0];(0,tw.Qu)(t,this.protocol.pubsubTopics);let r=[];try{r=await this.protocol.getPeers()}catch(e){return pS.error("Error getting peers to initiate subscription: ",e),{error:tb.K1.GENERIC_FAIL,subscription:null}}if(0===r.length)return{error:tb.K1.NO_PEER_AVAILABLE,subscription:null};pS.info(`Creating filter subscription with ${r.length} peers: `,r.map(e=>e.id.toString()));let n=this.getActiveSubscription(t)??this.setActiveSubscription(t,new pI(t,r,this.protocol));return{error:null,subscription:n}}async subscribe(e,t,r=pA){let n=this.getUniquePubsubTopics(e);if(0===n.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(n.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");let{subscription:i,error:s}=await this.createSubscription(n[0]);if(s)throw Error(`Failed to create subscription: ${s}`);await i.subscribe(e,t,r);let o=Array.from((0,tw.p3)(Array.isArray(e)?e:[e]).keys());return async()=>{await i.unsubscribe(o)}}toSubscriptionIterator(e){return(0,tw.B2)(this,e)}getUniquePubsubTopics(e){if(!Array.isArray(e))return[e.pubsubTopic];if(0===e.length)return[];let t=new Set(e.map(e=>e.pubsubTopic));return[...t]}}async function p_(e,t,r){let{decoders:n,callback:i}=e,{contentTopic:s}=r;if(!s){pS.warn("Message has no content topic, skipping");return}try{let e=n.map(e=>e.fromProtoObj(t,r).then(e=>e||Promise.reject("Decoding failed"))),s=await Promise.any(e);await i(s)}catch(e){pS.error("Error decoding message",e)}}let pR=new tw.Yd("sdk:light-push");class pC extends pE{protocol;constructor(e,t,r){super(new ri(t,r),e,{numPeersToUse:r?.numPeersToUse}),this.protocol=this.core}async send(e,t,r){let n={autoRetry:!0,...r},i=[],s=[],{pubsubTopic:o}=e;try{(0,tw.Qu)(o,this.protocol.pubsubTopics)}catch(e){return pR.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:tb.K1.TOPIC_NOT_CONFIGURED}],successes:[]}}let a=await this.hasPeers(n);if(!a)return{successes:i,failures:[{error:tb.K1.NO_PEER_AVAILABLE}]};let l=this.connectedPeers.map(r=>this.protocol.send(e,t,r)),c=await Promise.allSettled(l);for(let e of c)if("fulfilled"===e.status){let{failure:t,success:r}=e.value;r&&i.push(r),t&&(t.peerId&&await this.renewPeer(t.peerId),s.push(t))}else pR.error("Failed to send message to peer",e.reason),s.push({error:tb.K1.GENERIC_FAIL});return{successes:i,failures:s}}}let pk=new tw.Yd("waku:store:protocol");class pB extends pE{protocol;constructor(e,t,r){super(new ru(t,r),e,{numPeersToUse:1}),this.protocol=this.core}async *queryGenerator(e,t){let{pubsubTopic:r,contentTopics:n,decodersAsMap:i}=this.validateDecodersAndPubsubTopic(e,t),s=this.constructOptions(r,n,t),o=(await this.protocol.getPeers({numPeers:this.numPeersToUse,maxBootstrapPeers:1}))[0];if(!o)throw Error("No peers available to query");let a=this.protocol.queryPerPage(s,i,o);for await(let e of a)yield e}async queryWithOrderedCallback(e,t,r){for await(let n of this.queryGenerator(e,r))if(await this.processMessages(n,t,r))break}async queryWithPromiseCallback(e,t,r){let n=!1;for await(let i of this.queryGenerator(e,r)){let e=i.map(async e=>{n||(n=!!await t(e))});if(await Promise.all(e),n)break}}createCursor(e){if(!e||!e.timestamp||!e.payload||!e.contentTopic)throw Error("Message is missing required fields");let t=(0,tj.iY)(e.contentTopic),r=(0,iz.J)((0,tj.zo)([t,e.payload])),n=BigInt(e.timestamp.getTime())*BigInt(1e6);return{digest:r,pubsubTopic:e.pubsubTopic,senderTime:n,receiverTime:n}}validateDecodersAndPubsubTopic(e,t){if(0===e.length)throw Error("No decoders provided");let r=Array.from(new Set(e.map(e=>e.pubsubTopic)));if(r.length>1)throw Error("API does not support querying multiple pubsub topics at once");let n=r[0];if((0,tw.Qu)(n,this.protocol.pubsubTopics),t?.cursor?.pubsubTopic&&t.cursor.pubsubTopic!==n)throw Error(`Cursor pubsub topic (${t?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${n})`);let i=new Map;e.forEach(e=>{if(i.has(e.contentTopic))throw Error("API does not support different decoder per content topic");i.set(e.contentTopic,e)});let s=e.filter(e=>e.pubsubTopic===n).map(e=>e.contentTopic);if(0===s.length)throw Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:s,decodersAsMap:i}}constructOptions(e,t,r={}){let n,i;r?.timeFilter&&(n=r.timeFilter.startTime,i=r.timeFilter.endTime),n||pk.warn("No start time provided"),i||pk.warn("No end time provided");let s=Object.assign({pubsubTopic:e,pageDirection:tb.$Q.BACKWARD,pageSize:10},r,{contentTopics:t,startTime:n,endTime:i});return s}async processMessages(e,t,r){let n=!1,i=await Promise.all(e),s=i.filter(tw.$K);return this.shouldReverseOrder(r)&&(s=s.reverse()),await Promise.all(s.map(async e=>{e&&!n&&(n=!!await t(e))})),n}shouldReverseOrder(e){return void 0===e?.pageDirection||e?.pageDirection===tb.$Q.BACKWARD}}async function pP(e={}){let t=await yu(e);return new px(e,t,{store:!0,lightpush:!0,filter:!0})}async function pD(e,t,r){if(!e.filter)throw Error("Filter protocol missing from Waku node");let{shardInfo:n}=e.libp2p.components.metadata;if(!n)throw Error("Shard info missing from Waku node.");let i=(0,tw.yf)(n),s=(0,tw.L3)(t);if(!i.includes(s))throw Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await rb(e,[tb.Uw.Filter]);let o=(0,tm.UF)(t,s);o&&(o=o??o);let{subscription:a,error:l}=await e.filter.createSubscription(s);if(l)throw Error("Failed to create subscription for content topic.");return{decoder:o,subscription:a}}async function pN(e,t,r){r.waku=r.waku??await pP({shardInfo:{contentTopics:[e]}});let{decoder:n,subscription:i}=await pD(r.waku,e,r.peer);return await i.subscribe(n,t),{subscription:i,waku:r.waku}}let pL=new tw.Yd("waku");class px{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r){var n,i;if(0==e.pubsubTopics.length)throw Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r={filter:!1,lightpush:!1,store:!1,relay:!1,...r};let s=e.pingKeepAlive||300,o=this.relay?e.relayKeepAlive||300:0,a=this.libp2p.peerId.toString();if(this.connectionManager=rk.create(a,t,{pingKeepAlive:s,relayKeepAlive:o},this.pubsubTopics,this.relay),r.store){let r=function(e,t={}){return r=>new pB(e,r,t)}(this.connectionManager,e);this.store=r(t)}if(r.lightpush){let r=function(e,t={}){return r=>new pC(e,r,t)}(this.connectionManager,e);this.lightPush=r(t)}if(r.filter){let r=(n=this.connectionManager,t=>new pT(n,t,e));this.filter=r(t)}if(r.relay){let e=(i=this.pubsubTopics,e=>new hf(e,i));this.relay=e(t)}pL.info("Waku node created",a,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){let r=t??[],n=sJ(e)?e:oG(e);void 0===t&&(this.relay&&r.push(tb.Uw.Relay),this.store&&r.push(tb.Uw.Store),this.filter&&r.push(tb.Uw.Filter),this.lightPush&&r.push(tb.Uw.LightPush));let i=[];return r.includes(tb.Uw.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(e=>i.push(e)):pL.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(tb.Uw.Store)&&(this.store?i.push(this.store.protocol.multicodec):pL.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(tb.Uw.LightPush)&&(this.lightPush?i.push(this.lightPush.protocol.multicodec):pL.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(tb.Uw.Filter)&&(this.filter?i.push(this.filter.protocol.multicodec):pL.error("Filter codec not included in dial codec: protocol not mounted locally")),pL.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,i)}async start(){await this.libp2p.start()}async stop(){this.connectionManager.stop(),await this.libp2p.stop()}async subscribeToContentTopic(e,t,r){return(await pN(e,r,{waku:this,peer:t})).subscription}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}getLocalMultiaddrWithID(){let e=this.libp2p.getMultiaddrs().find(e=>e.toString().match(/127\.0\.0\.1/));if(!e||""===e.toString())throw"Not listening on localhost";return e+"/p2p/"+this.libp2p.peerId.toString()}}let pO={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",DEPRECATED_DEFAULT_PUBSUB:"enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im"},pM="bootstrap",pU={store:2,filter:1,lightPush:1};var pF=r(4755),pK=r(6398);function pV(e){return new Uint8Array(pK.keccak256.arrayBuffer(e))}function pH(e,t,r){try{let n=pF.Pc.fromCompact(e.slice(0,64));return pF.T(n,t,r)}catch{return!1}}let p$="Invalid record id";function pq(e){let t=e.reduce((e,t)=>e+2+t.bytes.length,0),r=new Uint8Array(t),n=new DataView(r.buffer),i=0;return e.forEach(e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(i,e.bytes.length),i+=2,r.set(e.bytes,i),i+=e.bytes.length}),r}class pz extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){let e=this.get("id");if(!e)throw Error("id not found.");return(0,tj.Md)(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(p$)}get rs(){let e=this.get("rs");if(e)return(0,tw.Ix)(e)}get rsv(){let e=this.get("rsv");if(e)return(0,tw.Ix)(e)}get ip(){return pG(this,"ip","ip4")}set ip(e){pW(this,"ip","ip4",e)}get tcp(){return pj(this,"tcp","tcp")}set tcp(e){pY(this,"tcp","tcp",e)}get udp(){return pj(this,"udp","udp")}set udp(e){pY(this,"udp","udp",e)}get ip6(){return pG(this,"ip6","ip6")}set ip6(e){pW(this,"ip6","ip6",e)}get tcp6(){return pj(this,"tcp6","tcp")}set tcp6(e){pY(this,"tcp6","tcp",e)}get udp6(){return pj(this,"udp6","udp")}set udp6(e){pY(this,"udp6","udp",e)}get multiaddrs(){let e=this.get("multiaddrs");if(e)return function(e){let t=[],r=0;for(;r<e.length;){let n=new DataView(e.buffer,r,2),i=n.getUint16(0);r+=2;let s=e.slice(r,r+i);r+=i,t.push(oG(s))}return t}(e)}set multiaddrs(e){pQ(this,"multiaddrs",e,pq)}get waku2(){let e=this.get("waku2");if(e)return function(e){let t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){pQ(this,"waku2",e,e=>{let t;return new Uint8Array([(t=0,e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t)])})}}function pG(e,t,r){let n=e.get(t);if(n)return oC(r,n)}function pj(e,t,r){let n=e.get(t);if(n)return Number(oC(r,n))}function pW(e,t,r,n){pQ(e,t,n,ok.bind({},r))}function pY(e,t,r,n){pW(e,t,r,n?.toString(10))}function pQ(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function pX(e,t){return pF.Xx(pV(t),e,{der:!1})}let pJ=new tw.Yd("enr");(eR=to||(to={})).TCP="tcp",eR.UDP="udp",(eC=ta||(ta={})).TCP4="tcp4",eC.UDP4="udp4",eC.TCP6="tcp6",eC.UDP6="udp6";class pZ extends pz{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){let n=new pZ(e,t,r);try{let e=n.publicKey;e&&(n.peerId=await function(e){let t=new ci.secp256k1.Secp256k1PublicKey(e);return oe(t.bytes,void 0)}(e))}catch(e){pJ.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){let t=pF.E9.fromHex(e),r=t.toRawBytes(!1);return(0,tj.ci)(pV(r.slice(1)))}(this.publicKey):void 0;throw Error(p$)}getLocationMultiaddr=(function e(t,r){let n;switch(r){case"udp":return e(t,"udp4")||e(t,"udp6");case"tcp":return e(t,"tcp4")||e(t,"tcp6")}let i=r.endsWith("6"),s=t.get(i?"ip6":"ip");if(!s)return;let o=r.slice(0,3);switch(o){case"udp":n=i?t.get("udp6"):t.get("udp");break;case"tcp":n=i?t.get("tcp6"):t.get("tcp");break;default:return}if(n){var a,l;return a=i?"ip6":"ip4",l=n,oG("/"+a+"/"+oC(a,s)).encapsulate(oG("/"+o+"/"+oC(o,l)))}}).bind({},this);get shardInfo(){return this.rs&&this.rsv&&pJ.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){let t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");let r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){let e=[];for(let t of Object.values(ta)){let r=this.getLocationMultiaddr(t);r&&e.push(r)}let t=this.multiaddrs??[];return e.concat(t).map(e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e)}get peerInfo(){let e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){let t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){let e=this.peerId;return this.multiaddrs.map(t=>t.encapsulate(`/p2p/${e.toString()}`))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(p$);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return pH(t,pV(e),this.publicKey)}async sign(e,t){if("v4"===this.id)this.signature=await pX(t,e);else throw Error(p$);return this.signature}}let p0=!1,p1=!1,p2={debug:1,default:2,info:2,warning:3,error:4,off:5},p3=2,p4=null,p6=function(){try{let e=[];if(["NFD","NFC","NFKD","NFKC"].forEach(t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}}),e.length)throw Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw Error("broken implementation")}catch(e){return e.message}return null}();(ek=tl||(tl={})).DEBUG="DEBUG",ek.INFO="INFO",ek.WARNING="WARNING",ek.ERROR="ERROR",ek.OFF="OFF",(eB=tc||(tc={})).UNKNOWN_ERROR="UNKNOWN_ERROR",eB.NOT_IMPLEMENTED="NOT_IMPLEMENTED",eB.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",eB.NETWORK_ERROR="NETWORK_ERROR",eB.SERVER_ERROR="SERVER_ERROR",eB.TIMEOUT="TIMEOUT",eB.BUFFER_OVERRUN="BUFFER_OVERRUN",eB.NUMERIC_FAULT="NUMERIC_FAULT",eB.MISSING_NEW="MISSING_NEW",eB.INVALID_ARGUMENT="INVALID_ARGUMENT",eB.MISSING_ARGUMENT="MISSING_ARGUMENT",eB.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",eB.CALL_EXCEPTION="CALL_EXCEPTION",eB.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",eB.NONCE_EXPIRED="NONCE_EXPIRED",eB.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",eB.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",eB.TRANSACTION_REPLACED="TRANSACTION_REPLACED",eB.ACTION_REJECTED="ACTION_REJECTED";let p5="0123456789abcdef";class p8{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){let r=e.toLowerCase();null==p2[r]&&this.throwArgumentError("invalid log level name","logLevel",e),p3>p2[r]||console.log.apply(console,t)}debug(...e){this._log(p8.levels.DEBUG,e)}info(...e){this._log(p8.levels.INFO,e)}warn(...e){this._log(p8.levels.WARNING,e)}makeError(e,t,r){if(p1)return this.makeError("censored error",t,{});t||(t=p8.errors.UNKNOWN_ERROR),r||(r={});let n=[];Object.keys(r).forEach(e=>{let t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=p5[t[e]>>4]+p5[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);let i=e,s="";switch(t){case tc.NUMERIC_FAULT:{s="NUMERIC_FAULT";let t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case tc.CALL_EXCEPTION:case tc.INSUFFICIENT_FUNDS:case tc.MISSING_NEW:case tc.NONCE_EXPIRED:case tc.REPLACEMENT_UNDERPRICED:case tc.TRANSACTION_REPLACED:case tc.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");let o=Error(e);return o.reason=i,o.code=t,Object.keys(r).forEach(function(e){o[e]=r[e]}),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,p8.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),p6&&this.throwError("platform missing String.prototype.normalize",p8.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:p6})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,p8.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,p8.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,p8.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,p8.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||null==e)&&this.throwError("missing new",p8.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",p8.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||null==e)&&this.throwError("missing new",p8.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return p4||(p4=new p8("logger/5.7.0")),p4}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",p8.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),p0){if(!e)return;this.globalLogger().throwError("error censorship permanent",p8.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}p1=!!e,p0=!!t}static setLogLevel(e){let t=p2[e.toLowerCase()];if(null==t){p8.globalLogger().warn("invalid log level - "+e);return}p3=t}static from(e){return new p8(e)}}p8.errors=tc,p8.levels=tl;let p9=new p8("bytes/5.7.0");function p7(e){return!!e.toHexString}function fe(e){return e.slice||(e.slice=function(){let t=Array.prototype.slice.call(arguments);return fe(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function ft(e){return"number"==typeof e&&e==e&&e%1==0}function fr(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e||!ft(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){let r=e[t];if(!ft(r)||r<0||r>=256)return!1}return!0}function fn(e,t){if(t||(t={}),"number"==typeof e){p9.checkSafeUint53(e,"invalid arrayify value");let t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),fe(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),p7(e)&&(e=e.toHexString()),fi(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":p9.throwArgumentError("hex data is odd-length","value",e));let n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return fe(new Uint8Array(n))}return fr(e)?fe(new Uint8Array(e)):p9.throwArgumentError("invalid arrayify value","value",e)}function fi(e,t){return"string"==typeof e&&!!e.match(/^0x[0-9A-Fa-f]*$/)&&(!t||e.length===2+2*t)}let fs="0123456789abcdef";function fo(e,t){if(t||(t={}),"number"==typeof e){p9.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=fs[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),p7(e))return e.toHexString();if(fi(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":p9.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(fr(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=fs[(240&n)>>4]+fs[15&n]}return t}return p9.throwArgumentError("invalid hexlify value","value",e)}let fa=new p8("rlp/5.7.0");function fl(e){let t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function fc(e,t,r){let n=0;for(let i=0;i<r;i++)n=256*n+e[t+i];return n}function fu(e,t,r,n){let i=[];for(;r<t+1+n;){let s=fh(e,r);i.push(s.result),(r+=s.consumed)>t+1+n&&fa.throwError("child data too short",p8.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:i}}function fh(e,t){if(0===e.length&&fa.throwError("data too short",p8.errors.BUFFER_OVERRUN,{}),e[t]>=248){let r=e[t]-247;t+1+r>e.length&&fa.throwError("data short segment too short",p8.errors.BUFFER_OVERRUN,{});let n=fc(e,t+1,r);return t+1+r+n>e.length&&fa.throwError("data long segment too short",p8.errors.BUFFER_OVERRUN,{}),fu(e,t,t+1+r,r+n)}if(e[t]>=192){let r=e[t]-192;return t+1+r>e.length&&fa.throwError("data array too short",p8.errors.BUFFER_OVERRUN,{}),fu(e,t,t+1,r)}if(e[t]>=184){let r=e[t]-183;t+1+r>e.length&&fa.throwError("data array too short",p8.errors.BUFFER_OVERRUN,{});let n=fc(e,t+1,r);t+1+r+n>e.length&&fa.throwError("data array too short",p8.errors.BUFFER_OVERRUN,{});let i=fo(e.slice(t+1+r,t+1+r+n));return{consumed:1+r+n,result:i}}if(e[t]>=128){let r=e[t]-128;t+1+r>e.length&&fa.throwError("data too short",p8.errors.BUFFER_OVERRUN,{});let n=fo(e.slice(t+1,t+1+r));return{consumed:1+r,result:n}}return{consumed:1,result:fo(e[t])}}let fd=new tw.Yd("enr:decoder");class fp{static fromString(e){if(!e.startsWith(pZ.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${pZ.RECORD_PREFIX}'`);return fp.fromRLP((0,i2.m)(e.slice(4),"base64url"))}static fromRLP(e){let t=(function(e){let t=fn(e),r=fh(t,0);return r.consumed!==t.length&&fa.throwArgumentError("invalid rlp data","data",e),r.result})(e).map(tj.nr);return ff(t)}}async function ff(e){let{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");let[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),i={};for(let e=0;e<n.length;e+=2)try{i[(0,tj.Md)(n[e])]=n[e+1]}catch(t){fd.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}let s=r.length?BigInt("0x"+(0,tj.ci)(r)):BigInt(0),o=await pZ.create(i,s,t);return function(e,t,r,n){let i=(0,tj.nr)(fo(function e(t){if(Array.isArray(t)){let r=[];if(t.forEach(function(t){r=r.concat(e(t))}),r.length<=55)return r.unshift(192+r.length),r;let n=fl(r.length);return n.unshift(247+n.length),n.concat(r)}fi(t)&&!(t.length%2)||fr(t)||fa.throwArgumentError("RLP object must be BytesLike","object",t);let r=Array.prototype.slice.call(fn(t));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;let n=fl(r.length);return n.unshift(183+n.length),n.concat(r)}([e,...t])));if(!r.verify(i,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}let fg=/^(\d{1,3}\.){3,3}\d{1,3}$/,fy=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,fm={name:"v4",size:4,isFormat:e=>fg.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);let n=e.length,i=0;for(let s=0;s<n;){let n=e.charCodeAt(s++);46===n?(t[r++]=i,i=0):i=10*i+(n-48)}return t[r]=i,t},decode:(e,t)=>(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},fb={name:"v6",size:16,isFormat:e=>e.length>0&&fy.test(e),encode(e,t,r){let n=(r=~~r)+16,i=-1,s=0,o=0,a=!0,l=!1;t=t||new Uint8Array(r+16);for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);58===u?(a?-1!==i?(r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2):r<n&&(i=r):(!0===l?(r<n&&(t[r]=o),r++):(r<n&&(t[r]=s>>8),r<n-1&&(t[r+1]=255&s),r+=2),s=0,o=0),a=!0,l=!1):46===u?(r<n&&(t[r]=o),r++,o=0,s=0,a=!1,l=!0):(a=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,o=10*o+u),s=(s<<4)+u)}if(!1===a)!0===l?(r<n&&(t[r]=o),r++):(r<n&&(t[r]=s>>8),r<n-1&&(t[r+1]=255&s),r+=2);else if(0===i)r<n&&(t[r]=0),r<n-1&&(t[r+1]=0),r+=2;else if(-1!==i){r+=2;for(let e=Math.min(r-1,n-1);e>=i+2;e--)t[e]=t[e-2];t[i]=0,t[i+1]=0,i=r}if(i!==r&&-1!==i)for(r>n-2&&(r=n-2);n>i;)t[--n]=r<n&&r>i?t[--r]:0;else for(;r<n;)t[r++]=0;return t},decode(e,t){t=~~t;let r="";for(let n=0;n<16;n+=2)0!==n&&(r+=":"),r+=(e[t+n]<<8|e[t+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function fw(e){if(fm.isFormat(e))return fm.size;if(fb.isFormat(e))return fb.size;throw Error(`Invalid ip address: ${e}`)}function fv(e){switch(e){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+e}function fE(e){switch(e.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":case"*":return 255}return e.toUpperCase().startsWith("UNKNOWN_")?parseInt(e.slice(8)):0}function fS(e){switch(e){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+e}function fA(e){switch(e.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function fI(e){if("number"==typeof e)return e;if(!e)return -1;switch(e.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let t=e.match(/_(\d+)$/);return t?parseInt(t[1],10):-1}function fT(e){let t=0,r=e.length;for(let n=0;n<r;n+=1){let i=e.charCodeAt(n);if(i<=127)t+=1;else if(i<=2047)t+=2;else if((63488&i)!=55296)t+=3;else{let s=n+1;if(s===r||i>=56320)t+=3;else{let r=e.charCodeAt(s);(64512&r)!=56320?t+=3:(n=s,t+=4)}}}return t}function f_(e,t,r){let n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(fT(e)+r));let i=r;for(let r=0;r<n;r+=1){let s=e.charCodeAt(r);if(s<=127)t[i++]=s;else if(s<=2047)t[i++]=192|(1984&s)>>6,t[i++]=128|63&s;else if((63488&s)!=55296)t[i++]=224|(61440&s)>>12,t[i++]=128|(4032&s)>>6,t[i++]=128|63&s;else{let o=r+1;if(o===n||s>=56320)t[i++]=239,t[i++]=191,t[i++]=189;else{let n=e.charCodeAt(o);(64512&n)!=56320?(t[i++]=239,t[i++]=191,t[i++]=189):(r=o,s=65536|(1023&s)<<10|1023&n,t[i++]=240|(1835008&s)>>18,t[i++]=128|(258048&s)>>12,t[i++]=128|(4032&s)>>6,t[i++]=128|63&s)}}}return f_.bytes=i-r,t}function fR(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let i=t;i<r;){let t;let r=e[i++];if(r<=128)t=r;else if(r>191&&r<224)t=(31&r)<<6|63&e[i++];else if(r>239&&r<365){t=((7&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536;let s=55296|t>>10&1023;n+=String.fromCharCode(s),t=56320|1023&t}else t=(15&r)<<12|(63&e[i++])<<6|63&e[i++];n+=String.fromCharCode(t)}return fR.bytes=r-t,n}f_.bytes=0,fR.bytes=0;let fC=e=>e instanceof Uint8Array;function fk(e){return"string"==typeof e?fT(e):e.byteLength}function fB(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):f_(e)}function fP(e,t,r){if("string"!=typeof t)throw Error("unknown input type");return f_(t,e,r),f_.bytes}let fD=(e,t)=>16777216*e[t]+65536*e[t+1]+256*e[t+2]+e[t+3],fN=(e,t)=>e[t]<<8|e[t+1],fL=(e,t,r)=>(t=+t,e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,r+4),fx=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function fO(e,t,r,n,i){return(r<0&&(n-=r,r=0),n<0&&(n=0),i<0)?new Uint8Array(0):r>=t.length||n>=i?0:function(e,t,r,n,i){i-n>t.length-r&&(i=n+t.length-r);let s=i-n,o=e.length-n;return s>o&&(s=o),(0!==n||i<e.length)&&(e=new Uint8Array(e.buffer,e.byteOffset+n,s)),t.set(e,r),s}(e,t,r,n,i)}function fM({bytes:e=0,encode:t,decode:r,encodingLength:n}){return t.bytes=e,r.bytes=e,{encode:t,decode:r,encodingLength:n||(()=>e)}}let fU=fM({encode(e,t,r){t||(t=new Uint8Array(fU.encodingLength(e))),r||(r=0);let n=r,i=e.replace(/^\.|\.$/gm,"");if(i.length){let e=i.split(".");for(let n=0;n<e.length;n++){let i=fP(t,e[n],r+1);t[r]=i,r+=i+1}}return t[r++]=0,fU.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=[],n=t,i=0,s=0,o=!1;for(;;){if(t>=e.length)throw Error("Cannot decode name (buffer overflow)");let a=e[t++];if(s+=o?0:1,0===a)break;if((192&a)==0){if(t+a>e.length)throw Error("Cannot decode name (buffer overflow)");if((i+=a+1)>254)throw Error("Cannot decode name (name too long)");r.push(fR(e,t,t+a)),t+=a,s+=o?0:a}else if((192&a)==192){if(t+1>e.length)throw Error("Cannot decode name (buffer overflow)");let r=fN(e,t-1)-49152;if(r>=n)throw Error("Cannot decode name (bad pointer)");t=r,n=r,s+=o?0:1,o=!0}else throw Error("Cannot decode name (bad label)")}return fU.decode.bytes=s,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:fk(e.replace(/^\.|\.$/gm,""))+2}),fF=fM({encode(e,t,r){t||(t=new Uint8Array(fF.encodingLength(e))),r||(r=0);let n=fP(t,e,r+1);return t[r]=n,fF.encode.bytes=n+1,t},decode(e,t){t||(t=0);let r=e[t],n=fR(e,t+1,t+1+r);return fF.decode.bytes=r+1,n},encodingLength:e=>fk(e)+1}),fK=fM({bytes:12,encode(e,t,r){t||(t=new Uint8Array(fK.encodingLength(e))),r||(r=0);let n=32767&(e.flags||0),i="response"===e.type?32768:0;return fx(t,e.id||0,r),fx(t,n|i,r+2),fx(t,e.questions.length,r+4),fx(t,e.answers.length,r+6),fx(t,e.authorities.length,r+8),fx(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw Error("Header must be 12 bytes");let r=fN(e,t+2);return{id:fN(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:(r>>15&1)==1,opcode:function(e){switch(e){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+e}(r>>11&15),flag_aa:(r>>10&1)==1,flag_tc:(r>>9&1)==1,flag_rd:(r>>8&1)==1,flag_ra:(r>>7&1)==1,flag_z:(r>>6&1)==1,flag_ad:(r>>5&1)==1,flag_cd:(r>>4&1)==1,rcode:function(e){switch(e){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+e}(15&r),questions:Array(fN(e,t+4)),answers:Array(fN(e,t+6)),authorities:Array(fN(e,t+8)),additionals:Array(fN(e,t+10))}},encodingLength:()=>12}),fV=fM({encode(e,t,r){t||(t=new Uint8Array(fV.encodingLength(e))),r||(r=0);let n=e.length;return fx(t,n,r),fO(e,t,r+2,0,n),fV.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=fN(e,t),n=e.slice(t+2,t+2+r);return fV.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),fH=fM({encode:(e,t,r)=>(t||(t=new Uint8Array(fH.encodingLength(e))),r||(r=0),fU.encode(e,t,r+2),fx(t,fU.encode.bytes,r),fH.encode.bytes=fU.encode.bytes+2,t),decode(e,t){t||(t=0);let r=fN(e,t),n=fU.decode(e,t+2);return fH.decode.bytes=r+2,n},encodingLength:e=>fU.encodingLength(e)+2}),f$=fM({encode(e,t,r){t||(t=new Uint8Array(f$.encodingLength(e))),r||(r=0);let n=r;return r+=2,fU.encode(e.mname,t,r),r+=fU.encode.bytes,fU.encode(e.rname,t,r),r+=fU.encode.bytes,fL(t,e.serial||0,r),r+=4,fL(t,e.refresh||0,r),r+=4,fL(t,e.retry||0,r),r+=4,fL(t,e.expire||0,r),r+=4,fL(t,e.minimum||0,r),r+=4,fx(t,r-n-2,n),f$.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mname=fU.decode(e,t),t+=fU.decode.bytes,n.rname=fU.decode(e,t),t+=fU.decode.bytes,n.serial=fD(e,t),t+=4,n.refresh=fD(e,t),t+=4,n.retry=fD(e,t),t+=4,n.expire=fD(e,t),t+=4,n.minimum=fD(e,t),t+=4,f$.decode.bytes=t-r,n},encodingLength:e=>22+fU.encodingLength(e.mname)+fU.encodingLength(e.rname)}),fq=fM({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++)if("string"==typeof e[t]&&(e[t]=fB(e[t])),!fC(e[t]))throw Error("Must be a Buffer");t||(t=new Uint8Array(fq.encodingLength(e))),r||(r=0);let n=r;return r+=2,e.forEach(function(e){t[r++]=e.length,fO(e,t,r,0,e.length),r+=e.length}),fx(t,r-n-2,n),fq.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=fN(e,t);t+=2;let i=[];for(;n>0;){let r=e[t++];if(--n<r)throw Error("Buffer overflow");i.push(e.slice(t,t+r)),t+=r,n-=r}return fq.decode.bytes=t-r,i},encodingLength(e){Array.isArray(e)||(e=[e]);let t=2;return e.forEach(function(e){"string"==typeof e?t+=fk(e)+1:t+=e.length+1}),t}}),fz=fM({encode(e,t,r){t||(t=new Uint8Array(fz.encodingLength(e))),r||(r=0),"string"==typeof e&&(e=fB(e)),e||(e=new Uint8Array(0));let n=r;r+=2;let i=e.length;return fO(e,t,r,0,i),r+=i,fx(t,r-n-2,n),fz.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=fN(e,t);t+=2;let i=e.slice(t,t+n);return t+=n,fz.decode.bytes=t-r,i},encodingLength:e=>e?(fC(e)?e.length:fk(e))+2:2}),fG=fM({encode(e,t,r){t||(t=new Uint8Array(fG.encodingLength(e))),r||(r=0);let n=r;return r+=2,fF.encode(e.cpu,t,r),r+=fF.encode.bytes,fF.encode(e.os,t,r),r+=fF.encode.bytes,fx(t,r-n-2,n),fG.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.cpu=fF.decode(e,t),t+=fF.decode.bytes,n.os=fF.decode(e,t),t+=fF.decode.bytes,fG.decode.bytes=t-r,n},encodingLength:e=>fF.encodingLength(e.cpu)+fF.encodingLength(e.os)+2}),fj=fM({encode:(e,t,r)=>(t||(t=new Uint8Array(fj.encodingLength(e))),r||(r=0),fU.encode(e,t,r+2),fx(t,fU.encode.bytes,r),fj.encode.bytes=fU.encode.bytes+2,t),decode(e,t){t||(t=0);let r=fU.decode(e,t+2);return fj.decode.bytes=fU.decode.bytes+2,r},encodingLength:e=>fU.encodingLength(e)+2}),fW=fM({encode(e,t,r){t||(t=new Uint8Array(fW.encodingLength(e))),r||(r=0),fx(t,e.priority||0,r+2),fx(t,e.weight||0,r+4),fx(t,e.port||0,r+6),fU.encode(e.target,t,r+8);let n=fU.encode.bytes+6;return fx(t,n,r),fW.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=fN(e,t),n={};return n.priority=fN(e,t+2),n.weight=fN(e,t+4),n.port=fN(e,t+6),n.target=fU.decode(e,t+8),fW.decode.bytes=r+2,n},encodingLength:e=>8+fU.encodingLength(e.target)}),fY=fM({encode(e,t,r){let n=fY.encodingLength(e);return t||(t=new Uint8Array(fY.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=fY.ISSUER_CRITICAL),fx(t,n-2,r),t[r+=2]=e.flags||0,r+=1,fF.encode(e.tag,t,r),r+=fF.encode.bytes,fP(t,e.value,r),r+=fk(e.value),fY.encode.bytes=n,t},decode(e,t){t||(t=0);let r=fN(e,t);t+=2;let n=t,i={};return i.flags=e[t],t+=1,i.tag=fF.decode(e,t),t+=fF.decode.bytes,i.value=fR(e,t,n+r),i.issuerCritical=!!(i.flags&fY.ISSUER_CRITICAL),fY.decode.bytes=r+2,i},encodingLength:e=>fF.encodingLength(e.tag)+fF.encodingLength(e.value)+2});fY.ISSUER_CRITICAL=128;let fQ=fM({encode(e,t,r){t||(t=new Uint8Array(fQ.encodingLength(e))),r||(r=0);let n=r;return r+=2,fx(t,e.preference||0,r),r+=2,fU.encode(e.exchange,t,r),r+=fU.encode.bytes,fx(t,r-n-2,n),fQ.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.preference=fN(e,t),t+=2,n.exchange=fU.decode(e,t),t+=fU.decode.bytes,fQ.decode.bytes=t-r,n},encodingLength:e=>4+fU.encodingLength(e.exchange)}),fX=fM({encode:(e,t,r)=>(t||(t=new Uint8Array(fX.encodingLength(e))),r||(r=0),fx(t,4,r),r+=2,fm.encode(e,t,r),t),decode(e,t){t||(t=0),t+=2;let r=fm.decode(e,t);return r},bytes:6}),fJ=fM({encode:(e,t,r)=>(t||(t=new Uint8Array(fJ.encodingLength(e))),r||(r=0),fx(t,16,r),r+=2,fb.encode(e,t,r),fJ.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;let r=fb.decode(e,t);return fJ.decode.bytes=18,r},bytes:18}),fZ=e=>new Uint8Array(e),f0=fM({encode(e,t,r){t||(t=new Uint8Array(f0.encodingLength(e))),r||(r=0);let n=r,i=fI(e.code);if(fx(t,i,r),r+=2,e.data)fx(t,e.data.length,r),r+=2,fO(e.data,t,r),r+=e.data.length;else switch(i){case 8:{let n=e.sourcePrefixLength||0,i=e.family||(fw(e.ip)===fm.size?1:2),s=function(e,t,r){r=~~r;let n=fw(e);return("function"==typeof t&&(t=t(r+n)),n===fm.size)?fm.encode(e,t,r):fb.encode(e,t,r)}(e.ip,fZ),o=Math.ceil(n/8);fx(t,o+4,r),r+=2,fx(t,i,r),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,fO(s,t,r,0,o),r+=o}break;case 11:e.timeout?(fx(t,2,r),r+=2,fx(t,e.timeout,r)):fx(t,0,r),r+=2;break;case 12:{let n=e.length||0;fx(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{let n=2*e.tags.length;for(let i of(fx(t,n,r),r+=2,e.tags))fx(t,i,r),r+=2}break;default:throw Error(`Unknown roption code: ${e.code}`)}return f0.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={};r.code=fN(e,t),r.type=function(e){switch(e){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return e<0?null:`OPTION_${e}`}(r.code),t+=2;let n=fN(e,t);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=fN(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{let i=new Uint8Array(1===r.family?4:16);fO(e,i,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===fm.size)return fm.decode(e,t,r);if(r===fb.size)return fb.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${fm.size} for v4 or ${fb.size} for v6.`)}(i)}break;case 11:n>0&&(r.timeout=fN(e,t),t+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(fN(e,t)),t+=2}return f0.decode.bytes=n+4,r},encodingLength(e){if(e.data)return e.data.length+4;let t=fI(e.code);switch(t){case 8:{let t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8}case 11:return"number"==typeof e.timeout?6:4;case 12:return e.length+4;case 14:return 4+2*e.tags.length}throw Error(`Unknown roption code: ${e.code}`)}}),f1=fM({encode(e,t,r){t||(t=new Uint8Array(f1.encodingLength(e))),r||(r=0);let n=r,i=gc(e,f0);return fx(t,i,r),r=gu(e,f0,t,r+2),f1.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=[],i=fN(e,t);t+=2;let s=0;for(;i>0;)n[s++]=f0.decode(e,t),t+=f0.decode.bytes,i-=f0.decode.bytes;return f1.decode.bytes=t-r,n},encodingLength:e=>2+gc(e||[],f0)}),f2=fM({encode(e,t,r){t||(t=new Uint8Array(f2.encodingLength(e))),r||(r=0);let n=r,i=e.key;if(!fC(i))throw Error("Key must be a Buffer");return r+=2,fx(t,e.flags,r),t[r+=2]=f2.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,r+=1,fO(i,t,r,0,i.length),r+=i.length,f2.encode.bytes=r-n,fx(t,f2.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=fN(e,t);if(t+=2,n.flags=fN(e,t),e[t+=2]!==f2.PROTOCOL_DNSSEC)throw Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+i+2),t+=n.key.length,f2.decode.bytes=t-r,n},encodingLength:e=>6+fk(e.key)});f2.PROTOCOL_DNSSEC=3,f2.ZONE_KEY=128,f2.SECURE_ENTRYPOINT=32768;let f3=fM({encode(e,t,r){t||(t=new Uint8Array(f3.encodingLength(e))),r||(r=0);let n=r,i=e.signature;if(!fC(i))throw Error("Signature must be a Buffer");return r+=2,fx(t,fE(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,fL(t,e.originalTTL,r),r+=4,fL(t,e.expiration,r),r+=4,fL(t,e.inception,r),r+=4,fx(t,e.keyTag,r),r+=2,fU.encode(e.signersName,t,r),r+=fU.encode.bytes,fO(i,t,r,0,i.length),r+=i.length,f3.encode.bytes=r-n,fx(t,f3.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=fN(e,t);return t+=2,n.typeCovered=fv(fN(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=fD(e,t),t+=4,n.expiration=fD(e,t),t+=4,n.inception=fD(e,t),t+=4,n.keyTag=fN(e,t),t+=2,n.signersName=fU.decode(e,t),t+=fU.decode.bytes,n.signature=e.slice(t,r+i+2),t+=n.signature.length,f3.decode.bytes=t-r,n},encodingLength:e=>20+fU.encodingLength(e.signersName)+fk(e.signature)}),f4=fM({encode(e,t,r){t||(t=new Uint8Array(f4.encodingLength(e))),r||(r=0);let n=r;return r+=2,fU.encode(e.mbox||".",t,r),r+=fU.encode.bytes,fU.encode(e.txt||".",t,r),r+=fU.encode.bytes,f4.encode.bytes=r-n,fx(t,f4.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mbox=fU.decode(e,t)||".",t+=fU.decode.bytes,n.txt=fU.decode(e,t)||".",t+=fU.decode.bytes,f4.decode.bytes=t-r,n},encodingLength:e=>2+fU.encodingLength(e.mbox||".")+fU.encodingLength(e.txt||".")}),f6=fM({encode(e,t,r){t||(t=new Uint8Array(f6.encodingLength(e))),r||(r=0);let n=r,i=[];for(let t=0;t<e.length;t++){let r=fE(e[t]);void 0===i[r>>8]&&(i[r>>8]=[]),i[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e<i.length;e++)if(void 0!==i[e]){let n=fB(i[e]);t[r]=e,t[r+=1]=n.length,r+=1,fO(n,t,r,0,n.length),r+=n.length}return f6.encode.bytes=r-n,t},decode(e,t,r){t||(t=0);let n=t,i=[];for(;t-n<r;){let r=e[t];t+=1;let n=e[t];t+=1;for(let s=0;s<n;s++){let n=e[t+s];for(let e=0;e<8;e++)if(n&1<<7-e){let t=fv(r<<8|s<<3|e);i.push(t)}}t+=n}return f6.decode.bytes=t-n,i},encodingLength(e){let t=[];for(let r=0;r<e.length;r++){let n=fE(e[r]);t[n>>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e<t.length;e++)void 0!==t[e]&&(r+=2+Math.ceil((t[e]+1)/8));return r}}),f5=fM({encode(e,t,r){t||(t=new Uint8Array(f5.encodingLength(e))),r||(r=0);let n=r;return r+=2,fU.encode(e.nextDomain,t,r),r+=fU.encode.bytes,f6.encode(e.rrtypes,t,r),r+=f6.encode.bytes,f5.encode.bytes=r-n,fx(t,f5.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=fN(e,t);return t+=2,n.nextDomain=fU.decode(e,t),t+=fU.decode.bytes,n.rrtypes=f6.decode(e,t,i-(t-r)),t+=f6.decode.bytes,f5.decode.bytes=t-r,n},encodingLength:e=>2+fU.encodingLength(e.nextDomain)+f6.encodingLength(e.rrtypes)}),f8=fM({encode(e,t,r){t||(t=new Uint8Array(f8.encodingLength(e))),r||(r=0);let n=r,i=e.salt;if(!fC(i))throw Error("salt must be a Buffer");let s=e.nextDomain;if(!fC(s))throw Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,fx(t,e.iterations,r),t[r+=2]=i.length,r+=1,fO(i,t,r,0,i.length),t[r+=i.length]=s.length,r+=1,fO(s,t,r,0,s.length),r+=s.length,f6.encode(e.rrtypes,t,r),r+=f6.encode.bytes,f8.encode.bytes=r-n,fx(t,f8.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=fN(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=fN(e,t),t+=2;let s=e[t];t+=1,n.salt=e.slice(t,t+s),t+=s;let o=e[t];return t+=1,n.nextDomain=e.slice(t,t+o),t+=o,n.rrtypes=f6.decode(e,t,i-(t-r)),t+=f6.decode.bytes,f8.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+f6.encodingLength(e.rrtypes)}),f9=fM({encode(e,t,r){t||(t=new Uint8Array(f9.encodingLength(e))),r||(r=0);let n=r,i=e.digest;if(!fC(i))throw Error("Digest must be a Buffer");return r+=2,fx(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,r+=1,fO(i,t,r,0,i.length),r+=i.length,f9.encode.bytes=r-n,fx(t,f9.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=fN(e,t);return t+=2,n.keyTag=fN(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+i+2),t+=n.digest.length,f9.decode.bytes=t-r,n},encodingLength:e=>6+fk(e.digest)});function f7(e){switch(e.toUpperCase()){case"A":return fX;case"PTR":case"CNAME":case"DNAME":return fj;case"TXT":return fq;case"NULL":return fz;case"AAAA":return fJ;case"SRV":return fW;case"HINFO":return fG;case"CAA":return fY;case"NS":return fH;case"SOA":return f$;case"MX":return fQ;case"OPT":return f1;case"DNSKEY":return f2;case"RRSIG":return f3;case"RP":return f4;case"NSEC":return f5;case"NSEC3":return f8;case"DS":return f9}return fV}let ge=fM({encode(e,t,r){t||(t=new Uint8Array(ge.encodingLength(e))),r||(r=0);let n=r;if(fU.encode(e.name,t,r),r+=fU.encode.bytes,fx(t,fE(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw Error("OPT name must be root.");fx(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,fx(t,e.flags||0,r+6),r+=8,f1.encode(e.options||[],t,r),r+=f1.encode.bytes}else{let n=fA(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),fx(t,n,r+2),fL(t,e.ttl||0,r+4),r+=8;let i=f7(e.type);i.encode(e.data,t,r),r+=i.encode.bytes}return ge.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={},n=t;if(r.name=fU.decode(e,t),t+=fU.decode.bytes,r.type=fv(fN(e,t)),"OPT"===r.type)r.udpPayloadSize=fN(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=fN(e,t+6),r.flag_do=(r.flags>>15&1)==1,r.options=f1.decode(e,t+8),t+=8+f1.decode.bytes;else{let n=fN(e,t+2);r.ttl=fD(e,t+4),r.class=fS(-32769&n),r.flush=!!(32768&n);let i=f7(r.type);r.data=i.decode(e,t+8),t+=8+i.decode.bytes}return ge.decode.bytes=t-n,r},encodingLength(e){let t=null!==e.data&&void 0!==e.data?e.data:e.options;return fU.encodingLength(e.name)+8+f7(e.type).encodingLength(t)}}),gt=fM({encode(e,t,r){t||(t=new Uint8Array(gt.encodingLength(e))),r||(r=0);let n=r;return fU.encode(e.name,t,r),r+=fU.encode.bytes,fx(t,fE(e.type),r),r+=2,fx(t,fA(void 0===e.class?"IN":e.class),r),r+=2,gt.encode.bytes=r-n,e},decode(e,t){t||(t=0);let r=t,n={};n.name=fU.decode(e,t),t+=fU.decode.bytes,n.type=fv(fN(e,t)),t+=2,n.class=fS(fN(e,t)),t+=2;let i=!!(32768&n.class);return i&&(n.class&=-32769),gt.decode.bytes=t-r,n},encodingLength:e=>fU.encodingLength(e.name)+4}),gr={encode:function(e,t,r){let n=!t;n&&(t=new Uint8Array(gl(e))),r||(r=0);let i=r;return(e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),fK.encode(e,t,r),r+=fK.encode.bytes,r=gu(e.questions,gt,t,r),r=gu(e.answers,ge,t,r),r=gu(e.authorities,ge,t,r),r=gu(e.additionals,ge,t,r),gr.encode.bytes=r-i,n&&go.bytes!==t.length)?t.slice(0,go.bytes):t},decode:function(e,t){t||(t=0);let r=t,n=fK.decode(e,t);return t+=fK.decode.bytes,t=gh(n.questions,gt,e,t),t=gh(n.answers,ge,e,t),t=gh(n.authorities,ge,e,t),t=gh(n.additionals,ge,e,t),gr.decode.bytes=t-r,n},encodingLength:function(e){return fK.encodingLength(e)+gc(e.questions||[],gt)+gc(e.answers||[],ge)+gc(e.authorities||[],ge)+gc(e.additionals||[],ge)}};function gn(e,t){if(e.questions)throw Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}gr.encode.bytes=0,gr.decode.bytes=0;let gi={encode:function(e,t,r){return t=gr.encode(gn(e,"query"),t,r),gi.encode.bytes=gr.encode.bytes,t},decode:function(e,t){let r=gr.decode(e,t);return gi.decode.bytes=gr.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r}};gi.encode.bytes=0,gi.decode.bytes=0;let gs={encode:function(e,t,r){return t=gr.encode(gn(e,"response"),t,r),gs.encode.bytes=gr.encode.bytes,t},decode:function(e,t){let r=gr.decode(e,t);return gs.decode.bytes=gr.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r}};gs.encode.bytes=0,gs.decode.bytes=0;let go=gr.encode,ga=gr.decode,gl=gr.encodingLength;function gc(e,t){let r=0;for(let n=0;n<e.length;n++)r+=t.encodingLength(e[n]);return r}function gu(e,t,r,n){for(let i=0;i<e.length;i++)t.encode(e[i],r,n),n+=t.encode.bytes;return n}function gh(e,t,r,n){for(let i=0;i<e.length;i++)e[i]=t.decode(r,n),n+=t.decode.bytes;return n}function gd(e,t,r,n){if(64!==t.length)throw Error(`Charset needs to be 64 characters long! (${t.length})`);let i=new Uint8Array(256),s=new Uint8Array(64);for(let e=0;e<64;e+=1){let r=t.charCodeAt(e);if(r>255)throw Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==i[r])throw Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);i[r]=e,s[e]=r}let o=r.charCodeAt(0),a={name:e,encodingLength(e){let t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===o?e.charCodeAt(t-2)===o?r-2:r-1:r},encode(e,t,r){null==t&&(t=new Uint8Array(a.encodingLength(e))),null==r&&(r=0);let n=e.length;e.charCodeAt(n-1)===o&&(e.charCodeAt(n-2)===o?n-=2:n-=1);let s=n%4,l=n-s,c=r,u=0;for(;u<l;){let r=i[e.charCodeAt(u)]<<18|i[e.charCodeAt(u+1)]<<12|i[e.charCodeAt(u+2)]<<6|i[e.charCodeAt(u+3)];t[c++]=r>>16,t[c++]=r>>8,t[c++]=r,u+=4}if(3===s){let r=i[e.charCodeAt(u)]<<10|i[e.charCodeAt(u+1)]<<4|i[e.charCodeAt(u+2)]>>2;t[c++]=r>>8,t[c++]=r}else 2===s&&(t[c++]=i[e.charCodeAt(u)]<<2|i[e.charCodeAt(u+1)]>>4);return a.encode.bytes=c-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);let i=r-t,l=i%3,c=t+i-l,u=[];for(let r=t;r<c;r+=3){let t=e[r]<<16|e[r+1]<<8|e[r+2];u.push(s[t>>18&63],s[t>>12&63],s[t>>6&63],s[63&t])}if(2===l){let t=(e[r-2]<<8)+e[r-1];u.push(s[t>>10],s[t>>4&63],s[t<<2&63]),1===n&&u.push(o)}else if(1===l){let t=e[r-1];u.push(s[t>>2],s[t<<4&63]),1===n&&u.push(o,o)}return a.decode.bytes=i,String.fromCharCode.apply(String,u)}};return a}gd("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);let gp=gd("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2),gf="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;gf||(gf=class extends Error{constructor(e="Request aborted."){super(e)}}),gf.prototype.name="AbortError",gf.prototype.code="ABORT_ERR";let gg="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class gy extends Error{constructor(e,t,r){super("status="+t+" while requesting "+e+" ["+r+"]"),this.uri=e,this.status=t,this.method=r}toJSON(){return{code:this.code,uri:this.uri,status:this.status,method:this.method,endpoint:this.endpoint}}}gy.prototype.name="HTTPStatusError",gy.prototype.code="HTTP_STATUS";class gm extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:function(e){if("string"==typeof e)return{message:e};try{let t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}let t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}(this.cause)}}}gm.prototype.name="ResponseError",gm.prototype.code="RESPONSE_ERR";class gb extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}gb.prototype.name="TimeoutError",gb.prototype.code="ETIMEOUT";let gw=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,gv=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i,gE=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,gS=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/ig,gA=/\[(((pk|name)=([^\]]+)))\]/ig;function gI(e,t){t.lastIndex=0;let r={};for(;;){let n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class gT extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${g_.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}gT.prototype.name="InvalidProtocolError",gT.prototype.code="EPROTOCOL";let g_=["http:","https:","udp4:","udp6:"];class gR{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;let r="string"==typeof e.port?e.port=parseInt(e.port,10):e.port;if(null==r)this.port=t?"https:"===this.protocol?443:80:e.pk?443:53;else if("number"==typeof r||isNaN(r))this.port=r;else throw Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`)}toJSON(){return this.toString()}}class gC extends gR{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){let e=this.port!==(this.pk?443:53)?`:${this.port}`:"",t=this.pk?` [pk=${this.pk}]`:"",r=this.name?` [name=${this.name}]`:"";return`udp://${this.ipv4||`[${this.ipv6}]`}${e}${t}${r}`}}class gk extends gC{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class gB extends gC{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function gP(e){return gv.test(e)&&!gw.test(e)?`[${e}]`:e}class gD extends gR{constructor(e){if(super(Object.assign({protocol:"https:"},e),!0),!e.host&&(e.ipv4&&(e.host=e.ipv4),e.ipv6&&(e.host=`[${e.ipv6}]`)),!e.host||"string"!=typeof e.host)throw Error(`Invalid Endpoint: host "${e.path}" needs to be set: ${JSON.stringify(e)}`);if(this.host=e.host,this.path=e.path||"/dns-query",this.method=/^post$/i.test(e.method)?"POST":"GET",this.ipv4=e.ipv4,this.ipv6=e.ipv6,!this.ipv6){let e=gv.exec(this.host);e&&(this.ipv6=e[1])}!this.ipv4&&gw.test(this.host)&&(this.ipv4=this.host);let t=`${this.protocol}//${gP(this.host)}:${this.port}${this.path}`;try{this.url=new gg(t)}catch(e){throw Error(e.message+` [${t}]`)}}toString(){let e="https:"===this.protocol?"":"http://",t=this.port!==("https:"===this.protocol?443:80)?`:${this.port}`:"",r="GET"!==this.method?" [post]":"",n="/dns-query"===this.path?"":this.path,i=this.name?` [name=${this.name}]`:"",s=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",o=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${gP(this.host)}${t}${n}${r}${s}${o}${i}`}}function gN(e){let t;if("string"==typeof e)t=function(e){let t=gE.exec(e),r=t[2]||"https:",n=t[3],i=t[5],s=t[6],o=t[7];if("https:"===r||"http:"===r){let e=gI(o,gS);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:i,path:s,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){let t=gI(o,gA),s=/^\[(.*)\]$/.exec(n);if(s&&"udp4:"===r)throw Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!s&&"udp6:"===r)throw Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return s?new gB({protocol:"udp6:",ipv6:s[1],port:i,pk:t.pk,name:t.name}):new gk({protocol:"udp4:",ipv4:n,port:i,pk:t.pk,name:t.name})}throw new gT(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw Error(`Can not convert ${e} to an endpoint`);if(e instanceof gR)return e;t=e}(null===t.protocol||void 0===t.protocol)&&(t.protocol="https:");let r=t.protocol;if("udp4:"===r)return new gk(t);if("udp6:"===r)return new gB(t);if("https:"===r||"http:"===r)return new gD(t);throw new gT(r,JSON.stringify(t))}let gL="application/dns-message";function gx(){}async function gO(e,t,r,n){let i=t?t.localStoragePrefix+t.name:null;if(i)try{let e=JSON.parse(localStorage.getItem(i));if(e&&e.time>t.maxTime)return e}catch(e){}let{data:s}=await gM(e,"GET",null,r,n),o={time:Date.now(),data:JSON.parse(fR(s))};if(i)try{localStorage.setItem(i,JSON.stringify(o))}catch(e){o.time=null}return o}function gM(e,t,r,n,i){return new Promise((s,o)=>{let a=new gg(e);"GET"===t&&r&&(a.search="?dns="+gp.decode(r));let l=a.toString(),c=new XMLHttpRequest;c.open(t,l,!0),c.setRequestHeader("Accept",gL),"POST"===t&&c.setRequestHeader("Content-Type",gL),c.responseType="arraybuffer",c.timeout=n,c.ontimeout=function(){u(new gb(n));try{c.abort()}catch(e){}},c.onreadystatechange=function(){if(c.readyState>1&&200!==c.status&&0!==c.status){u(new gy(l,c.status,t));try{c.abort()}catch(e){}}},c.onerror=function(){u(200===c.status?Error("Inexplicable XHR Error"):new gy(l,c.status,t))},c.onload=function(){if(200!==c.status)u(new gy(l,c.status,t));else{let e;if("string"==typeof c.response)e=f_(c.response);else if(c.response instanceof Uint8Array)e=c.response;else if(Array.isArray(c.response)||c.response instanceof ArrayBuffer)e=new Uint8Array(c.response);else throw Error("Unprocessable response "+c.response);u(null,e)}},"POST"===t?c.send(r):c.send(),i&&i.addEventListener("abort",h);let u=function(e,t){u=gx,i&&i.removeEventListener("abort",h),e?s({error:e,response:c}):s({data:t,response:c})};function h(){u(new gf);try{c.abort()}catch(e){}}})}function gU(e){let t=null===e.time||void 0===e.time?Date.now():e.time,r=e.data.map(e=>(e.endpoint=gN(Object.assign({name:e.name},e.endpoint)),e)).filter(e=>e.cors||e.endpoint.cors),n=r.map(e=>e.endpoint);return{data:{resolvers:r,resolverByName:r.reduce((e,t)=>(e[t.name]=t,e),{}),endpoints:n,endpointByName:n.reduce((e,t)=>(e[t.name]=t,e),{})},time:t}}let gF=gU({data:[{name:"adfree.usableprivacy.net",endpoint:{protocol:"https:",host:"adfree.usableprivacy.net"},description:"Public updns DoH service with advertising, tracker and malware filters.\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0},{name:"adguard-dns-doh",endpoint:{protocol:"https:",host:"dns.adguard.com",ipv4:"94.140.15.15"},description:"Remove ads and protect your computer from malware (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-family-doh",endpoint:{protocol:"https:",host:"dns-family.adguard.com",ipv4:"94.140.15.16"},description:"Adguard DNS with safesearch and adult content blocking (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-unfiltered-doh",endpoint:{protocol:"https:",host:"dns-unfiltered.adguard.com",ipv4:"94.140.14.140"},description:"AdGuard public DNS servers without filters (over DoH)",country:"France",location:{lat:48.8582,long:2.3387}},{name:"ahadns-doh-chi",endpoint:{protocol:"https:",host:"doh.chi.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=chi",country:"United States",location:{lat:41.8483,long:-87.6517},filter:!0,cors:!0},{name:"ahadns-doh-in",endpoint:{protocol:"https:",host:"doh.in.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=in",country:"India",location:{lat:19.0748,long:72.8856},filter:!0,cors:!0},{name:"ahadns-doh-la",endpoint:{protocol:"https:",host:"doh.la.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=la",country:"United States",location:{lat:34.0549,long:-118.2578},filter:!0,cors:!0},{name:"ahadns-doh-nl",endpoint:{protocol:"https:",host:"doh.nl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=nl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"ahadns-doh-ny",endpoint:{protocol:"https:",host:"doh.ny.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=ny",country:"United States",location:{lat:40.7308,long:-73.9975},filter:!0,cors:!0},{name:"ahadns-doh-pl",endpoint:{protocol:"https:",host:"doh.pl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=pl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"alidns-doh",endpoint:{protocol:"https:",host:"dns.alidns.com",ipv4:"223.5.5.5",cors:!0},description:"A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud.\nWarning: GFW filtering rules are applied by that resolver.\nHomepage: https://alidns.com/",country:"China",location:{lat:34.7725,long:113.7266},filter:!0,log:!0,cors:!0},{name:"ams-ads-doh-nl",endpoint:{protocol:"https:",host:"dnsnl-noads.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.",country:"Romania",location:{lat:45.9968,long:24.997},filter:!0},{name:"ams-doh-nl",endpoint:{protocol:"https:",host:"dnsnl.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Romania",location:{lat:45.9968,long:24.997}},{name:"att",endpoint:{protocol:"https:",host:"dohtrial.att.net"},description:"AT&T test DoH server.",log:!0},{name:"bcn-ads-doh",endpoint:{protocol:"https:",host:"dnses-noads.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611},filter:!0},{name:"bcn-doh",endpoint:{protocol:"https:",host:"dnses.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611}},{name:"brahma-world",endpoint:{protocol:"https:",host:"dns.brahma.world"},description:"DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet.\nHosted in Stockholm, Sweden. (https://dns.brahma.world)",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"cisco-doh",endpoint:{protocol:"https:",host:"doh.opendns.com",ipv4:"146.112.41.2"},description:"Remove your DNS blind spot (DoH protocol)\nWarning: modifies your queries to include a copy of your network\naddress when forwarding them to a selection of companies and organizations.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0,log:!0},{name:"cloudflare",endpoint:{protocol:"https:",host:"dns.cloudflare.com",ipv4:"1.0.0.1",cors:!0},description:"Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1",country:"Australia",location:{lat:-33.494,long:143.2104},cors:!0},{name:"cloudflare-family",endpoint:{protocol:"https:",host:"family.cloudflare-dns.com",ipv4:"1.0.0.3",cors:!0},description:"Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"cloudflare-ipv6",endpoint:{protocol:"https:",host:"1dot1dot1dot1.cloudflare-dns.com",cors:!0},description:"Cloudflare DNS over IPv6 (anycast)",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"cloudflare-security",endpoint:{protocol:"https:",host:"security.cloudflare-dns.com",ipv4:"1.0.0.2",cors:!0},description:"Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"controld-block-malware",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p1"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p2"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad-social",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p3"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking and Social Networks domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-family-friendly",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/family"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-uncensored",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/uncensored"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS unblocks censored domains from various countries.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"controld-unfiltered",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p0"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"dns.digitale-gesellschaft.ch",endpoint:{protocol:"https:",host:"dns.digitale-gesellschaft.ch"},description:"Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\nHosted in Zurich, Switzerland.\nNon-logging, non-filtering, supports DNSSEC.",country:"Switzerland",location:{lat:47.1449,long:8.1551}},{name:"dns.ryan-palmer",endpoint:{protocol:"https:",host:"dns1.ryan-palmer.com"},description:"Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.",country:"United Kingdom",location:{lat:51.5164,long:-.093}},{name:"dns.sb",endpoint:{protocol:"https:",host:"doh.sb",ipv4:"185.222.222.222",cors:!0},description:"DNSSEC-enabled DoH server by https://xtom.com/\nhttps://dns.sb/doh/",country:"Unknown",location:{lat:47,long:8},cors:!0},{name:"dns.therifleman.name",endpoint:{protocol:"https:",host:"dns.therifleman.name"},description:"DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads.\nIP addresses are not logged, but queries are logged for 24 hours for debugging.\nReport issues, send suggestions @ joker349 at protonmail.com.\nAlso supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"dnsforfamily-doh",endpoint:{protocol:"https:",host:"dns-doh.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements.\nIt also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforfamily-doh-no-safe-search",endpoint:{protocol:"https:",host:"dns-doh-no-safe-search.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements.\nUnlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nWarning: This server is incompatible with anonymization.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforge.de",endpoint:{protocol:"https:",host:"dnsforge.de",cors:!0},description:"Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.",country:"Germany",location:{lat:52.2998,long:9.447},filter:!0,cors:!0},{name:"dnshome-doh",endpoint:{protocol:"https:",host:"dns.dnshome.de"},description:"https://www.dnshome.de/ public resolver in Germany"},{name:"dnspod-doh",endpoint:{protocol:"https:",host:"doh.pub",cors:!0},description:"A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en",filter:!0,log:!0,cors:!0},{name:"dnswarden-asia-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adblock"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-adultfilter-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adultfilter"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-uncensor-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/uncensored"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547}},{name:"dnswarden-eu-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.eu.dnswarden.com"},description:"Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Germany",location:{lat:50.1103,long:8.7147},filter:!0},{name:"dnswarden-us-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.us.dnswarden.com"},description:"Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"United States",location:{lat:32.7889,long:-96.8021},filter:!0},{name:"doh-ch-blahdns",endpoint:{protocol:"https:",host:"doh-ch.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"doh-cleanbrowsing-adult",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/adult-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It does\nnot block proxy or VPNs, nor mixed-content sites. Sites like Reddit\nare allowed. Google and Bing are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-family",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/family-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It also\nblocks proxy and VPN domains that are used to bypass the filters.\nMixed content sites (like Reddit) are also blocked. Google, Bing and\nYoutube are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-security",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/security-filter/",cors:!0},description:"Block access to phishing, malware and malicious domains. It does not block adult content.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-crypto-sx",endpoint:{protocol:"https:",host:"doh.crypto.sx",cors:!0},description:"DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-crypto-sx-ipv6",endpoint:{protocol:"https:",host:"doh-ipv6.crypto.sx",cors:!0},description:"DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-de-blahdns",endpoint:{protocol:"https:",host:"doh-de.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0,cors:!0},{name:"doh-fi-blahdns",endpoint:{protocol:"https:",host:"doh-fi.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0,cors:!0},{name:"doh-ibksturm",endpoint:{protocol:"https:",host:"ibksturm.synology.me"},description:"DoH & DoT Server, No Logging, No Filters, DNSSEC\nRunning privately by ibksturm in Thurgau, Switzerland"},{name:"doh-jp-blahdns",endpoint:{protocol:"https:",host:"doh-jp.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/",country:"Japan",location:{lat:35.6882,long:139.7532},filter:!0,cors:!0},{name:"doh.ffmuc.net",endpoint:{protocol:"https:",host:"doh.ffmuc.net"},description:"An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\nhttps://ffmuc.net/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"doh.tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org"},description:"Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"google",endpoint:{protocol:"https:",host:"dns.google",ipv4:"8.8.8.8",cors:!0},description:"Google DNS (anycast)",country:"United States",location:{lat:37.751,long:-97.822},log:!0,cors:!0},{name:"hdns",endpoint:{protocol:"https:",host:"query.hdns.io",cors:!0},description:"HDNS is a public DNS resolver that supports Handshake domains.\nhttps://www.hdns.io",country:"United States",location:{lat:37.7771,long:-122.406},cors:!0},{name:"he",endpoint:{protocol:"https:",host:"ordns.he.net"},description:"Hurricane Electric DoH server (anycast)\nUnknown logging policy.",country:"United States",location:{lat:37.751,long:-97.822},log:!0},{name:"id-gmail-doh",endpoint:{protocol:"https:",host:"doh.tiar.app"},description:"Non-Logging DNS-over-HTTPS server located in Singapore.\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"iij",endpoint:{protocol:"https:",host:"public.dns.iij.jp"},description:"DoH server operated by Internet Initiative Japan in Tokyo.\nhttps://www.iij.ad.jp/",country:"Japan",location:{lat:35.69,long:139.69},log:!0},{name:"iqdns-doh",endpoint:{protocol:"https:",host:"a.passcloud.xyz"},description:'Non-logging DoH service runned by V2EX.com user johnsonwil.\nReturns "no such domain" for anti-Chinese government websites. Supports DNSSEC.\nFor more information: https://www.v2ex.com/t/785666',filter:!0},{name:"jp.tiar.app-doh",endpoint:{protocol:"https:",host:"jp.tiar.app"},description:"Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\nNo ECS, Support DNSSEC",country:"Japan",location:{lat:35.6882,long:139.7532}},{name:"jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org"},description:"DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\nCached via Cloudflare."},{name:"libredns",endpoint:{protocol:"https:",host:"doh.libredns.gr"},description:"DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\nhttps://libredns.gr/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"nextdns",endpoint:{protocol:"https:",host:"anycsast.dns.nextdns.io"},description:"NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nDNSSEC, Anycast, Non-logging, NoFilters\nhttps://www.nextdns.io/",country:"Netherlands",location:{lat:52.3891,long:4.6563}},{name:"nextdns-ultralow",endpoint:{protocol:"https:",host:"dns.nextdns.io",path:"/dnscrypt-proxy"},description:'NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nhttps://www.nextdns.io/\nTo select the server location, the "-ultralow" variant relies on bootstrap servers\ninstead of anycast.'},{name:"njalla-doh",endpoint:{protocol:"https:",host:"dns.njal.la",cors:!0},description:"Non-logging DoH server in Sweden operated by Njalla.\nhttps://dns.njal.la/",country:"Sweden",location:{lat:59.3247,long:18.056},cors:!0},{name:"odoh-cloudflare",endpoint:{protocol:"https:",host:"odoh.cloudflare-dns.com",cors:!0},description:"Cloudflare ODoH server.\nhttps://cloudflare.com",cors:!0},{name:"odoh-crypto-sx",endpoint:{protocol:"https:",host:"odoh.crypto.sx",cors:!0},description:"ODoH target server. Anycast, no logs.\nBackend hosted by Scaleway. Maintained by Frank Denis.",cors:!0},{name:"odoh-id-gmail",endpoint:{protocol:"https:",host:"doh.tiar.app",path:"/odoh"},description:"ODoH target server. Based in Singapore, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"odoh-jp.tiar.app",endpoint:{protocol:"https:",host:"jp.tiar.app",path:"/odoh"},description:"ODoH target server. no logs."},{name:"odoh-jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs."},{name:"odoh-resolver4.dns.openinternet.io",endpoint:{protocol:"https:",host:"resolver4.dns.openinternet.io"},description:"ODoH target server. no logs, no filter, DNSSEC.\nRunning on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States.\nUses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic\nin any way). Provided by https://openinternet.io"},{name:"odoh-tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"publicarray-au2-doh",endpoint:{protocol:"https:",host:"doh-2.seby.io",cors:!0},description:"DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\nMaintained by publicarray - https://dns.seby.io",country:"Australia",location:{lat:-33.8591,long:151.2002},cors:!0},{name:"puredns-doh",endpoint:{protocol:"https:",host:"puredns.org",ipv4:"146.190.6.13",cors:!0},description:"Public uncensored DNS resolver in Singapore - https://puredns.org\n** Only available in Indonesia and Singapore **",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"quad101",endpoint:{protocol:"https:",host:"dns.twnic.tw",cors:!0},description:"DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\nhttps://101.101.101.101/index_en.html",cors:!0},{name:"quad9-doh-ip4-port443-filter-ecs-pri",endpoint:{protocol:"https:",host:"dns11.quad9.net",ipv4:"149.112.112.11"},description:"Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-filter-pri",endpoint:{protocol:"https:",host:"dns.quad9.net",ipv4:"149.112.112.112"},description:"Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-nofilter-ecs-pri",endpoint:{protocol:"https:",host:"dns12.quad9.net",ipv4:"9.9.9.12"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip4-port443-nofilter-pri",endpoint:{protocol:"https:",host:"dns10.quad9.net",ipv4:"149.112.112.10"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip6-port5053-filter-pri",endpoint:{protocol:"https:",host:"dns9.quad9.net"},description:"Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"safesurfer-doh",endpoint:{protocol:"https:",host:"doh.safesurfer.io"},description:"Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more.\nFree to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing\nusage, data never sold - https://safesurfer.io",filter:!0,log:!0},{name:"sth-ads-doh-se",endpoint:{protocol:"https:",host:"dnsse-noads.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332},filter:!0},{name:"sth-doh-se",endpoint:{protocol:"https:",host:"dnsse.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332}},{name:"switch",endpoint:{protocol:"https:",host:"dns.switch.ch"},description:"Public DoH service provided by SWITCH in Switzerland\nhttps://www.switch.ch\nProvides protection against malware, but does not block ads.",filter:!0},{name:"uncensoreddns-dk-ipv4",endpoint:{protocol:"https:",host:"unicast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"uncensoreddns-ipv4",endpoint:{protocol:"https:",host:"anycast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"v.dnscrypt.uk-doh-ipv4",endpoint:{protocol:"https:",host:"v.dnscrypt.uk"},description:"DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\nhttps://www.dnscrypt.uk",country:"United Kingdom",location:{lat:51.4964,long:-.1224}}],time:1654187067783}),gK=new gg("https://martinheidegger.github.io/dns-query/resolvers.json");function gV(e){return/^@/.test(e)}class gH{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:gK,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?gO(this.opts.updateURL,this.opts.persist?{name:"resolvers.json",localStoragePrefix:this.opts.localStoragePrefix,maxTime:Date.now()-this.opts.maxAge}:null,this.opts.timeout).then(e=>gU({data:e.data.resolvers,time:e.time})).catch(()=>t||gF):Promise.resolve(gF),this._dataP):this._dataP.then(e=>e.time<Date.now()-this.opts.maxAge?this._data(!0,e):e)}data(){return this._data(!1).then(e=>e.data)}endpoints(e){if(null==e)return this.data().then(e=>e.endpoints);if("doh"===e&&(e=gq),"dns"===e&&(e=gz),"function"==typeof e)return this.data().then(t=>t.endpoints.filter(e));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(gV))try{return Promise.resolve(e.map(gN))}catch(e){return Promise.reject(e)}return this.data().then(t=>e.map(e=>{if(gV(e)){let r=t.endpointByName[e.substring(1)];if(!r)throw Error(`Endpoint ${e} is not known.`);return r}return gN(e)}))}}let g$=new gH;function gq(e){return"https:"===e.protocol||"http:"===e.protocol}function gz(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}let gG=new tw.Yd("dns-over-https");class gj{endpoints;retries;static async create(e,t){let r=e??await g$.endpoints("doh");return new gj(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{var r,n,i,s;let o=await (r={question:{type:"TXT",name:e}},n={endpoints:this.endpoints,retries:this.retries},(n=Object.assign({retries:5,timeout:3e4},n),r.question)?(null!==(s=i=n.endpoints)&&"object"==typeof s&&"function"==typeof s.then?i:Promise.resolve(i)).then(e=>{if(!Array.isArray(e)||0===e.length)throw Error("No endpoints defined to lookup dns records.");return function e(t,r,n){var i,s,o,a,l;let c=1===t.length?t[0]:t[Math.floor(Math.random()*t.length)%t.length];return(i=n.timeout,(s=n.signal)&&s.aborted?Promise.reject(new gf):"udp4:"===c.protocol||"udp6:"===c.protocol?function(){throw Error('Only "doh" endpoints are supported in the browser')}(c,r,i,s):(o=c.url,a=c.method,l=go(Object.assign({flags:256},r)),gM(o,a,l,i,s)).then(function(e){let t=e.data,r=e.response,n=e.error;if(void 0===n){if(0===t.length)n=new gm("Empty.");else try{let e=ga(t);return e.response=r,e}catch(e){n=new gm("Invalid packet (cause="+e.message+")",e)}}throw Object.assign(n,{response:r})})).then(e=>(e.endpoint=c.toString(),e),i=>{if("AbortError"===i.name||0===n.retries)throw i.endpoint=c.toString(),i;return n.retries>0&&(n.retries-=1),e(t,r,n)})}(e.map(gN),function(e){let t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(r),n)}).then(e=>(e.question=e.questions[0],delete e.questions,e)):Promise.reject(Error("To request data you need to specify a .question!")));t=o.answers}catch(e){throw gG.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error(`Could not resolve ${e}`);let o=t.map(e=>e.data),a=[];return o.forEach(e=>{"string"==typeof e?a.push(e):Array.isArray(e)?e.forEach(e=>{"string"==typeof e?a.push(e):a.push((0,tj.Md)(e))}):a.push((0,tj.Md)(e))}),a}}var gW=r(7935);class gY{static RECORD_PREFIX=pZ.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);let r=gY.parseRootValues(e),n=gW.decode.asBytes(t),i=e.split(" sig")[0],s=(0,tj.iY)(i),o=(0,i2.m)(r.signature,"base64url").slice(0,64),a=pH(o,pV(s),new Uint8Array(n));if(!a)throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){let t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();let[r,n,i,s]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!i)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(i),signature:s}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);let t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();let[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}let gQ=new tw.Yd("discovery:fetch_nodes");async function gX(e,t,r){let n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},i=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0},o=0,a=[];for(;!gZ(n,s)&&o<i+t;){let e=await r();e&&function(e,t){if(!e.nodeId)return!1;for(let r of t)if(e.nodeId===r.nodeId)return!1;return!0}(e,a)&&(e.waku2&&g1(e.waku2,n,s)&&(g0(e.waku2,s),a.push(e)),gQ.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}return a}async function*gJ(e,t,r){let n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},i=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0},o=0,a=new Set;for(;!gZ(n,s)&&o<i+t;){let e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&g1(e.waku2,n,s)&&(g0(e.waku2,s),yield e),gQ.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}}function gZ(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function g0(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function g1(e,t,r){if(gZ(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";let n={relay:r.relay<t.relay,store:r.store<t.store,filter:r.filter<t.filter,lightPush:r.lightPush<t.lightPush};return n.relay&&e.relay||n.store&&e.store||n.filter&&e.filter||n.lightPush&&e.lightPush}let g2=new tw.Yd("discovery:dns");class g3{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await gj.create()),new g3(e)}async getPeers(e,t){let r=Math.floor(Math.random()*e.length),{publicKey:n,domain:i}=gY.parseTree(e[r]),s={domain:i,publicKey:n,visits:{}},o=await gX(t,this._errorTolerance,()=>this._search(i,s));return g2.info("retrieved peers: ",o.map(e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map(e=>e.toString())}))),o}constructor(e){this._DNSTreeCache={},this.dns=e}async *getNextPeer(e,t){let r=Math.floor(Math.random()*e.length),{publicKey:n,domain:i}=gY.parseTree(e[r]),s={domain:i,publicKey:n,visits:{}};for await(let e of gJ(t,this._errorTolerance,()=>this._search(i,s)))yield e}async _search(e,t){try{let r,n;let i=await this._getTXTRecord(e,t);t.visits[e]=!0;let s=i.startsWith(gY.ROOT_PREFIX)?gY.ROOT_PREFIX:i.startsWith(gY.BRANCH_PREFIX)?gY.BRANCH_PREFIX:i.startsWith(gY.RECORD_PREFIX)?gY.RECORD_PREFIX:"";try{switch(s){case gY.ROOT_PREFIX:return r=gY.parseAndVerifyRoot(i,t.publicKey),await this._search(r,t);case gY.BRANCH_PREFIX:return n=gY.parseBranch(i),r=function(e,t){let r;let n={};for(let[r,i]of e.entries())t.visits[i]&&(n[r]=!0);if(Object.keys(n).length===e.length)throw Error("Unresolvable circular path detected");do r=Math.floor(Math.random()*e.length);while(n[r]);return e[r]}(n,t),await this._search(r,t);case gY.RECORD_PREFIX:return fp.fromString(i);default:return null}}catch(t){return g2.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return g2.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];let r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");let i=n.join("");return this._DNSTreeCache[e]=i,i}}let g4=new tw.Yd("peer-discovery-dns");class g6 extends rI{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;let{enrUrls:r}=t;g4.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(g4.info("Starting peer discovery via dns"),this._started=!0,void 0===this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);let{wantedNodeCapabilityCount:t}=this._options,r=await g3.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(let e of this.nextPeer()){if(!this._started)return;let{peerInfo:t,shardInfo:r}=e;if(!t)continue;let n={[pM]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}},i=!1,s=await this._components.peerStore.has(t.id);if(s){let e=await this._components.peerStore.get(t.id),r=e.tags.has(pM);r||(i=!0,await this._components.peerStore.merge(t.id,{tags:n}))}else i=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:(0,tw.kL)(r)}}});i&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[of](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}class g5{proto;constructor(e){this.proto=e}static createRequest(e){let{numPeers:t}=e;return new g5({query:{numPeers:t},response:void 0})}encode(){return t0._G.Zj.encode(this.proto)}static decode(e){let t=t0._G.Zj.decode(e);return new g5(t)}get query(){return this.proto.query}get response(){return this.proto.response}}let g8="/vac/waku/peer-exchange/2.0.0-alpha1",g9=new tw.Yd("peer-exchange");class g7 extends tZ{constructor(e,t){super(g8,e,g9,t)}async query(e){let t;let{numPeers:r}=e,n=g5.createRequest({numPeers:BigInt(r)}),i=await this.peerStore.get(e.peerId);if(!i)return{peerInfos:null,error:tb.K1.NO_PEER_AVAILABLE};try{t=await this.getStream(i)}catch(e){return g9.error("Failed to get stream",e),{peerInfos:null,error:tb.K1.NO_STREAM_AVAILABLE}}let s=await tV([n.encode()],tP,t,tL,async e=>await tv(e));try{let e=new tC;s.forEach(t=>{e.append(t)});let{response:t}=g5.decode(e);if(!t)return g9.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:tb.K1.EMPTY_PAYLOAD};let r=await Promise.all(t.peerInfos.map(e=>e.enr).filter(tw.$K).map(async e=>({ENR:await fp.fromRLP(e)})));return{peerInfos:r,error:null}}catch(e){return g9.error("Failed to decode push reply",e),{peerInfos:null,error:tb.K1.DECODE_FAILED}}}}let ye=new tw.Yd("peer-exchange-discovery"),yt=tb.$G.PEER_EXCHANGE;class yr extends rI{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{let{protocols:t,peerId:r}=e.detail;!t.includes(g8)||this.queryingPeers.has(r.toString())||(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch(e=>ye.error(`Error querying peer ${e}`)))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new g7(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(ye.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(ye.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[of](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{let t=e.toString(),{queryInterval:r=1e4,maxRetries:n=3}=this.options;ye.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);let i=this.queryAttempts.get(t)??1;if(i>n){this.abortQueriesForPeer(t);return}setTimeout(()=>{this.queryAttempts.set(t,i+1),this.startRecurringQueries(e).catch(e=>{ye.error(`Error in startRecurringQueries: ${e}`)})},r*i)};async query(e){let{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return ye.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(let e of r){let{ENR:t}=e;if(!t){ye.warn("No ENR in peerInfo object, skipping");continue}let{peerId:r,peerInfo:n,shardInfo:i}=t;if(!r||!n)continue;let s=await this.components.peerStore.has(r);s||(await this.components.peerStore.save(r,{tags:{[yt]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...i&&{metadata:{shardInfo:(0,tw.kL)(i)}}}),ye.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){ye.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}let yn=new tw.Yd("peer-exchange-discovery"),yi=tb.$G.LOCAL;class ys extends rI{components;options;isStarted;peers=[];constructor(e,t){super(),this.components=e,this.options=t,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){if(!this.isStarted){for(let{id:e,address:t}of(yn.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers),this.peers)){let r=await hI({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[oG(t)],tags:{[this.options?.tagName??yi]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:[oG(t)]}})))}yn.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(yn.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{let{peerId:t,listenAddrs:r}=e.detail,n=(0,tw.Yl)(r),i=this.getPeersFromLocalStorage(),s=i.findIndex(e=>e.id===t.toString());s>=0?i[s].address=n.toString():i.push({id:t.toString(),address:n.toString()}),this.peers=i,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{let e=localStorage.getItem("waku:peers");if(!e)return[];let t=JSON.parse(e);return t.filter(yo)}catch(e){return yn.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){yn.error("Error saving peers to local storage:",e)}}}function yo(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}let ya={lightPush:1,filter:1,store:1},yl=new tw.Yd("sdk:create");async function yc(e,t,r,n){r?.hideWebSocketInfo||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));let i=e?{metadata:t=>new rD(e,t)}:{};return pv({connectionManager:{minConnections:1},transports:[function(e={}){return t=>new uM(t,e)}({filter:uO})],streamMuxers:[function(e={}){return t=>new um(t,e)}()],connectionEncryption:[function(e={}){return t=>new op(t,e)}()],...r,services:{identify:function(e={}){return t=>new c8(t,e)}({agentVersion:n??"js-waku"}),ping:function(e={}){return t=>new uv(t,e)}({maxInboundStreams:r?.pingMaxInboundStreams??10}),...i,...t?{pubsub:t}:{},...r?.services}})}async function yu(e){(function(e){if(e.pubsubTopics){yl.info("Using pubsubTopics array to bootstrap the node.");return}if(e.contentTopics){yl.info("Using contentTopics and default cluster ID (1) to bootstrap the node.");return}e.shardInfo&&yl.info("Using shardInfo parameters to bootstrap the node.")})(e),e.contentTopics&&(e.shardInfo={contentTopics:e.contentTopics});let t=e.shardInfo?(0,tw.Ao)(e.shardInfo):void 0;e.pubsubTopics=t?.pubsubTopics??e.pubsubTopics??[tb.nf];let r=e?.libp2p??{},n=r.peerDiscovery??[];if(e?.defaultBootstrap&&n.push(...function(e){let t=e.includes(tb.nf),r=t?[pO.DEPRECATED_DEFAULT_PUBSUB]:[pO.SANDBOX,pO.TEST],n=[function(e,t=pU){return r=>new g6(r,{enrUrls:e,wantedNodeCapabilityCount:t})}(r,ya),(e,t)=>new ys(e,t),t=>new yr(t,e)];return n}(e.pubsubTopics)),e?.bootstrapPeers){var i;n.push((i={list:e.bootstrapPeers},e=>new ag(e,i)))}r.peerDiscovery=n;let s=await yc(t?.shardInfo,function(e={}){return t=>{e={...e,msgIdFn:({data:e})=>(0,iz.J)(e),globalSignaturePolicy:eQ.StrictNoSign,fallbackToFloodsub:!1};let r=new ha(t,e);return r.multicodecs=hl,r}}(e),r,e?.userAgent);return s}},9710:function(e,t,r){"use strict";r.d(t,{Md:function(){return l},ci:function(){return a},hL:function(){return o},iY:function(){return c},nr:function(){return s},zo:function(){return u}});var n=r(2223),i=r(7519);function s(e){if("string"==typeof e){let t=e.replace(/^0x/i,"");return(0,n.m)(t.toLowerCase(),"base16")}return e}function o(e){let t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}let a=e=>(0,i.B)(e,"base16"),l=e=>(0,i.B)(e,"utf8"),c=e=>(0,n.m)(e,"utf8");function u(e,t){let r=t??e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(r),i=0;for(let t of e)n.set(t,i),i+=t.length;return n}},5758:function(e,t,r){"use strict";r.d(t,{I:function(){return n},k:function(){return i}});let n=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");let t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){let r=Math.floor(e/8)+2,i=7-e%8;t.getUint8(r)&1<<i&&n.push(e)}else{let r=t.getUint8(2);for(let i=0,s=3;i<r;i++,s+=2){if(s+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(s))}}return{clusterId:r,shards:n}},i=e=>{let{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,i=new ArrayBuffer(n),s=new DataView(i);if(s.setUint16(0,t),r.length>=64)for(let e of r){let t=Math.floor(e/8)+2,r=7-e%8;s.setUint8(t,s.getUint8(t)|1<<r)}else{s.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)s.setUint16(t,r[e])}return new Uint8Array(i)}},9527:function(e,t,r){"use strict";function n(e){return!!e}function i(e){let t=new Map;return e.forEach(e=>{let r=t.get(e.contentTopic);r||(t.set(e.contentTopic,[]),r=t.get(e.contentTopic)),r.push(e)}),t}async function s(e,t,r){let n;let i=r?.iteratorDelay??60,s=[];n=await e.subscribe(t,e=>{s.push(e)});let o=Number.isInteger(r?.timeoutMs),a=r?.timeoutMs??0,l=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-l>=a)return;await function(e){return new Promise(t=>{setTimeout(t,e)})}(i);let e=s.shift();if(!n&&0===s.length)return e;(e||!n)&&(yield e)}}(),async stop(){n&&(await n(),n=void 0)}}}async function o(e,t){let r=await e.toWire(t);return!!r&&a(r)}r.d(t,{Yd:function(){return T},L3:function(){return y},Ix:function(){return v.I},gw:function(){return E},IY:function(){return m},kL:function(){return v.k},Qu:function(){return f},Ao:function(){return b},Yl:function(){return S},p3:function(){return i},$K:function(){return n},eh:function(){return o},qc:function(){return a},Tf:function(){return p},IC:function(){return w},yf:function(){return d},B2:function(){return s}});let a=e=>e.length/1048576<=1;var l=r(9802),c=r(5867),u=r(9710);let h=e=>{if(void 0===e.shard)throw Error("Invalid shard");return`/waku/2/rs/${e.clusterId??c.eZ}/${e.shard}`},d=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map(t=>y(t,e.clusterId))));if("shards"in e){if(void 0===e.shards)throw Error("Invalid shard");return Array.from(new Set(e.shards.map(t=>`/waku/2/rs/${e.clusterId??c.eZ}/${t}`)))}if("application"in e&&"version"in e)return[y(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw Error("Missing required configuration in shard parameters")},p=e=>{let t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");let r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function f(e,t){if(!t.includes(e))throw Error(`Pubsub topic ${e} has not been configured on this instance. Configured topics are: ${t}. Please update your configuration by passing in the topic during Waku node instantiation.`)}function g(e,t=8){let{application:r,version:n}=function(e){let t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(isNaN(r=parseInt(t[1])))throw Error("Invalid generation field in content topic");if(r>0)throw Error("Generation greater than 0 is not supported")}let n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty");if(0==n[1].length)throw Error("Version field cannot be empty");if(0==n[2].length)throw Error("Topic name field cannot be empty");if(0==n[3].length)throw Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),i=(0,l.J)((0,u.zo)([(0,u.iY)(r),(0,u.iY)(n)])),s=new DataView(i.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(t))}function y(e,t=c.eZ,r=8){if(!e)throw Error("Content topic must be specified");let n=g(e,r);return`/waku/2/rs/${t}/${n}`}function m(e,t){return"string"==typeof t?t:t?.shard!==void 0?h(t):y(e,t?.clusterId??c.eZ)}let b=e=>{let t=e.clusterId??c.eZ,r="shards"in e?e.shards:[],n="contentTopics"in e?e.contentTopics:[],[i,s]="application"in e&&"version"in e?[e.application,e.version]:[void 0,void 0],o=r&&r.length>0,a=n&&n.length>0,l=i&&s;if(o)return{shardingParams:{clusterId:t,shards:r},shardInfo:{clusterId:t,shards:r},pubsubTopics:d({clusterId:t,shards:r})};if(a){let e=Array.from(new Set(n.map(e=>y(e,t)))),r=Array.from(new Set(n.map(e=>g(e))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(l){let e=y(`/${i}/${s}/default/default`,t);return{shardingParams:{clusterId:t,application:i,version:s},shardInfo:{clusterId:t,shards:[p(e).shard]},pubsubTopics:[e]}}throw Error("Missing minimum required configuration options for static sharding or autosharding.")};function w(e,t,r){let n=e.get(t);void 0===n&&(e.set(t,new Set),n=e.get(t)),n.add(r)}var v=r(5758);async function E(e){return new Promise(t=>setTimeout(t,e))}function S(e){let t=e.find(e=>e.toString().includes("ws")||e.toString().includes("wss"));if(!t)throw Error("No ws multiaddr found in the given addresses");return t}var A=r(4461);let I="waku";class T{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${I}:${e}:${t}`:`${I}:${e}`}constructor(e){this._info=A(T.createDebugNamespace("info",e)),this._warn=A(T.createDebugNamespace("warn",e)),this._error=A(T.createDebugNamespace("error",e))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){let r=this[e];r(...t)}}},7744:function(e,t,r){"use strict";r.d(t,{kU:function(){return h},Dp:function(){return u},ET:function(){return d}});var n=r(495),i=function(e,t){if(e.length>=255)throw TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(255!==r[o])throw TypeError(s+" is ambiguous");r[o]=i}var a=e.length,l=e.charAt(0),c=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[0]){for(var n=0,i=0;e[t]===l;)n++,t++;for(var s=(e.length-t)*c+1>>>0,o=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=s-1;(0!==u||h<i)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");i=h,t++}if(" "!==e[t]){for(var p=s-i;p!==s&&0===o[p];)p++;for(var f=new Uint8Array(n+(s-p)),g=n;p!==s;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,s=t.length;i!==s&&0===t[i];)i++,r++;for(var o=(s-i)*u+1>>>0,c=new Uint8Array(o);i!==s;){for(var h=t[i],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*c[p]>>>0,c[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,i++}for(var f=o-n;f!==o&&0===c[f];)f++;for(var g=l.repeat(r);f<o;++f)g+=e.charAt(c[f]);return g},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw Error(`Non-${t} character`)}}};class s{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class o{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return l(this,e)}}class a{decoders;constructor(e){this.decoders=e}or(e){return l(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function l(e,t){return new a({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class c{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new s(e,t,r),this.decoder=new o(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function u({name:e,prefix:t,encode:r,decode:n}){return new c(e,t,r,n)}function h({name:e,prefix:t,alphabet:r}){let{encode:s,decode:o}=i(r,e);return u({prefix:t,name:e,encode:s,decode:e=>(0,n.oQ)(o(e))})}function d({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return u({prefix:t,name:e,encode:e=>(function(e,t,r){let n="="===t[t.length-1],i=(1<<r)-1,s="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,s+=t[i&a>>o];if(0!==o&&(s+=t[i&a<<r-o]),n)for(;(s.length*r&7)!=0;)s+="=";return s})(e,n,r),decode:t=>(function(e,t,r,n){let i={};for(let e=0;e<t.length;++e)i[t[e]]=e;let s=e.length;for(;"="===e[s-1];)--s;let o=new Uint8Array(s*r/8|0),a=0,l=0,c=0;for(let t=0;t<s;++t){let s=i[e[t]];if(void 0===s)throw SyntaxError(`Non-${n} character`);l=l<<r|s,(a+=r)>=8&&(a-=8,o[c++]=255&l>>a)}if(a>=r||(255&l<<8-a)!=0)throw SyntaxError("Unexpected end of data");return o})(t,n,r,e)})}},8273:function(e,t,r){"use strict";r.r(t),r.d(t,{base32:function(){return i},base32hex:function(){return l},base32hexpad:function(){return u},base32hexpadupper:function(){return h},base32hexupper:function(){return c},base32pad:function(){return o},base32padupper:function(){return a},base32upper:function(){return s},base32z:function(){return d}});var n=r(7744);let i=(0,n.ET)({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),s=(0,n.ET)({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o=(0,n.ET)({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a=(0,n.ET)({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),l=(0,n.ET)({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),c=(0,n.ET)({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),u=(0,n.ET)({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),h=(0,n.ET)({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),d=(0,n.ET)({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})},9029:function(e,t,r){"use strict";r.r(t),r.d(t,{base58btc:function(){return i},base58flickr:function(){return s}});var n=r(7744);let i=(0,n.kU)({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),s=(0,n.kU)({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})},9678:function(e,t,r){"use strict";r.r(t),r.d(t,{base64:function(){return i},base64pad:function(){return s},base64url:function(){return o},base64urlpad:function(){return a}});var n=r(7744);let i=(0,n.ET)({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),s=(0,n.ET)({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),o=(0,n.ET)({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),a=(0,n.ET)({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})},4110:function(e,t,r){"use strict";r.d(t,{gh:function(){return V}});var n={};r.r(n),r.d(n,{base10:function(){return p}});var i={};r.r(i),r.d(i,{base16:function(){return f},base16upper:function(){return g}});var s={};r.r(s),r.d(s,{base2:function(){return y}});var o={};r.r(o),r.d(o,{base256emoji:function(){return v}});var a={};r.r(a),r.d(a,{base36:function(){return S},base36upper:function(){return A}});var l={};r.r(l),r.d(l,{base8:function(){return _}});var c={};r.r(c),r.d(c,{identity:function(){return C}});var u={};r.r(u),r.d(u,{code:function(){return D},decode:function(){return L},encode:function(){return N},name:function(){return P}});var h={};r.r(h),r.d(h,{code:function(){return O},decode:function(){return U},encode:function(){return M},name:function(){return x}});var d=r(7744);let p=(0,d.kU)({prefix:"9",name:"base10",alphabet:"0123456789"}),f=(0,d.ET)({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),g=(0,d.ET)({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),y=(0,d.ET)({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),m=Array.from("\uD83D\uDE80\uD83E\uDE90☄\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09☀\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02❤\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09☺\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E✌✨\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D❣\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33✋\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13⭐✅\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6✔\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90☹\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20☝\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B⚽\uD83E\uDD19☕\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81⚡\uD83C\uDF1E\uD83C\uDF88❌✊\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C✈\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74▶➡❓\uD83D\uDC8E\uD83D\uDCB8⬇\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A⚠\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37☎\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51❄\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42"),b=m.reduce((e,t,r)=>(e[r]=t,e),[]),w=m.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]),v=(0,d.Dp)({prefix:"\uD83D\uDE80",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=b[t],"")},decode:function(e){let t=[];for(let r of e){let e=w[r.codePointAt(0)];if(void 0===e)throw Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}});var E=r(8273);let S=(0,d.kU)({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),A=(0,d.kU)({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var I=r(9029),T=r(9678);let _=(0,d.ET)({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var R=r(495);let C=(0,d.Dp)({prefix:"\x00",name:"identity",encode:e=>(0,R.BB)(e),decode:e=>(0,R.mL)(e)}),k=new TextEncoder,B=new TextDecoder,P="json",D=512;function N(e){return k.encode(JSON.stringify(e))}function L(e){return JSON.parse(B.decode(e))}let x="raw",O=85;function M(e){return(0,R.oQ)(e)}function U(e){return(0,R.oQ)(e)}var F=r(9137),K=r(1818);r(8590),r(50),r(4511),r(9716);let V={...c,...s,...l,...n,...i,...E,...a,...I,...T,...o};({...K,...F})},495:function(e,t,r){"use strict";function n(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function i(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}function s(e){return new TextEncoder().encode(e)}function o(e){return new TextDecoder().decode(e)}r.d(t,{BB:function(){return o},fS:function(){return n},mL:function(){return s},oQ:function(){return i}}),new Uint8Array(0)},8590:function(e,t,r){"use strict";r.d(t,{k0:function(){return h}});var n=r(8273),i=r(9029),s=r(495),o=r(50),a=r(9716);function l(e,t){let{bytes:r,version:s}=e;return 0===s?function(e,t,r){let{prefix:n}=r;if(n!==i.base58btc.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=t.get(n);if(null!=s)return s;{let i=r.encode(e).slice(1);return t.set(n,i),i}}(r,u(e),t??i.base58btc.encoder):function(e,t,r){let{prefix:n}=r,i=t.get(n);if(null!=i)return i;{let i=r.encode(e);return t.set(n,i),i}}(r,u(e),t??n.base32.encoder)}let c=new WeakMap;function u(e){let t=c.get(e);if(null==t){let t=new Map;return c.set(e,t),t}return t}class h{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}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!==d)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==p)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return h.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,r=o.Ue(e,t);return h.createV1(this.code,r)}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 h.equals(this,e)}static equals(e,t){return null!=t&&e.code===t.code&&e.version===t.version&&o.fS(e.multihash,t.multihash)}toString(e){return l(this,e)}toJSON(){return{"/":l(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;if(e instanceof h)return e;if(null!=e["/"]&&e["/"]===e.bytes||e.asCID===e){let{version:t,code:r,multihash:n,bytes:i}=e;return new h(t,r,n,i??f(t,r,n.bytes))}if(!0!==e[g])return null;{let{version:t,multihash:r,code:n}=e,i=o.Jx(r);return h.create(t,n,i)}}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t===d)return new h(e,t,r,r.bytes);throw Error(`Version 0 CID must use dag-pb (code: ${d}) block encoding`);case 1:{let n=f(e,t,r.bytes);return new h(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return h.create(0,d,e)}static createV1(e,t){return h.create(1,e,t)}static decode(e){let[t,r]=h.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){let t=h.inspectBytes(e),r=t.size-t.multihashSize,n=(0,s.oQ)(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),a=new o.zZ(t.multihashCode,t.digestSize,i,n),l=0===t.version?h.createV0(a):h.createV1(t.codec,a);return[l,e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[r,n]=a.Jx(e.subarray(t));return t+=n,r},n=r(),i=d;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw RangeError(`Invalid CID version ${n}`);let s=t,o=r(),l=r(),c=t+l;return{version:n,codec:i,multihashCode:o,digestSize:l,multihashSize:c-s,size:c}}static parse(e,t){let[r,s]=function(e,t){switch(e[0]){case"Q":{let r=t??i.base58btc;return[i.base58btc.prefix,r.decode(`${i.base58btc.prefix}${e}`)]}case i.base58btc.prefix:{let r=t??i.base58btc;return[i.base58btc.prefix,r.decode(e)]}case n.base32.prefix:{let r=t??n.base32;return[n.base32.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),o=h.decode(s);if(0===o.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return u(o).set(r,e),o}}let d=112,p=18;function f(e,t,r){let n=a.P$(e),i=n+a.P$(t),s=new Uint8Array(i+r.byteLength);return a.mL(e,s,0),a.mL(t,s,n),s.set(r,i),s}let g=Symbol.for("@ipld/js-cid/CID")},50:function(e,t,r){"use strict";r.d(t,{Jx:function(){return o},Ue:function(){return s},fS:function(){return a},zZ:function(){return l}});var n=r(495),i=r(9716);function s(e,t){let r=t.byteLength,n=i.P$(e),s=n+i.P$(r),o=new Uint8Array(s+r);return i.mL(e,o,0),i.mL(r,o,n),o.set(t,s),new l(e,r,t,o)}function o(e){let t=(0,n.oQ)(e),[r,s]=i.Jx(t),[o,a]=i.Jx(t.subarray(s)),c=t.subarray(s+a);if(c.byteLength!==o)throw Error("Incorrect length");return new l(r,o,c,t)}function a(e,t){return e===t||e.code===t.code&&e.size===t.size&&t.bytes instanceof Uint8Array&&(0,n.fS)(e.bytes,t.bytes)}class l{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}},4511:function(e,t,r){"use strict";r.d(t,{D:function(){return i}});var n=r(50);function i({name:e,code:t,encode:r}){return new s(e,t,r)}class s{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?n.Ue(this.code,t):t.then(e=>n.Ue(this.code,e))}throw Error("Unknown type, must be binary type")}}},9137:function(e,t,r){"use strict";r.r(t),r.d(t,{identity:function(){return o}});var n=r(495),i=r(50);let s=n.oQ,o={code:0,name:"identity",encode:s,digest:function(e){return i.Ue(0,s(e))}}},1818:function(e,t,r){"use strict";r.r(t),r.d(t,{sha256:function(){return s},sha512:function(){return o}});var n=r(4511);function i(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}let s=(0,n.D)({name:"sha2-256",code:18,encode:i("SHA-256")}),o=(0,n.D)({name:"sha2-512",code:19,encode:i("SHA-512")})},9716:function(e,t,r){"use strict";r.d(t,{Jx:function(){return i},mL:function(){return s},P$:function(){return o}});var n={encode:function e(t,r,n){r=r||[];for(var i=n=n||0;t>=2147483648;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},decode:function e(t,r){var n,i=0,r=r||0,s=0,o=r,a=t.length;do{if(o>=a)throw e.bytes=0,RangeError("Could not decode varint");n=t[o++],i+=s<28?(127&n)<<s:(127&n)*Math.pow(2,s),s+=7}while(n>=128);return e.bytes=o-r,i},encodingLength:function(e){return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<0x7fffffffffffffff?9:10}};function i(e,t=0){let r=n.decode(e,t);return[r,n.decode.bytes]}function s(e,t,r=0){return n.encode(e,t,r),t}function o(e){return n.encodingLength(e)}},6995:function(e,t,r){"use strict";r.d(t,{sv:function(){return V},C6:function(){return E},LE:function(){return M},Ji:function(){return F},yw:function(){return K}});var n,i,s=r(7383);let o=new Float32Array([-0]),a=new Uint8Array(o.buffer);function l(e,t,r){o[0]=e,t[r]=a[0],t[r+1]=a[1],t[r+2]=a[2],t[r+3]=a[3]}let c=new Float64Array([-0]),u=new Uint8Array(c.buffer);function h(e,t,r){c[0]=e,t[r]=u[0],t[r+1]=u[1],t[r+2]=u[2],t[r+3]=u[3],t[r+4]=u[4],t[r+5]=u[5],t[r+6]=u[6],t[r+7]=u[7]}let d=BigInt(Number.MAX_SAFE_INTEGER),p=BigInt(Number.MIN_SAFE_INTEGER);class f{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){let e=~this.lo+1>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){let e=~this.lo+1>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<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=-(1&this.lo);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,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return g;if(e<d&&e>p)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>y&&(n=0n,++r>y&&(r=0n))),new f(Number(n),Number(r))}static fromNumber(e){if(0===e)return g;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new f(r,n)}static from(e){return"number"==typeof e?f.fromNumber(e):"bigint"==typeof e?f.fromBigInt(e):"string"==typeof e?f.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new f(e.low>>>0,e.high>>>0):g}}let g=new f(0,0);g.toBigInt=function(){return 0n},g.zzEncode=g.zzDecode=function(){return this},g.length=function(){return 1};let y=4294967296n;function m(e,t,r){let n,i;let s=r;for(let s=0;s<e.length;++s)(n=e.charCodeAt(s))<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:((64512&n)==55296&&(64512&(i=e.charCodeAt(s+1)))==56320?(n=65536+((1023&n)<<10)+(1023&i),++s,t[r++]=n>>18|240,t[r++]=n>>12&63|128):t[r++]=n>>12|224,t[r++]=n>>6&63|128),t[r++]=63&n|128);return r-s}function b(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function w(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class v{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=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,b(this,10);return e}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)|0}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw b(this,4);let e=w(this.buf,this.pos+=4);return e}sfixed32(){if(this.pos+4>this.len)throw b(this,4);let e=0|w(this.buf,this.pos+=4);return e}float(){var e,t;if(this.pos+4>this.len)throw b(this,4);let r=(e=this.buf,t=this.pos,a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],a[3]=e[t+3],o[0]);return this.pos+=4,r}double(){var e,t;if(this.pos+8>this.len)throw b(this,4);let r=(e=this.buf,t=this.pos,u[0]=e[t],u[1]=e[t+1],u[2]=e[t+2],u[3]=e[t+3],u[4]=e[t+4],u[5]=e[t+5],u[6]=e[t+6],u[7]=e[t+7],c[0]);return this.pos+=8,r}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw b(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return function(e,t,r){let n,i;let s=r-t;if(s<1)return"";let o=[],a=0;for(;t<r;)(i=e[t++])<128?o[a++]=i:i>191&&i<224?o[a++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[a++]=55296+(i>>10),o[a++]=56320+(1023&i)):o[a++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),a=0);return null!=n?(a>0&&n.push(String.fromCharCode.apply(String,o.slice(0,a))),n.join("")):String.fromCharCode.apply(String,o.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw b(this,e);this.pos+=e}else do if(this.pos>=this.len)throw b(this);while((128&this.buf[this.pos++])!=0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)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 f(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw b(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw b(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw b(this,8);let e=w(this.buf,this.pos+=4),t=w(this.buf,this.pos+=4);return new f(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=(0,s.CJ)(this.buf,this.pos);return this.pos+=(0,s.P$)(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 E(e,t,r){let n=new v(e instanceof Uint8Array?e:e.subarray());return t.decode(n,void 0,r)}var S=r(9425),A=r(2223);class I{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function T(){}class _{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}let R=function(e){let t;let r=(void 0)??8192,n=r>>>1,i=r;return function(e){if(e<1||e>n)return(0,S.E)(e);i+e>r&&(t=(0,S.E)(r),i=0);let s=t.subarray(i,i+=e);return(7&i)!=0&&(i=(7|i)+1),s}}();class C{len;head;tail;states;constructor(){this.len=0,this.head=new I(T,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new I(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new P((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(D,10,f.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=f.fromBigInt(e);return this._push(D,t.length(),t)}uint64Number(e){return this._push(s.lN,(0,s.P$)(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=f.fromBigInt(e).zzEncode();return this._push(D,t.length(),t)}sint64Number(e){let t=f.fromNumber(e).zzEncode();return this._push(D,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(k,1,e?1:0)}fixed32(e){return this._push(N,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=f.fromBigInt(e);return this._push(N,4,t.lo)._push(N,4,t.hi)}fixed64Number(e){let t=f.fromNumber(e);return this._push(N,4,t.lo)._push(N,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(l,4,e)}double(e){return this._push(h,8,e)}bytes(e){let t=e.length>>>0;return 0===t?this._push(k,1,0):this.uint32(t)._push(L,t,e)}string(e){let t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)(r=e.charCodeAt(n))<128?t+=1:r<2048?t+=2:(64512&r)==55296&&(64512&e.charCodeAt(n+1))==56320?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(m,t,e):this._push(k,1,0)}fork(){return this.states=new _(this),this.head=this.tail=new I(T,0,0),this.len=0,this}reset(){return null!=this.states?(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 I(T,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){var e;let t=this.head.next,r=(e=this.len,null!=globalThis.Buffer?(0,S.E)(e):R(e)),n=0;for(;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function k(e,t,r){t[r]=255&e}function B(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class P extends I{next;constructor(e,t){super(B,e,t),this.next=void 0}}function D(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function N(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function L(e,t,r){t.set(e,r)}function x(e,t,r){t.set(e,r)}function O(e,t,r){e.length<40?m(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set((0,A.m)(e),r)}function M(e,t){let r=new C;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function U(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function F(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return U("enum",i.VARINT,function(e,r){let n=t(e);r.int32(n)},function(e){let r=e.int32();return t(r)})}function K(e,t){return U("message",i.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(C.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(x,t,e),this},C.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(O,t,e),this}),(n=i||(i={}))[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32";class V extends Error{code;constructor(e,t,r){super(e,r),this.code=t}}},7383:function(e,t,r){"use strict";r.d(t,{CJ:function(){return o},Jx:function(){return l},P$:function(){return i},cv:function(){return a},lN:function(){return s}});var n=r(9425);function i(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<268435456)return 4;if(e<34359738368)return 5;if(e<4398046511104)return 6;if(e<562949953421312)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw RangeError("Could not encode varint");return 8}function s(e,t,r=0){switch(i(e)){case 8:t[r++]=255&e|128,e/=128;case 7:t[r++]=255&e|128,e/=128;case 6:t[r++]=255&e|128,e/=128;case 5:t[r++]=255&e|128,e/=128;case 4:t[r++]=255&e|128,e>>>=7;case 3:t[r++]=255&e|128,e>>>=7;case 2:t[r++]=255&e|128,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function o(e,t){let r,n=e[t];if(r=0+(127&n),n<128||(r+=(127&(n=e[t+1]))<<7,n<128)||(r+=(127&(n=e[t+2]))<<14,n<128)||(r+=(127&(n=e[t+3]))<<21,n<128)||(r+=(127&(n=e[t+4]))*268435456,n<128)||(r+=(127&(n=e[t+5]))*34359738368,n<128)||(r+=(127&(n=e[t+6]))*4398046511104,n<128)||(r+=(127&(n=e[t+7]))*562949953421312,n<128))return r;throw RangeError("Could not decode varint")}function a(e,t,r=0){return(null==t&&(t=(0,n.E)(i(e))),t instanceof Uint8Array)?s(e,t,r):function(e,t,r=0){switch(i(e)){case 8:t.set(r++,255&e|128),e/=128;case 7:t.set(r++,255&e|128),e/=128;case 6:t.set(r++,255&e|128),e/=128;case 5:t.set(r++,255&e|128),e/=128;case 4:t.set(r++,255&e|128),e>>>=7;case 3:t.set(r++,255&e|128),e>>>=7;case 2:t.set(r++,255&e|128),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function l(e,t=0){return e instanceof Uint8Array?o(e,t):function(e,t){let r,n=e.get(t);if(r=0+(127&n),n<128||(r+=(127&(n=e.get(t+1)))<<7,n<128)||(r+=(127&(n=e.get(t+2)))<<14,n<128)||(r+=(127&(n=e.get(t+3)))<<21,n<128)||(r+=(127&(n=e.get(t+4)))*268435456,n<128)||(r+=(127&(n=e.get(t+5)))*34359738368,n<128)||(r+=(127&(n=e.get(t+6)))*4398046511104,n<128)||(r+=(127&(n=e.get(t+7)))*562949953421312,n<128))return r;throw RangeError("Could not decode varint")}(e,t)}},9425:function(e,t,r){"use strict";function n(e=0){return new Uint8Array(e)}function i(e=0){return new Uint8Array(e)}r.d(t,{E:function(){return i},u:function(){return n}})},1363:function(e,t,r){"use strict";function n(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}r.d(t,{f:function(){return n}})},2223:function(e,t,r){"use strict";r.d(t,{m:function(){return i}});var n=r(4264);function i(e,t="utf8"){let r=n.Z[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}},7519:function(e,t,r){"use strict";r.d(t,{B:function(){return i}});var n=r(4264);function i(e,t="utf8"){let r=n.Z[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}},4264:function(e,t,r){"use strict";var n=r(4110),i=r(9425);function s(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}let o=s("utf8","u",e=>{let t=new TextDecoder("utf8");return"u"+t.decode(e)},e=>{let t=new TextEncoder;return t.encode(e.substring(1))}),a=s("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=(0,i.E)(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),l={utf8:o,"utf-8":o,hex:n.gh.base16,latin1:a,ascii:a,binary:a,...n.gh};t.Z=l}}]); |