mirror of
https://github.com/logos-messaging/lab.waku.org.git
synced 2026-03-31 16:43:49 +00:00
52 lines
901 KiB
JavaScript
52 lines
901 KiB
JavaScript
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[324],{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 m(e,t,r){let n=e[t];e[t]=e[r],e[r]=n}function y(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 E(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 v(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 R(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)m(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)m(this,t,t+3),m(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)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(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 y(this,e,t,r,!0)},a.prototype.lastIndexOf=function(e,t,r){return y(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||E(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||E(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||E(e,1,this.length),this[e]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(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||E(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readBigUInt64LE=F(function(e){D(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&P(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){D(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&P(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||E(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||E(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||E(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||E(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||E(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||E(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||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readBigInt64LE=F(function(e){D(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&P(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){D(e>>>=0,"offset");let t=this[e],r=this[e+7];(void 0===t||void 0===r)&&P(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||E(e,4,this.length),i.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),i.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),i.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(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;v(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;v(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||v(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||v(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||v(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||v(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||v(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);v(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);v(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||v(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||v(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||v(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||v(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||v(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 R(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return R(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 _={};function k(e,t,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 C(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 _.ERR_OUT_OF_RANGE("value",n,e)}D(i,"offset"),(void 0===n[i]||void 0===n[i+s])&&P(i,n.length-(s+1))}function D(e,t){if("number"!=typeof e)throw new _.ERR_INVALID_ARG_TYPE(t,"number",e)}function P(e,t,r){if(Math.floor(e)!==e)throw D(e,r),new _.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new _.ERR_BUFFER_OUT_OF_BOUNDS;throw new _.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}k("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),k("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),k("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=C(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=C(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?V:e}function V(){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,m,y,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},m={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,m=f>>3<<3;g<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++)],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 y=f-m;return 2===y?p+=String.fromCharCode(((r=a[e.charAt(g++)])<<3|(n=a[e.charAt(g++)])>>>2)&255):4===y?(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===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++)],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===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++)],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=m:(n.base32=m,s&&void 0!==(y=(function(){return m}).call(m,r,m,e))&&(e.exports=y))},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],m=[224,256,384,512],y=[128,256],b=["hex","buffer","arrayBuffer","array","digest"],w={128:168,256:136},E=a.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=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(!E(e)&&!v(e))throw Error(s);return[e,!1]},A=function(e){return 0===S(e)[0].length},I=function(e,t,r){return function(n){return new F(e,t,e).update(n)[r]()}},T=function(e,t,r){return function(n,i){return new F(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]()}},_=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},C=function(e,t){var r=I(e,t,"hex");return r.create=function(){return new F(e,t,e)},r.update=function(e){return r.create().update(e)},k(r,I,e,t)},B=[{name:"keccak",padding:[1,256,65536,16777216],bits:m,createMethod:C},{name:"sha3",padding:[6,1536,393216,100663296],bits:m,createMethod:C},{name:"shake",padding:[31,7936,2031616,520093696],bits:y,createMethod:function(e,t){var r=T(e,t,"hex");return r.create=function(r){return new F(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},k(r,T,e,t)}},{name:"cshake",padding:p,bits:y,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 F(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:y,createMethod:function(e,t){var r=w[e],n=_(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,_,e,t)}}],D={},P=[],N=0;N<B.length;++N)for(var L=B[N],x=L.bits,O=0;O<x.length;++O){var M=L.name+"_"+x[O];if(P.push(M),D[M]=L.createMethod(x[O],L.padding),"sha3"!==L.name){var U=L.name+x[O];P.push(U),D[U]=D[M]}}function F(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){F.call(this,e,t,r)}F.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];K(u),this.reset=!0}else this.start=r}return this},F.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},F.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},F.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},F.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];K(n)}},F.prototype.toString=F.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&&(K(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},F.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&&K(r)}return i&&(l[s]=r[s],e=e.slice(0,a)),e},F.prototype.buffer=F.prototype.arrayBuffer,F.prototype.digest=F.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&&K(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 F,V.prototype.finalize=function(){return this.encode(this.outputBits,!0),F.prototype.finalize.call(this)};var K=function(e){var t,r,n,i,s,o,a,l,c,u,h,d,p,f,m,y,b,w,E,v,S,A,I,T,R,_,k,C,B,D,P,N,L,x,O,M,U,F,V,K,H,q,$,z,G,j,W,Y,X,J,Q,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],m=e[1],j=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=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,q=e[40]<<18|e[41]>>>14,$=e[41]<<18|e[40]>>>14,x=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,D=e[33]<<13|e[32]>>>19,P=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,E=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,Q=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,R=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,V=e[27]<<25|e[26]>>>7,v=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,_=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,es=e[29]<<7|e[28]>>>25,eo=e[28]<<7|e[29]>>>25,K=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^~y&w,e[1]=m^~b&E,e[10]=T^~_&C,e[11]=R^~k&B,e[20]=x^~M&F,e[21]=O^~U&V,e[30]=z^~j&Y,e[31]=G^~W&X,e[40]=et^~en&es,e[41]=er^~ei&eo,e[2]=y^~w&v,e[3]=b^~E&S,e[12]=_^~C&D,e[13]=k^~B&P,e[22]=M^~F&K,e[23]=U^~V&H,e[32]=j^~Y&J,e[33]=W^~X&Q,e[42]=en^~es&ea,e[43]=ei^~eo&el,e[4]=w^~v&A,e[5]=E^~S&I,e[14]=C^~D&N,e[15]=B^~P&L,e[24]=F^~K&q,e[25]=V^~H&$,e[34]=Y^~J&Z,e[35]=X^~Q&ee,e[44]=es^~ea&ec,e[45]=eo^~el&eu,e[6]=v^~A&f,e[7]=S^~I&m,e[16]=D^~N&T,e[17]=P^~L&R,e[26]=K^~q&x,e[27]=H^~$&O,e[36]=J^~Z&z,e[37]=Q^~ee&G,e[46]=ea^~ec&et,e[47]=el^~eu&er,e[8]=A^~f&y,e[9]=I^~m&b,e[18]=N^~T&_,e[19]=L^~R&k,e[28]=q^~x&M,e[29]=$^~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(N=0;N<P.length;++N)a[P[N]]=D[P[N]];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))}},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,m=0,t=0;t<256;++t){h=(h=m^m<<1^m<<2^m<<3^m<<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 y=0;y<4;++y)o[y][g]=p,a[y][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=m=1:(g=r^e[e[e[r^c]]],m^=e[e[m]])}}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],m=i.slice(0);c=i.length;for(var u=0,y=c-4;u<c;u+=4,y-=4)if(0===u||u===c-4)m[u]=i[y],m[u+1]=i[y+3],m[u+2]=i[y+2],m[u+3]=i[y+1];else for(var b=0;b<4;++b)h=i[y+b],m[u+(3&-b)]=d[n[h>>>24]]^p[n[h>>>16&255]]^f[n[h>>>8&255]]^g[n[255&h]];i=m}return i}function p(e,t,r,s){var l,c,u,h,d,p,f,g,m,y,b,w,E=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],m=t[s?1:3]^e[3];for(var v=3,S=1;S<E;++S)y=l[p>>>24]^c[f>>>16&255]^u[g>>>8&255]^h[255&m]^e[++v],b=l[f>>>24]^c[g>>>16&255]^u[m>>>8&255]^h[255&p]^e[++v],w=l[g>>>24]^c[m>>>16&255]^u[p>>>8&255]^h[255&f]^e[++v],m=l[m>>>24]^c[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++v],p=y,f=b,g=w;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&m]^e[++v],r[s?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[m>>>8&255]<<8^d[255&p]^e[++v],r[2]=d[g>>>24]<<24^d[m>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++v],r[s?1:3]=d[m>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++v]}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 m=(32&h)==32;if(m){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 y=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 E=e(t,r,n+1,{strict:!0,decodeBitStrings:!0}),v=l-t.length();r-=v,p==i.Type.BITSTRING&&v++;var S=E.tagClass;v===f&&(S===i.Class.UNIVERSAL||S===i.Class.CONTEXT_SPECIFIC)&&(c=[E])}catch(e){}void 0===c&&(t.read=y,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,m,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],m=e.length()>8?3:1,y=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,E=0;E<m;E++){var v=e.getInt32(),S=e.getInt32();t=(v>>>4^S)&252645135,S^=t,v^=t<<4,t=(S>>>-16^v)&65535,v^=t,S^=t<<-16,t=(v>>>2^S)&858993459,S^=t,v^=t<<2,t=(S>>>-16^v)&65535,v^=t,S^=t<<-16,t=(v>>>1^S)&1431655765,S^=t,v^=t<<1,t=(S>>>8^v)&16711935,v^=t,S^=t<<8,t=(v>>>1^S)&1431655765,S^=t,v^=t<<1,t=v<<8|S>>>20&240,v=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var A=0;A<b.length;++A){b[A]?(v=v<<2|v>>>26,S=S<<2|S>>>26):(v=v<<1|v>>>27,S=S<<1|S>>>27),S&=-15;var I=r[(v&=-15)>>>28]|n[v>>>24&15]|i[v>>>20&15]|s[v>>>16&15]|o[v>>>12&15]|a[v>>>8&15]|l[v>>>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,y[w++]=I^t,y[w++]=T^t<<16}}return y}(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],m=t[1];p=(g>>>4^m)&252645135,m^=p,g^=p<<4,p=(g>>>16^m)&65535,m^=p,g^=p<<16,p=(m>>>2^g)&858993459,g^=p,m^=p<<2,p=(m>>>8^g)&16711935,g^=p,m^=p<<8,p=(g>>>1^m)&1431655765,m^=p,g^=p<<1,g=g<<1|g>>>31,m=m<<1|m>>>31;for(var y=0;y<f;y+=3){for(var b=i[y+1],w=i[y+2],E=i[y];E!=b;E+=w){var v=m^e[E],S=(m>>>4|m<<28)^e[E+1];p=g,g=m,m=p^(o[v>>>24&63]|l[v>>>16&63]|u[v>>>8&63]|d[63&v]|s[S>>>24&63]|a[S>>>16&63]|c[S>>>8&63]|h[63&S])}p=g,g=m,m=p}p=((g=g>>>1|g<<31)>>>1^(m=m>>>1|m<<31))&1431655765,m^=p,g^=p<<1,p=(m>>>8^g)&16711935,g^=p,m^=p<<8,p=(m>>>2^g)&858993459,g^=p,m^=p<<2,p=(g>>>16^m)&65535,m^=p,g^=p<<16,p=(g>>>4^m)&252645135,m^=p,g^=p<<4,r[0]=g,r[1]=m}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 m(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 y(e,t){return e&t}function b(e,t){return e|t}function w(e,t){return e^t}function E(e,t){return e&~t}function v(){}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)},m.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},m.prototype.revert=function(e){var t=l();return e.copyTo(t),this.reduce(t),t},m.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)},m.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},m.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,m=(1<<this.F1)/p,y=1<<this.F2,b=r.t,w=b-h,E=null==t?l():t;for(s.dlShiftTo(w,E),r.compareTo(E)>=0&&(r.data[r.t++]=1,r.subTo(E,r)),a.ONE.dlShiftTo(h,E),E.subTo(s,s);s.t<h;)s.data[s.t++]=0;for(;--w>=0;){var v=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+y)*m);if((r.data[b]+=s.am(0,v,r,w,0,h))<v)for(s.dlShiftTo(w,E),r.subTo(E,r);r.data[b]<--v;)r.subTo(E,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 m(t),this.exp(e,r)},a.ZERO=p(0),a.ONE=p(1),v.prototype.convert=S,v.prototype.revert=S,v.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},v.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,y,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,E,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,E)},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 m(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,y,b=e.t-1,w=!0,E=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,E),n.sqrTo(E,s),a-=2;a>0?n.sqrTo(s,E):(y=s,s=E,E=y),n.mulTo(E,o[d],s)}for(;b>=0&&(e.data[b]&1<<i)==0;)n.sqrTo(s,E),y=s,s=E,E=y,--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 v)},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,m=16,y=a["aes128-CBC"],b=n.aes.createEncryptionCipher;break;case"aes192":d=24,m=16,y=a["aes192-CBC"],b=n.aes.createEncryptionCipher;break;case"aes256":d=32,m=16,y=a["aes256-CBC"],b=n.aes.createEncryptionCipher;break;case"des":d=8,m=8,y=a.desCBC,b=n.des.createEncryptionCipher;break;default:var u,h,d,f,g,m,y,b,w=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw w.algorithm=r.algorithm,w}var E="hmacWith"+r.prfAlgorithm.toUpperCase(),v=p(E),S=n.pkcs5.pbkdf2(t,i,l,d,v),A=n.random.getBytesSync(m),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"!==E&&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[E]).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(y).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,A)])])])}else if("3des"===r.algorithm){d=24;var R=new n.util.ByteBuffer(i),S=o.pbe.generatePkcs12Key(t,R,1,l,d),A=o.pbe.generatePkcs12Key(t,R,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 m=u*Math.ceil(f/u),y=new n.util.ByteBuffer;for(l=0;l<m;l++)y.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 E=y;E.putBuffer(w);for(var v=Math.ceil(s/c),S=1;S<=v;S++){var A=new n.util.ByteBuffer;A.putBytes(g.bytes()),A.putBytes(E.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 R=Math.ceil(f/u)+Math.ceil(p/u),_=new n.util.ByteBuffer;for(a=0;a<R;a++){var k=new n.util.ByteBuffer(E.getBytes(u)),C=511;for(l=T.length()-1;l>=0;l--)C>>=8,C+=T.at(l)+k.at(l),k.setAt(l,255&C);_.putBuffer(k)}E=_,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),m=n.pkcs5.pbkdf2(r,p,f,i,g),y=l.encIv,b=a(m);return b.start(y),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 m=d(c.prfOid),y=o.pbe.generatePkcs12Key(r,f,1,g,i,m);return m.start(),l(y,o.pbe.generatePkcs12Key(r,f,2,g,a,m))},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)),y=w=p.digest().getBytes();for(var m=2;m<=r;++m)p.start(null,null),p.update(w),b=p.digest().getBytes(),y=s.util.xorBytes(y,b,c),w=b;f+=g<h?y:y.substr(0,d)}return f}var y,b,w,m,g=1;(function e(){if(g>h)return l(null,f);p.start(null,null),p.update(t),p.update(s.util.int32ToBytes(g)),y=w=p.digest().getBytes(),m=2,function t(){if(m<=r)return p.start(null,null),p.update(w),b=p.digest().getBytes(),y=s.util.xorBytes(y,b,c),w=b,++m,s.util.setImmediate(t);f+=g<h?y:y.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(","),m=0;m<g.length;++m)f.values.push(g[m].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 m=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 y=s(o,c-a.digestLength-1,l),b=n.util.xorBytes(m,y,m.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),m=n.util.xorBytes(p,g,p.length),y=m.substring(0,o.digestLength),c="\x00"!==h,b=0;b<o.digestLength;++b)c|=u.charAt(b)!==y.charAt(b);for(var w=1,E=o.digestLength,v=o.digestLength;v<m.length;v++){var S=m.charCodeAt(v),A=1&S^1;c|=S&(w?65534:0),w&=A,E+=w}if(c||1!==m.charCodeAt(E))throw Error("Invalid RSAES-OAEP padding.");return m.substring(E+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()},m=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 y(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 E(e){return n.util.isNodejs&&"function"==typeof s[e]}function v(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=y(e,t,r)):(s=n.util.createBuffer()).putBytes(e);for(var l=m(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=m(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(E("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(v("generateKey")&&v("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(E("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 y(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={},m=[];if(o.validate(e,u,g,m)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},m=[],!o.validate(e,h,g,m)){var y=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw y.errors=m,y}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,m,y,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,m=e.h5,y=e.h6,b=e.h7;u<64;++u)o=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7),l=y^g&(m^y),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=y,y=m,m=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+m|0,e.h6=e.h6+y|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,m,y,b,w,E,v,S,A,I,T,R,_,k,C,B,D,P,N,L,x,O,M,U,F=r.length();F>=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((N=(x=t[P-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[P-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[P-7],U=t[P-16],L=i+O[1]+o+U[1],t[P][0]=n+O[0]+s+U[0]+(L/4294967296>>>0)>>>0,t[P][1]=L>>>0;for(P=0,m=e[0][0],y=e[0][1],b=e[1][0],w=e[1][1],E=e[2][0],v=e[2][1],S=e[3][0],A=e[3][1],I=e[4][0],T=e[4][1],R=e[5][0],_=e[5][1],k=e[6][0],C=e[6][1],B=e[7][0],D=e[7][1];P<80;++P)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=(k^I&(R^k))>>>0,p=(C^T&(_^C))>>>0,a=((m>>>28|y<<4)^(y>>>2|m<<30)^(y>>>7|m<<25))>>>0,c=((m<<4|y>>>28)^(y<<30|m>>>2)^(y<<25|m>>>7))>>>0,f=(m&b|E&(m^b))>>>0,g=(y&w|v&(y^w))>>>0,L=D+h+p+l[P][1]+t[P][1],n=B+u+d+l[P][0]+t[P][0]+(L/4294967296>>>0)>>>0,i=L>>>0,s=a+f+((L=c+g)/4294967296>>>0)>>>0,o=L>>>0,B=k,D=C,k=R,C=_,R=I,_=T,I=S+n+((L=A+i)/4294967296>>>0)>>>0,T=L>>>0,S=E,A=v,E=b,v=w,b=m,w=y,m=n+s+((L=i+o)/4294967296>>>0)>>>0,y=L>>>0;L=e[0][1]+y,e[0][0]=e[0][0]+m+(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]+v,e[2][0]=e[2][0]+E+(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]+_,e[5][0]=e[5][0]+R+(L/4294967296>>>0)>>>0,e[5][1]=L>>>0,L=e[6][1]+C,e[6][0]=e[6][0]+k+(L/4294967296>>>0)>>>0,e[6][1]=L>>>0,L=e[7][1]+D,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)},m=function(e,t,r){var n=f(e,t);return null!==n&&(n=r in n?n[r]:null),n},y=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(m,arguments,n)},a.removeItem=function(e,t,r,n){w(y,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),m=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+m|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 m},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 m(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 Q},Xx:function(){return X}});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 m=d.a===a;class y 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=V(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),m=U(f-p);if(g===a)return m===a?this.double():w.ZERO;let y=U(g*g),E=U(g*y),v=U(h*y),S=U(m*m-E-c*v),A=U(m*(v-S)-p*E),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(!m){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=m?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&&v.get(t);!n&&(n=this.precomputeWindow(r),t&&1!==r&&(n=w.normalizeZ(n),v.set(t,n)));let i=w.ZERO,s=w.BASE,o=1+(m?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(E(p,n[r])):i=i.add(E(f,n[d]))}return{p:i,f:s}}multiply(e,t){let r,n,i=M(e);if(m){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=E(e,l),u=new w(U((u=E(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:V(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 E(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 v=new WeakMap;class S{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,v.delete(this)}hasEvenY(){return this.y%c===a}static fromCompressedHex(e){let t=32===e.length,r=x(t?e:e.subarray(1));if(!$(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,m=F(g,n)*g%t,y=F(m,i)*m%t,b=F(y,o)*y%t,w=F(b,a)*b%t,E=F(w,o)*y%t,v=F(E,u)*h%t,S=F(v,s)*m%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=K(O(e)),{n:o}=d,a=2===r||3===r?n+o:n,l=V(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(!$(t)||!$(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: ${k(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?k(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: ${k(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: ${k(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(!q(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!q(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(P(this.s)),t=A(P(this.r)),r=e.length/2,n=t.length/2,i=P(r),s=P(n),o=P(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 R(...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 _=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function k(e){if(!(e instanceof Uint8Array))throw Error("Expected Uint8Array");let t="";for(let r=0;r<e.length;r++)t+=_[e[r]];return t}let C=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function B(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(a<=e&&e<C))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function D(e){let t=L(B(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function P(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(k(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&&q(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 V(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 K(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 y("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 R(...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 R(...t)}}function q(e){return a<e&&e<d.n}function $(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(!q(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 X(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=[D(i),function(e){var t;let r=Y(e),n=U(r,d.n);return D(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=R(...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=K(e,!0);if(!q(s))return;let o=V(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 J={strict:!0};function Q(e,t,r,n=J){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=K(t);try{s=r instanceof S?(r.assertValidity(),r):S.fromHex(r)}catch(e){return!1}let{n:c}=d,u=V(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:k,hexToBytes:L,concatBytes:R,mod:U,invert:V,isValidPrivateKey(e){try{return z(e),!0}catch(e){return!1}},_bigintTo32Bytes:D,_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 D(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",R(...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=R(...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=R(t,t),ee[e]=r}return et.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof n)throw new y("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=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)}}})},5302:function(e,t,r){"use strict";let n,i,s,o,a,l,c,u,h,d,p,f,g,m,y,b,w,E,v,S,A,I,T,R,_,k,C,B,D,P,N,L,x,O,M,U,F,V,K,H,q,$,z,G,j,W,Y,X,J,Q,Z,ee,et,er,en,ei,es,eo,ea,el,ec,eu,eh,ed,ep,ef,eg,em,ey,eb,ew,eE,ev,eS,eA,eI,eT,eR,e_,ek,eC,eB,eD,eP,eN,eL,ex,eO,eM,eU,eF,eV,eK,eH,eq,e$,ez,eG,ej,eW,eY,eX,eJ,eQ,eZ,e0,e1,e2,e3,e4,e6,e8,e5,e9,e7,te,tt,tr,tn,ti,ts,to,ta,tl,tc,tu,th,td,tp,tf,tg,tm,ty,tb,tw,tE,tv,tS,tA,tI,tT;r.d(t,{Uw:function(){return sr},Md:function(){return af.Md},pq:function(){return wm},iY:function(){return af.iY},gT:function(){return lD}});var tR,t_,tk,tC,tB,tD,tP,tN,tL,tx,tO,tM,tU,tF,tV,tK,tH,tq,t$,tz,tG,tj,tW,tY,tX,tJ,tQ,tZ,t0,t1,t2,t3,t4,t6,t8,t5,t9,t7,re,rt,rr,rn,ri,rs,ro,ra,rl,rc,ru,rh,rd,rp,rf,rg,rm,ry,rb,rw,rE,rv,rS,rA,rI,rT,rR,r_,rk,rC,rB,rD,rP,rN,rL,rx,rO,rM,rU,rF,rV,rK,rH,rq,r$,rz,rG,rj,rW,rY,rX,rJ,rQ,rZ,r0,r1,r2,r3,r4,r6,r8,r5,r9,r7,ne,nt,nr,nn,ni,ns,no,na,nl,nc,nu,nh,nd,np,nf,ng,nm,ny,nb,nw,nE,nv,nS,nA,nI,nT,nR,n_,nk,nC,nB,nD,nP,nN,nL,nx,nO,nM,nU,nF,nV,nK,nH,nq,n$,nz,nG,nj,nW,nY,nX,nJ,nQ,nZ,n0,n1,n2,n3,n4,n6,n8,n5,n9,n7,ie,it,ir,ii,is,io,ia,il,ic,iu,ih,id,ip,ig,im,iy,ib,iw,iE,iv,iS,iA,iI,iT,iR,i_,ik,iC,iB,iD,iP,iN,iL,ix,iO,iM,iU,iF,iV,iK,iH,iq,i$,iz,iG,ij,iW,iY,iX,iJ,iQ,iZ,i0,i1,i2,i3,i4,i6,i8,i5,i9,i7,se,st,sr,sn,si,ss,so,sa,sl,sc,su,sh,sd,sp,sf,sg,sm,sy,sb,sw,sE,sv,sS,sA,sI,sT,sR,s_,sk,sC,sB,sD,sP,sN,sL,sx,sO,sM,sU,sF,sV,sK,sH,sq,s$,sz,sG,sj,sW,sY,sX,sJ,sQ,sZ,s0,s1,s2,s3,s4,s6,s8,s5,s9,s7,oe,ot,or,on,oi,os,oo,oa,ol,oc,ou,oh,od,op,of,og,om,oy,ob,ow,oE,ov,oS,oA,oI,oT,oR,o_,ok,oC,oB,oD,oP,oN,oL,ox,oO,oM,oU,oF,oV,oK,oH,oq,o$,oz,oG,oj,oW,oY,oX,oJ,oQ,oZ,o0,o1,o2,o3,o4,o6,o8,o5,o9,o7={};r.r(o7),r.d(o7,{gk:function(){return cV},dQ:function(){return cZ},ci:function(){return cH},bytesToNumberBE:function(){return cj},ty:function(){return cW},eV:function(){return cQ},n$:function(){return c2},ql:function(){return cJ},hexToBytes:function(){return cG},_t:function(){return cF},tL:function(){return cY},S5:function(){return cX},FF:function(){return c4}});var ae={};r.r(ae),r.d(ae,{Ed25519PrivateKey:function(){return hm},Ed25519PublicKey:function(){return hg},generateKeyPair:function(){return hw},generateKeyPairFromSeed:function(){return hE},unmarshalEd25519PrivateKey:function(){return hy},unmarshalEd25519PublicKey:function(){return hb}});var at={};r.r(at),r.d(at,{MAX_KEY_SIZE:function(){return hD},RsaPrivateKey:function(){return hN},RsaPublicKey:function(){return hP},fromJwk:function(){return hO},generateKeyPair:function(){return hM},unmarshalRsaPrivateKey:function(){return hL},unmarshalRsaPublicKey:function(){return hx}});var ar={};r.r(ar),r.d(ar,{Secp256k1PrivateKey:function(){return hZ},Secp256k1PublicKey:function(){return hQ},generateKeyPair:function(){return h2},unmarshalSecp256k1PrivateKey:function(){return h0},unmarshalSecp256k1PublicKey:function(){return h1}});var an={};r.r(an),r.d(an,{Ed25519PrivateKey:function(){return pB},Ed25519PublicKey:function(){return pC},generateKeyPair:function(){return pN},generateKeyPairFromSeed:function(){return pL},unmarshalEd25519PrivateKey:function(){return pD},unmarshalEd25519PublicKey:function(){return pP}});var ai={};r.r(ai),r.d(ai,{MAX_RSA_KEY_SIZE:function(){return f5},RsaPrivateKey:function(){return f7},RsaPublicKey:function(){return f9},fromJwk:function(){return gr},generateKeyPair:function(){return gn},unmarshalRsaPrivateKey:function(){return ge},unmarshalRsaPublicKey:function(){return gt}});var as={};r.r(as),r.d(as,{Secp256k1PrivateKey:function(){return go},Secp256k1PublicKey:function(){return gs},generateKeyPair:function(){return gc},unmarshalSecp256k1PrivateKey:function(){return ga},unmarshalSecp256k1PublicKey:function(){return gl}});var ao=r(6995),aa=r(9425);function al(e){return!!e}function ac(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 au(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 ah(e,t){let r=await e.toWire(t);return!!r&&ad(r)}(tR=ik||(ik={})).codec=()=>(null==s&&(s=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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),tR.encode=e=>(0,ao.LE)(e,tR.codec()),tR.decode=(e,t)=>(0,ao.C6)(e,tR.codec(),t),(t_=iC||(iC={})).codec=()=>(null==o&&(o=(0,ao.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),ik.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,aa.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=ik.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),o),t_.encode=e=>(0,ao.LE)(e,t_.codec()),t_.decode=(e,t)=>(0,ao.C6)(e,t_.codec(),t),(tC=(tk=iB||(iB={})).ContentFilter||(tk.ContentFilter={})).codec=()=>(null==l&&(l=(0,ao.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})),l),tC.encode=e=>(0,ao.LE)(e,tC.codec()),tC.decode=(e,t)=>(0,ao.C6)(e,tC.codec(),t),tk.codec=()=>(null==a&&(a=(0,ao.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),tk.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(tk.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&t)}}return n})),a),tk.encode=e=>(0,ao.LE)(e,tk.codec()),tk.decode=(e,t)=>(0,ao.C6)(e,tk.codec(),t),(tB=iD||(iD={})).codec=()=>(null==c&&(c=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(10),iL.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(iL.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),c),tB.encode=e=>(0,ao.LE)(e,tB.codec()),tB.decode=(e,t)=>(0,ao.C6)(e,tB.codec(),t),(tD=iP||(iP={})).codec=()=>(null==u&&(u=(0,ao.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),iB.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),iD.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=iB.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=iD.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),u),tD.encode=e=>(0,ao.LE)(e,tD.codec()),tD.decode=(e,t)=>(0,ao.C6)(e,tD.codec(),t),(tP=iN||(iN={})).codec=()=>(null==h&&(h=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),h),tP.encode=e=>(0,ao.LE)(e,tP.codec()),tP.decode=(e,t)=>(0,ao.C6)(e,tP.codec(),t),(tN=iL||(iL={})).codec=()=>(null==d&&(d=(0,ao.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),iN.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,aa.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=iN.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),d),tN.encode=e=>(0,ao.LE)(e,tN.codec()),tN.decode=(e,t)=>(0,ao.C6)(e,tN.codec(),t),(tL=ix||(ix={})).codec=()=>(null==p&&(p=(0,ao.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})),p),tL.encode=e=>(0,ao.LE)(e,tL.codec()),tL.decode=(e,t)=>(0,ao.C6)(e,tL.codec(),t),(tO=f=(tx=iO||(iO={})).FilterSubscribeType||(tx.FilterSubscribeType={})).SUBSCRIBER_PING="SUBSCRIBER_PING",tO.SUBSCRIBE="SUBSCRIBE",tO.UNSUBSCRIBE="UNSUBSCRIBE",tO.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL",(tM=g||(g={}))[tM.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",tM[tM.SUBSCRIBE=1]="SUBSCRIBE",tM[tM.UNSUBSCRIBE=2]="UNSUBSCRIBE",tM[tM.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL",(f=tx.FilterSubscribeType||(tx.FilterSubscribeType={})).codec=()=>(0,ao.Ji)(g),tx.codec=()=>(null==m&&(m=(0,ao.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!==g[e.filterSubscribeType]&&(t.uint32(16),tx.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:f.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=tx.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 ao.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})),m),tx.encode=e=>(0,ao.LE)(e,tx.codec()),tx.decode=(e,t)=>(0,ao.C6)(e,tx.codec(),t),(tU=iM||(iM={})).codec=()=>(null==y&&(y=(0,ao.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})),y),tU.encode=e=>(0,ao.LE)(e,tU.codec()),tU.decode=(e,t)=>(0,ao.C6)(e,tU.codec(),t),(tF=iU||(iU={})).codec=()=>(null==b&&(b=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),iV.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=iV.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),b),tF.encode=e=>(0,ao.LE)(e,tF.codec()),tF.decode=(e,t)=>(0,ao.C6)(e,tF.codec(),t),(tV=iF||(iF={})).codec=()=>(null==w&&(w=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),w),tV.encode=e=>(0,ao.LE)(e,tV.codec()),tV.decode=(e,t)=>(0,ao.C6)(e,tV.codec(),t),(tK=iV||(iV={})).codec=()=>(null==E&&(E=(0,ao.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),iF.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,aa.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=iF.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),E),tK.encode=e=>(0,ao.LE)(e,tK.codec()),tK.decode=(e,t)=>(0,ao.C6)(e,tK.codec(),t),(tH=iK||(iK={})).codec=()=>(null==v&&(v=(0,ao.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),iz.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=iz.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),v),tH.encode=e=>(0,ao.LE)(e,tH.codec()),tH.decode=(e,t)=>(0,ao.C6)(e,tH.codec(),t),(tq=iH||(iH={})).codec=()=>(null==S&&(S=(0,ao.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})),S),tq.encode=e=>(0,ao.LE)(e,tq.codec()),tq.decode=(e,t)=>(0,ao.C6)(e,tq.codec(),t),(t$=iq||(iq={})).codec=()=>(null==A&&(A=(0,ao.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),iK.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),iH.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=iK.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=iH.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),A),t$.encode=e=>(0,ao.LE)(e,t$.codec()),t$.decode=(e,t)=>(0,ao.C6)(e,t$.codec(),t),(tz=i$||(i$={})).codec=()=>(null==I&&(I=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),I),tz.encode=e=>(0,ao.LE)(e,tz.codec()),tz.decode=(e,t)=>(0,ao.C6)(e,tz.codec(),t),(tG=iz||(iz={})).codec=()=>(null==T&&(T=(0,ao.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),i$.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,aa.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=i$.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),T),tG.encode=e=>(0,ao.LE)(e,tG.codec()),tG.decode=(e,t)=>(0,ao.C6)(e,tG.codec(),t),(tj=iG||(iG={})).codec=()=>(null==R&&(R=(0,ao.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,aa.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})),R),tj.encode=e=>(0,ao.LE)(e,tj.codec()),tj.decode=(e,t)=>(0,ao.C6)(e,tj.codec(),t),(tY=(tW=ij||(ij={})).Direction||(tW.Direction={})).BACKWARD="BACKWARD",tY.FORWARD="FORWARD",(tX=_||(_={}))[tX.BACKWARD=0]="BACKWARD",tX[tX.FORWARD=1]="FORWARD",(tW.Direction||(tW.Direction={})).codec=()=>(0,ao.Ji)(_),tW.codec=()=>(null==k&&(k=(0,ao.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),iG.codec().encode(e.cursor,t)),null!=e.direction&&(t.uint32(24),tW.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=iG.codec().decode(e,e.uint32(),{limits:r.limits?.cursor});break;case 3:n.direction=tW.Direction.codec().decode(e);break;default:e.skipType(7&t)}}return n})),k),tW.encode=e=>(0,ao.LE)(e,tW.codec()),tW.decode=(e,t)=>(0,ao.C6)(e,tW.codec(),t),(tJ=iW||(iW={})).codec=()=>(null==C&&(C=(0,ao.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})),C),tJ.encode=e=>(0,ao.LE)(e,tJ.codec()),tJ.decode=(e,t)=>(0,ao.C6)(e,tJ.codec(),t),(tQ=iY||(iY={})).codec=()=>(null==B&&(B=(0,ao.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),iW.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),ij.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(iW.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=ij.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})),B),tQ.encode=e=>(0,ao.LE)(e,tQ.codec()),tQ.decode=(e,t)=>(0,ao.C6)(e,tQ.codec(),t),(t0=D=(tZ=iX||(iX={})).HistoryError||(tZ.HistoryError={})).NONE="NONE",t0.INVALID_CURSOR="INVALID_CURSOR",t0.TOO_MANY_RESULTS="TOO_MANY_RESULTS",t0.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",(t1=P||(P={}))[t1.NONE=0]="NONE",t1[t1.INVALID_CURSOR=1]="INVALID_CURSOR",t1[t1.TOO_MANY_RESULTS=429]="TOO_MANY_RESULTS",t1[t1.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",(D=tZ.HistoryError||(tZ.HistoryError={})).codec=()=>(0,ao.Ji)(P),tZ.codec=()=>(null==N&&(N=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(18),iZ.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(26),ij.codec().encode(e.pagingInfo,t)),null!=e.error&&0!==P[e.error]&&(t.uint32(32),tZ.HistoryError.codec().encode(e.error,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[],error:D.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(iZ.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 3:n.pagingInfo=ij.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 4:n.error=tZ.HistoryError.codec().decode(e);break;default:e.skipType(7&t)}}return n})),N),tZ.encode=e=>(0,ao.LE)(e,tZ.codec()),tZ.decode=(e,t)=>(0,ao.C6)(e,tZ.codec(),t),(t2=iJ||(iJ={})).codec=()=>(null==L&&(L=(0,ao.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),iY.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),iX.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=iY.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=iX.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),L),t2.encode=e=>(0,ao.LE)(e,t2.codec()),t2.decode=(e,t)=>(0,ao.C6)(e,t2.codec(),t),(t3=iQ||(iQ={})).codec=()=>(null==x&&(x=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),x),t3.encode=e=>(0,ao.LE)(e,t3.codec()),t3.decode=(e,t)=>(0,ao.C6)(e,t3.codec(),t),(t4=iZ||(iZ={})).codec=()=>(null==O&&(O=(0,ao.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),iQ.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,aa.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=iQ.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),O),t4.encode=e=>(0,ao.LE)(e,t4.codec()),t4.decode=(e,t)=>(0,ao.C6)(e,t4.codec(),t),(t6=i0||(i0={})).codec=()=>(null==M&&(M=(0,ao.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})),M),t6.encode=e=>(0,ao.LE)(e,t6.codec()),t6.decode=(e,t)=>(0,ao.C6)(e,t6.codec(),t),(t8=i1||(i1={})).codec=()=>(null==U&&(U=(0,ao.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})),U),t8.encode=e=>(0,ao.LE)(e,t8.codec()),t8.decode=(e,t)=>(0,ao.C6)(e,t8.codec(),t),(t5=i2||(i2={})).codec=()=>(null==F&&(F=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(let r of e.peerInfos)t.uint32(10),i0.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 ao.sv('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(i0.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),F),t5.encode=e=>(0,ao.LE)(e,t5.codec()),t5.decode=(e,t)=>(0,ao.C6)(e,t5.codec(),t),(t9=i3||(i3={})).codec=()=>(null==V&&(V=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),i1.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),i2.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=i1.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=i2.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),V),t9.encode=e=>(0,ao.LE)(e,t9.codec()),t9.decode=(e,t)=>(0,ao.C6)(e,t9.codec(),t),(t7=i4||(i4={})).codec=()=>(null==K&&(K=(0,ao.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 ao.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),t7.encode=e=>(0,ao.LE)(e,t7.codec()),t7.decode=(e,t)=>(0,ao.C6)(e,t7.codec(),t),(re=i6||(i6={})).codec=()=>(null==H&&(H=(0,ao.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 ao.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})),H),re.encode=e=>(0,ao.LE)(e,re.codec()),re.decode=(e,t)=>(0,ao.C6)(e,re.codec(),t);let ad=e=>e.length/1048576<=1;var ap=r(9802);(rt=i8||(i8={})).Relay="relay",rt.Store="store",rt.LightPush="lightpush",rt.Filter="filter",(rr=i5||(i5={})).GENERIC_FAIL="Generic error",rr.ENCODE_FAILED="Failed to encode",rr.DECODE_FAILED="Failed to decode",rr.EMPTY_PAYLOAD="Payload is empty",rr.SIZE_TOO_BIG="Size is too big",rr.TOPIC_NOT_CONFIGURED="Topic not configured",rr.NO_PEER_AVAILABLE="No peer available",rr.REMOTE_PEER_FAULT="Remote peer fault",rr.REMOTE_PEER_REJECTED="Remote peer rejected",rr.REQUEST_TIMEOUT="Request timeout",(rn=i9||(i9={})).BACKWARD="backward",rn.FORWARD="forward",(ri=i7||(i7={})).BOOTSTRAP="bootstrap",ri.PEER_EXCHANGE="peer-exchange",ri.LOCAL="local-peer-cache",(rs=se||(se={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",rs.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",rs.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",rs.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(st||(st={})).CONNECTION_STATUS="waku:connection";var af=r(9710);let ag=e=>{if(void 0===e.clusterId||void 0===e.shard)throw Error("Invalid shard");return`/waku/2/rs/${e.clusterId}/${e.shard}`},am=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map(t=>aE(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??1}/${t}`)))}if("application"in e&&"version"in e)return[aE(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw Error("Missing required configuration in shard parameters")},ay=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 ab(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 aw(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,ap.J)((0,af.zo)([(0,af.iY)(r),(0,af.iY)(n)])),s=new DataView(i.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(t))}function aE(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");let n=aw(e,r);return`/waku/2/rs/${t}/${n}`}function av(e,t){return"string"==typeof t?t:t?.shard?ag(t):aE(e,t?.clusterId||1)}let aS=e=>{let t=e.clusterId??1,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:am({clusterId:t,shards:r})};if(a){let e=Array.from(new Set(n.map(e=>aE(e,t)))),r=Array.from(new Set(n.map(e=>aw(e))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(l){let e=aE(`/${i}/${s}/default/default`,t);return{shardingParams:{clusterId:t,application:i,version:s},shardInfo:{clusterId:t,shards:[ay(e).shard]},pubsubTopics:[e]}}throw Error("Missing minimum required configuration options for static sharding or autosharding.")},aA=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}},aI=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)};var aT=r(4461);let aR="waku";class a_{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${aR}:${e}:${t}`:`${aR}:${e}`}constructor(e){this._info=aT(a_.createDebugNamespace("info",e)),this._warn=aT(a_.createDebugNamespace("warn",e)),this._error=aT(a_.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)}}let ak=new a_("message:version-0"),aC=BigInt(1e6);class aB{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/aC;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 aD{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 iC.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())*aC,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){let e=this.metaSetter(r);return{...r,meta:e}}return r}}class aP{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=iC.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?(ak.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new aB(e,t)}}(ro=sr||(sr={})).Relay="relay",ro.Store="store",ro.LightPush="lightpush",ro.Filter="filter",(ra=sn||(sn={})).GENERIC_FAIL="Generic error",ra.ENCODE_FAILED="Failed to encode",ra.DECODE_FAILED="Failed to decode",ra.EMPTY_PAYLOAD="Payload is empty",ra.SIZE_TOO_BIG="Size is too big",ra.TOPIC_NOT_CONFIGURED="Topic not configured",ra.NO_PEER_AVAILABLE="No peer available",ra.REMOTE_PEER_FAULT="Remote peer fault",ra.REMOTE_PEER_REJECTED="Remote peer rejected",ra.REQUEST_TIMEOUT="Request timeout",(rl=si||(si={})).BACKWARD="backward",rl.FORWARD="forward",(rc=ss||(ss={})).BOOTSTRAP="bootstrap",rc.PEER_EXCHANGE="peer-exchange",rc.LOCAL="local-peer-cache",(ru=so||(so={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",ru.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",ru.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",ru.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(sa||(sa={})).CONNECTION_STATUS="waku:connection";let aN="/waku/2/default-waku/proto";var aL=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},ax=r(7383);function aO(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));let r=(0,aa.E)(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}var aM=r(1363);let aU=Symbol.for("@achingbrain/uint8arraylist");function aF(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 aV(e){return!!e?.[aU]}class aK{bufs;length;[aU]=!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(aV(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(aV(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=aF(this.bufs,e);return t.buf[t.index]}set(e,t){let r=aF(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(aV(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 aO(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:aO(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new aK;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(!aV(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,aa.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,aa.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,aa.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,aa.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,aa.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,aa.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,aa.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,aa.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,aa.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,aa.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 aK)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!(0,aM.f)(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new aK;return r.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),r.length=t,r}}function aH(e){return null!=e[Symbol.asyncIterator]}let aq=e=>{let t=ax.P$(e),r=(0,aa.E)(t);return ax.cv(e,r),aq.bytes=t,r};function a$(e,t){t=t??{};let r=t.lengthEncoder??aq;function*n(e){let t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return aH(e)?async function*(){for await(let t of e)yield*n(t)}():function*(){for(let t of e)yield*n(t)}()}aq.bytes=0,a$.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??aq;return new aK(r(e.byteLength),e)};var az=r(2594);(rh=sl||(sl={}))[rh.LENGTH=0]="LENGTH",rh[rh.DATA=1]="DATA";let aG=e=>{let t=ax.Jx(e);return aG.bytes=ax.P$(t),t};function aj(e,t){let r=new aK,n=sl.LENGTH,i=-1,s=t?.lengthDecoder??aG,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*l(){for(;r.byteLength>0;){if(n===sl.LENGTH)try{if((i=s(r))<0)throw az(Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw az(Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let e=s.bytes;r.consume(e),t?.onLength!=null&&t.onLength(i),n=sl.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw az(Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===sl.DATA){if(r.byteLength<i)break;let e=r.sublist(0,i);r.consume(i),t?.onData!=null&&t.onData(e),yield e,n=sl.LENGTH}}}return aH(e)?async function*(){for await(let t of e)r.append(t),yield*l();if(r.byteLength>0)throw az(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let t of e)r.append(t),yield*l();if(r.byteLength>0)throw az(Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}function aW(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}aG.bytes=0,aj.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 aj(n,{...t??{},onLength:e=>{r=e}})};class aY{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 aX{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new aY(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 aY(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 aJ extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function aQ(e={}){return function(e,t){let r,n,i;let s=(t=t??{}).onEnd,o=new aX,a=aW(),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=aW()})}},c=e=>null!=n?n(e):(o.push(e),r),u=e=>(o=new aX,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 aX,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 aJ)},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 aZ=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=aQ({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 a0(e,...t){if(null==e)throw Error("Empty pipeline");if(a4(e)){let t=e;e=()=>t.source}else if(a3(e)||a2(e)){let t=e;e=()=>t}let r=[e,...t];if(r.length>1&&a4(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++)a4(r[e])&&(r[e]=a6(r[e]));return a1(...r)}let a1=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},a2=e=>e?.[Symbol.asyncIterator]!=null,a3=e=>e?.[Symbol.iterator]!=null,a4=e=>null!=e&&null!=e.sink&&null!=e.source,a6=e=>t=>{let r=e.sink(t);if(r?.then!=null){let t;let n=aQ({objectMode:!0});r.then(()=>{n.end()},e=>{n.end(e)});let i=e.source;if(a2(i))t=async function*(){yield*i,n.end()};else if(a3(i))t=function*(){yield*i,n.end()};else throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");return aZ(n,t())}return e.source};async function a8(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,af.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 a5(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 a9(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&&aA(e);if(t&&n.clusterId===t.clusterId)return i}}return null}),o=await Promise.all(s);return o.filter(e=>null!==e)}function a7(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)}class le{multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new a_(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool.bind(this)),this.getStream=this.getStream.bind(this),this.streamPool=new Map}async getStream(e){let t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.newStream(e);this.streamPool.delete(t),this.prepareNewStream(e);let n=await r;return n&&"closed"!==n.status?n:this.newStream(e)}async newStream(e){let t=this.getConnections(e.id),r=a7(t);if(!r)throw Error("Failed to get a connection to the peer");return r.newStream(this.multicodec)}prepareNewStream(e){let t=this.newStream(e).catch(()=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()}`)});this.streamPool.set(e.id.toString(),t)}handlePeerUpdateStreamPool=e=>{let t=e.detail.peer;t.protocols.includes(this.multicodec)&&(this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareNewStream(t))}}class lt{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 le(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 a5(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 a9(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?aS(this.options.shardInfo).shardInfo:void 0),n=function(e,t,r){let n=e.filter(e=>e.tags.has(ss.BOOTSTRAP)).slice(0,r);t>0&&t<n.length&&(n=n.slice(0,t));let i=e.filter(e=>!e.tags.has(ss.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 a8(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}}let lr="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var ln={randomUUID:lr};let li=new Uint8Array(16),ls=[];for(let e=0;e<256;++e)ls.push((e+256).toString(16).slice(1));var lo=function(e,t,r){if(ln.randomUUID&&!t&&!e)return ln.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(li)})();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 ls[e[t+0]]+ls[e[t+1]]+ls[e[t+2]]+ls[e[t+3]]+"-"+ls[e[t+4]]+ls[e[t+5]]+"-"+ls[e[t+6]]+ls[e[t+7]]+"-"+ls[e[t+8]]+ls[e[t+9]]+"-"+ls[e[t+10]]+ls[e[t+11]]+ls[e[t+12]]+ls[e[t+13]]+ls[e[t+14]]+ls[e[t+15]]}(i)};class la{proto;constructor(e){this.proto=e}static decode(e){let t=iU.decode(e);return new la(t)}encode(){return iU.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class ll{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new ll({requestId:lo(),filterSubscribeType:iO.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new ll({requestId:lo(),filterSubscribeType:iO.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new ll({requestId:lo(),filterSubscribeType:iO.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new ll({requestId:lo(),filterSubscribeType:iO.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){let t=iO.decode(e);return new ll(t)}encode(){return iO.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 lc{proto;constructor(e){this.proto=e}static decode(e){let t=iM.decode(e);return new lc(t)}encode(){return iM.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}let lu=new a_("filter:v2"),lh={SUBSCRIBE:"/vac/waku/filter-subscribe/2.0.0-beta1",PUSH:"/vac/waku/filter-push/2.0.0-beta1"};class ld{peers;pubsubTopic;newStream;receivedMessagesHashStr=[];subscriptionCallbacks;constructor(e,t,r){this.peers=t,this.pubsubTopic=e,this.newStream=r,this.subscriptionCallbacks=new Map}async subscribe(e,t){let r=Array.isArray(e)?e:[e];r.forEach(e=>{if(e.pubsubTopic!==this.pubsubTopic)throw Error(`Pubsub topic not configured: decoder is configured for pubsub topic ${e.pubsubTopic} but this subscription is for pubsub topic ${this.pubsubTopic}. Please create a new Subscription for the different pubsub topic.`)});let n=ac(r),i=Array.from(n.keys()),s=this.peers.map(async e=>{let t=await this.newStream(e),r=ll.createSubscribeRequest(this.pubsubTopic,i);try{let n=await a0([r.encode()],a$,t,aj,async e=>await aL(e));if(!n||!n.length)throw Error(`No response received for request ${r.requestId}: ${n}`);let{statusCode:s,requestId:o,statusDesc:a}=lc.decode(n[0].slice());if(s<200||s>=300)throw Error(`Filter subscribe request ${o} failed with status code ${s}: ${a}`);lu.info("Subscribed to peer ",e.id.toString(),"for content topics",i)}catch(t){throw Error("Error subscribing to peer: "+e.id.toString()+" for content topics: "+i+": "+t)}}),o=await Promise.allSettled(s);this.handleErrors(o,"subscribe"),n.forEach((e,r)=>{this.subscriptionCallbacks.set(r,{decoders:e,callback:t})})}async unsubscribe(e){let t=this.peers.map(async t=>{let r=await this.newStream(t),n=ll.createUnsubscribeRequest(this.pubsubTopic,e);try{await a0([n.encode()],a$,r.sink)}catch(e){throw Error("Error unsubscribing: "+e)}e.forEach(e=>{this.subscriptionCallbacks.delete(e)})}),r=await Promise.allSettled(t);this.handleErrors(r,"unsubscribe")}async ping(){let e=this.peers.map(async e=>{let t=await this.newStream(e),r=ll.createSubscriberPingRequest();try{let n=await a0([r.encode()],a$,t,aj,async e=>await aL(e));if(!n||!n.length)throw Error(`No response received for request ${r.requestId}: ${n}`);let{statusCode:i,requestId:s,statusDesc:o}=lc.decode(n[0].slice());if(i<200||i>=300)throw Error(`Filter ping request ${s} failed with status code ${i}: ${o}`);lu.info(`Ping successful for peer ${e.id.toString()}`)}catch(e){throw lu.error("Error pinging: ",e),e}}),t=await Promise.allSettled(e);this.handleErrors(t,"ping")}async unsubscribeAll(){let e=this.peers.map(async e=>{let t=await this.newStream(e),r=ll.createUnsubscribeAllRequest(this.pubsubTopic);try{let e=await a0([r.encode()],a$,t,aj,async e=>await aL(e));if(!e||!e.length)throw Error(`No response received for request ${r.requestId}: ${e}`);let{statusCode:n,requestId:i,statusDesc:s}=lc.decode(e[0].slice());if(n<200||n>=300)throw Error(`Filter unsubscribe all request ${i} failed with status code ${n}: ${s}`);this.subscriptionCallbacks.clear(),lu.info(`Unsubscribed from all content topics for pubsub topic ${this.pubsubTopic}`)}catch(e){throw Error("Error unsubscribing from all content topics: "+e)}}),t=await Promise.allSettled(e);this.handleErrors(t,"unsubscribeAll")}async processMessage(e){let t=function(e,t){let r=function(e,t){let r;let n=(0,af.iY)(e),i=(0,af.iY)(t.contentTopic);return r=t.meta?(0,af.zo)([n,t.payload,i,t.meta]):(0,af.zo)([n,t.payload,i]),(0,ap.J)(r)}(e,t),n=(0,af.Md)(r);return n}(this.pubsubTopic,e);if(this.receivedMessagesHashStr.includes(t)){lu.info("Message already received, skipping");return}this.receivedMessagesHashStr.push(t);let{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);if(!n){lu.error("No subscription callback available for ",r);return}lu.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await lf(n,this.pubsubTopic,e)}handleErrors(e,t){let r=e.filter(e=>"rejected"===e.status).map(e=>e.reason);if(r.length===this.peers.length){let e=new Map;r.forEach(t=>{let r=t instanceof Error?t.message:String(t);e.set(r,(e.get(r)||0)+1)});let n=Array.from(e,([e,t])=>`${e} (occurred ${t} times)`).join(", ");throw Error(`Error ${t} all peers: ${n}`)}r.length>0?lu.warn(`Some ${t} failed. These will be refreshed with new peers`,r):lu.info(`${t} successful for all peers`)}}class lp extends lt{activeSubscriptions=new Map;getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}numPeersToUse;constructor(e,t){super(lh.SUBSCRIBE,e.components,lu,t.pubsubTopics,t),this.numPeersToUse=t?.numPeersToUse??3,e.handle(lh.PUSH,this.onRequest.bind(this)).catch(e=>{lu.error("Failed to register ",lh.PUSH,e)}),this.activeSubscriptions=new Map}async createSubscription(e=aN){let t="string"==typeof e?e:ag(e);ab(t,this.pubsubTopics);let r=await this.getPeers({maxBootstrapPeers:1,numPeers:this.numPeersToUse});if(0===r.length)throw Error("No peer found to initiate subscription.");lu.info(`Creating filter subscription with ${r.length} peers: `,r.map(e=>e.id.toString()));let n=this.getActiveSubscription(t)??this.setActiveSubscription(t,new ld(t,r,this.getStream.bind(this)));return n}toSubscriptionIterator(e){return au(this,e)}async subscribe(e,t){let r=this.getPubsubTopics(e);if(0===r.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(r.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");let n=await this.createSubscription(r[0]);await n.subscribe(e,t);let i=Array.from(ac(Array.isArray(e)?e:[e]).keys());return async()=>{await n.unsubscribe(i)}}onRequest(e){let{connection:t,stream:r}=e,{remotePeer:n}=t;lu.info(`Received message from ${n.toString()}`);try{a0(r,aj,async e=>{for await(let t of e){let e=la.decode(t.slice()),{pubsubTopic:r,wakuMessage:n}=e;if(!n){lu.error("Received empty message");return}if(!r){lu.error("Pubsub topic missing from push message");return}let i=this.getActiveSubscription(r);if(!i){lu.error(`No subscription locally registered for topic ${r}`);return}await i.processMessage(n)}}).then(()=>{lu.info("Receiving pipe closed.")},e=>{lu.error("Error with receiving pipe",e)})}catch(e){lu.error("Error decoding message",e)}}getPubsubTopics(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 lf(e,t,r){let{decoders:n,callback:i}=e,{contentTopic:s}=r;if(!s){lu.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){lu.error("Error decoding message",e)}}class lg{proto;constructor(e){this.proto=e}static createRequest(e,t){return new lg({requestId:lo(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){let t=iq.decode(e);return new lg(t)}encode(){return iq.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}let lm=new a_("light-push");class ly extends lt{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,lm,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return lm.error("Failed to send waku light push: payload is empty"),{query:null,error:sn.EMPTY_PAYLOAD};if(!await ah(e,t))return lm.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:sn.SIZE_TOO_BIG};let r=await e.toProtoObj(t);if(!r)return lm.error("Failed to encode to protoMessage, aborting push"),{query:null,error:sn.ENCODE_FAILED};let n=lg.createRequest(r,e.pubsubTopic);return{query:n,error:null}}catch(e){return lm.error("Failed to prepare push message",e),{query:null,error:sn.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 lm.error(`Failed to get a stream for remote peer${r.id.toString()}`,e),{success:null,failure:{error:sn.REMOTE_PEER_FAULT,peerId:r.id}}}try{i=await a0([o.encode()],a$,n,aj,async e=>await aL(e))}catch(e){return lm.error("Failed to send waku light push request",e),{success:null,failure:{error:sn.GENERIC_FAIL,peerId:r.id}}}let l=new aK;i.forEach(e=>{l.append(e)});try{s=lg.decode(l).response}catch(e){return lm.error("Failed to decode push reply",e),{success:null,failure:{error:sn.DECODE_FAILED,peerId:r.id}}}return s?s.isSuccess?{success:r.id,failure:null}:(lm.error("Remote peer rejected the message: ",s.info),{success:null,failure:{error:sn.REMOTE_PEER_REJECTED,peerId:r.id}}):(lm.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:sn.REMOTE_PEER_FAULT,peerId:r.id}})}}let lb={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},lw=BigInt(1e6);(rd=sc||(sc={})).BACKWARD="backward",rd.FORWARD="forward";class lE{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 sc.BACKWARD:return ij.Direction.BACKWARD;case sc.FORWARD:return ij.Direction.FORWARD;default:return ij.Direction.BACKWARD}}(e.pageDirection),s={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:i};return e.startTime&&(t=BigInt(e.startTime.valueOf())*lw),e.endTime&&(r=BigInt(e.endTime.valueOf())*lw),new lE({requestId:lo(),query:{pubsubTopic:e.pubsubTopic,contentFilters:n,pagingInfo:s,startTime:t,endTime:r},response:void 0})}decode(e){let t=iJ.decode(e);return new lE(t)}encode(){return iJ.encode(this.proto)}}var lv=iX.HistoryError;let lS=new a_("store");class lA extends lt{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,lS,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(;;){e.cursor=n;let i=lE.createQuery(e),s=await this.getStream(r),o=await a0([i.encode()],a$,s,aj,async e=>await aL(e)),a=new aK;o.forEach(e=>{a.append(e)});let l=i.decode(a);if(!l.response){lS.warn("Stopping pagination due to store `response` field missing");break}let c=l.response;if(c.error&&c.error!==lv.NONE)throw"History response contains an Error: "+c.error;if(!c.messages||!c.messages.length){lS.warn("Stopping pagination due to store `response.messages` field missing or empty");break}lS.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,{...lb,...r})}return Promise.resolve(void 0)});let u=c.pagingInfo?.cursor;if(void 0===u){lS.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;let h=c.pagingInfo?.pageSize,d=i.query?.pagingInfo?.pageSize;if(h&&d&&h<d)break}}}class lI extends Error{constructor(e){super(e),this.name="TimeoutError"}}class lT extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}let lR=e=>void 0===globalThis.DOMException?new lT(e):new DOMException(e),l_=e=>{let t=void 0===e.reason?lR("This operation was aborted."):e.reason;return t instanceof Error?t:lR(t)};function lk(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(l_(e)),e.addEventListener("abort",()=>{l(l_(e))})}if(n===Number.POSITIVE_INFINITY){e.then(a,l);return}let c=new lI;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 lC=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)}},lB=new a_("wait-for-remote-peer");async function lD(e,t,r){if(t=t??function(e){let t=[];return e.relay&&t.push(sr.Relay),e.filter&&t.push(sr.Filter),e.store&&t.push(sr.Store),e.lightPush&&t.push(sr.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");let n=[];if(t.includes(sr.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");n.push(lN(e.relay))}if(t.includes(sr.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");n.push(lP(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(sr.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");n.push(lP(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(sr.Filter)){if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted");n.push(lP(e.filter,e.libp2p.services.metadata))}r?await lx(Promise.all(n),r,"Timed out waiting for a remote peer."):await Promise.all(n)}async function lP(e,t){let r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t){lB.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&&lB.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),lB.error(`Error waiting for handshake confirmation: ${e}`)}}lB.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&&lB.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),lB.error(`Error waiting for handshake confirmation: ${e}`)}):(e.removeLibp2pEventListener("peer:identify",i),n()))};e.addLibp2pEventListener("peer:identify",i)})}async function lN(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}=lC(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=lk(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 lL=(e,t)=>new Promise((r,n)=>setTimeout(()=>n(t),e));async function lx(e,t,r){await Promise.race([e,lL(t,r)])}let lO=(e,...t)=>{};class lM extends EventTarget{#e=new Map;constructor(){super(),lO(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 lU extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}let CustomEvent=globalThis.CustomEvent??lU,lF=new a_("keep-alive");class lV{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),lF.info(`Ping succeeded (${s})`,i)}catch(e){lF.error(`Ping failed for peer (${s}).
|
|
Next ping will be attempted in ${n} seconds.
|
|
`);return}try{await r.patch(e,{metadata:{ping:(0,af.iY)(i.toString())}})}catch(e){lF.error("Failed to update ping",e)}}catch(e){lF.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=function({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:i}){return new aD(r,n,av(r,e??t),i)}({pubsubTopicShardInfo:ay(i),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),a=setInterval(()=>{lF.info("Sending Waku Relay ping message"),e.send(o,{payload:new Uint8Array([1])}).catch(e=>lF.error("Failed to send relay ping",e))},1e3*t);n.push(a)}return n}}let lK=new a_("connection-manager");class lH extends lM{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(sa.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new CustomEvent(sa.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,i,s){let o=lH.instances.get(e);return o||(o=new lH(t,r,n,i,s),lH.instances.set(e,o)),o}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(ss.BOOTSTRAP)?r.push(t):e.includes(ss.PEER_EXCHANGE)?n.push(t):e.includes(ss.LOCAL)&&i.push(t)}for(let e of t){let t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(ss.BOOTSTRAP)?s.push(t):r.includes(ss.PEER_EXCHANGE)?o.push(t):r.includes(ss.LOCAL)&&a.push(t)}return{DISCOVERED:{[ss.BOOTSTRAP]:r,[ss.PEER_EXCHANGE]:n,[ss.LOCAL]:i},CONNECTED:{[ss.BOOTSTRAP]:s,[ss.PEER_EXCHANGE]:o,[ss.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 lV(t,n),this.run().then(()=>lK.info("Connection Manager is now running")).catch(e=>lK.error("Unexpected error while running service",e)),this.dialPeerStorePeers().catch(e=>lK.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){lK.error("Unexpected error while dialing peer store peers",e)}}async run(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener()}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 dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t<this.options.maxDialAttemptsForPeer;)try{lK.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?lK.error(`Error dialing peer ${e.toString()} - ${r.errors}`):lK.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?lK.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):lK.warn("No errors array found for AggregateError"):r=t.message,lK.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}`)}}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),lK.info(`Dropped connection with peer ${e.toString()}`)}catch(t){lK.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount<this.options.maxParallelDials){let e=this.pendingPeerDialQueue.shift();e&&this.attemptDial(e).catch(e=>{lK.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=>{lK.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){lK.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{lK.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(ss.BOOTSTRAP);if(r){let e=this.libp2p.getConnections().filter(e=>e.tags.includes(ss.BOOTSTRAP));e.length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new CustomEvent(so.PEER_CONNECT_BOOTSTRAP,{detail:t}))}else this.dispatchEvent(new CustomEvent(so.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 lK.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 lK.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())||(lK.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(lK.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===ss.BOOTSTRAP);if(!r)return!0;{let e=this.libp2p.getConnections().filter(e=>e.tags.find(e=>e===ss.BOOTSTRAP)).length;if(e<this.options.maxBootstrapPeersAllowed)return!0}return!1}async dispatchDiscoveryEvent(e){let t=(await this.getTagNamesForPeer(e)).includes(ss.BOOTSTRAP);this.dispatchEvent(new CustomEvent(t?so.PEER_DISCOVERY_BOOTSTRAP:so.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 lK.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=am(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 aA(n)}}let lq=new a_("metadata"),l$="/vac/waku/metadata/1.0.0";class lz extends lt{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(l$,t.components,lq,am(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(l$,e=>{this.onRequest(e)})}async onRequest(e){try{let{stream:t,connection:r}=e,n=i6.encode(this.shardInfo),i=await a0([n],a$,t,aj,async e=>await aL(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){lq.error("Error handling metadata request",e)}}async query(e){let t=i4.encode(this.shardInfo),r=await this.peerStore.get(e);if(!r)return{shardInfo:null,error:sn.NO_PEER_AVAILABLE};let n=await this.getStream(r),i=await a0([t],a$,n,aj,async e=>await aL(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 aK;e.forEach(e=>{t.append(e)});let r=i6.decode(t);return r?{shardInfo:r,error:null}:(lq.error("Error decoding metadata response"),{shardInfo:null,error:sn.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:aI(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}class lG 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 lj(e,t,r){let n;if(null==t)return e;if(t.aborted)return Promise.reject(new lG(r?.errorMessage,r?.errorCode));let i=new lG(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 lW{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=aW(),this.haveNext=aW()}[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=aW(),e}async throw(e){return this.ended=!0,null!=e&&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");if(null!=this.nextResult&&(await this.readNext.promise,null!=this.nextResult))throw Error("NeedNext promise resolved but nextResult was not consumed");null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=aW(),await lj(this.readNext.promise,t?.signal,t)}}class lY extends Error{code;constructor(e,t){super(e),this.code=t}}class lX extends lY{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}class lJ extends Error{code;constructor(e,t){super(e),this.code=t}}function lQ(e,t={}){let r=function(e,t){let r=new lW;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 aK;return{read:async(e,t)=>{let r;t?.signal?.throwIfAborted();let s=new Promise((e,n)=>{r=()=>{n(new lX("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 aK;return t}for(;i.byteLength<e;){let{value:e,done:t}=await Promise.race([n.next(),s]);if(!0===t)throw new lY("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=ax.P$(t.maxDataLength));let n=t?.lengthDecoder??ax.Jx,i=t?.lengthEncoder??ax.cv;return{read:async e=>{let i=-1,s=new aK;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 lJ("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(i>-1)break}if(t?.maxDataLength!=null&&i>t.maxDataLength)throw new lJ("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(i,e)},write:async(e,t)=>{await r.write(new aK(i(e.byteLength),e),t)},writeV:async(e,t)=>{let n=new aK(...e.flatMap(e=>[i(e.byteLength),e]));await r.write(n,t)},unwrap:()=>r.unwrap()}}function lZ(){let e=aW(),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 l0=!!globalThis.process?.env?.DUMP_SESSION_KEYS,l1=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function l2(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}let l3=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),l4=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!l4)throw Error("Non little-endian hardware is not supported");function l6(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function l8(e){if("string"==typeof e)e=l6(e);else if(l2(e))e=e.slice();else throw Error(`expected Uint8Array, got ${typeof e}`);return e}let l5=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function l9(e,t){if(!l2(e))throw Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw Error(`Uint8Array length ${t} expected`)}function l7(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 ce(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`wrong positive integer: ${e}`)}function ct(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function cr(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 cn(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 ci=(e,t)=>255&e[t++]|(255&e[t++])<<8;class cs{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,l9(e=l8(e),32);let t=ci(e,0),r=ci(e,2),n=ci(e,4),i=ci(e,6),s=ci(e,8),o=ci(e,10),a=ci(e,12),l=ci(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]=ci(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=ci(e,t+0),m=ci(e,t+2),y=ci(e,t+4),b=ci(e,t+6),w=ci(e,t+8),E=ci(e,t+10),v=ci(e,t+12),S=ci(e,t+14),A=n[0]+(8191&g),I=n[1]+((g>>>13|m<<3)&8191),T=n[2]+((m>>>10|y<<6)&8191),R=n[3]+((y>>>7|b<<9)&8191),_=n[4]+((b>>>4|w<<12)&8191),k=n[5]+(w>>>1&8191),C=n[6]+((w>>>14|E<<2)&8191),B=n[7]+((E>>>11|v<<5)&8191),D=n[8]+((v>>>8|S<<8)&8191),P=n[9]+(S>>>5|(r?0:2048)),N=0,L=0+A*s+I*(5*f)+T*(5*p)+R*(5*d)+_*(5*h);N=L>>>13,L&=8191,L+=k*(5*u)+C*(5*c)+B*(5*l)+D*(5*a)+P*(5*o),N+=L>>>13,L&=8191;let x=N+A*o+I*s+T*(5*f)+R*(5*p)+_*(5*d);N=x>>>13,x&=8191,x+=k*(5*h)+C*(5*u)+B*(5*c)+D*(5*l)+P*(5*a),N+=x>>>13,x&=8191;let O=N+A*a+I*o+T*s+R*(5*f)+_*(5*p);N=O>>>13,O&=8191,O+=k*(5*d)+C*(5*h)+B*(5*u)+D*(5*c)+P*(5*l),N+=O>>>13,O&=8191;let M=N+A*l+I*a+T*o+R*s+_*(5*f);N=M>>>13,M&=8191,M+=k*(5*p)+C*(5*d)+B*(5*h)+D*(5*u)+P*(5*c),N+=M>>>13,M&=8191;let U=N+A*c+I*l+T*a+R*o+_*s;N=U>>>13,U&=8191,U+=k*(5*f)+C*(5*p)+B*(5*d)+D*(5*h)+P*(5*u),N+=U>>>13,U&=8191;let F=N+A*u+I*c+T*l+R*a+_*o;N=F>>>13,F&=8191,F+=k*s+C*(5*f)+B*(5*p)+D*(5*d)+P*(5*h),N+=F>>>13,F&=8191;let V=N+A*h+I*u+T*c+R*l+_*a;N=V>>>13,V&=8191,V+=k*o+C*s+B*(5*f)+D*(5*p)+P*(5*d),N+=V>>>13,V&=8191;let K=N+A*d+I*h+T*u+R*c+_*l;N=K>>>13,K&=8191,K+=k*a+C*o+B*s+D*(5*f)+P*(5*p),N+=K>>>13,K&=8191;let H=N+A*p+I*d+T*h+R*u+_*c;N=H>>>13,H&=8191,H+=k*l+C*a+B*o+D*s+P*(5*f),N+=H>>>13,H&=8191;let q=N+A*f+I*p+T*d+R*h+_*u;N=q>>>13,q&=8191,q+=k*c+C*l+B*a+D*o+P*s,N+=q>>>13,q&=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]=V,n[7]=K,n[8]=H,n[9]=q}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){cn(this);let{buffer:t,blockLen:r}=this;e=l8(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){cn(this),function(e,t){cr(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 co=function(e){let t=(t,r)=>e(r).update(l8(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(e=>new cs(e)),ca=l6("expand 16-byte k"),cl=l6("expand 32-byte k"),cc=l1(ca),cu=l1(cl);function ch(e,t){return e<<t|e>>>32-t}function cd(e){return e.byteOffset%4==0}let cp=4294967296-1,cf=new Uint32Array;function cg(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||!l5(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 ce(i),ce(o),ct(s),ct(r),(t,a,l,c,u=0)=>{cr(t),cr(a),cr(l);let h=l.length;if(c||(c=new Uint8Array(h)),cr(c),ce(u),u<0||u>=cp)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=cu;else if(16===p&&r)(f=new Uint8Array(32)).set(t),f.set(t,16),g=cc,d.push(f);else throw Error(`arx: invalid 32-byte key, got length=${p}`);cd(a)||(a=a.slice(),d.push(a));let m=l1(f);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(g,m,l1(a.subarray(0,16)),m),a=a.subarray(16)}let y=16-i;if(y!==a.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){let e=new Uint8Array(12);e.set(a,s?0:12-a.length),a=e,d.push(a)}let b=l1(a);for(function(e,t,r,n,i,s,o,a){let l=i.length,c=new Uint8Array(64),u=l1(c),h=cd(i)&&cd(s),d=h?l1(i):cf,p=h?l1(s):cf;for(let f=0;f<l;o++){if(e(t,r,n,u,o,a),o>=cp)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,m,b,l,c,u,o);d.length>0;)d.pop().fill(0);return c}}function cm(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],m=t[6],y=t[7],b=r[0],w=r[1],E=r[2],v=o,S=a,A=l,I=c,T=u,R=h,_=d,k=p,C=f,B=g,D=m,P=y,N=i,L=b,x=w,O=E;for(let e=0;e<s;e+=2)C=C+(N=ch(N^(v=v+T|0),16))|0,v=v+(T=ch(T^C,12))|0,C=C+(N=ch(N^v,8))|0,T=ch(T^C,7),B=B+(L=ch(L^(S=S+R|0),16))|0,S=S+(R=ch(R^B,12))|0,B=B+(L=ch(L^S,8))|0,R=ch(R^B,7),D=D+(x=ch(x^(A=A+_|0),16))|0,A=A+(_=ch(_^D,12))|0,D=D+(x=ch(x^A,8))|0,_=ch(_^D,7),P=P+(O=ch(O^(I=I+k|0),16))|0,I=I+(k=ch(k^P,12))|0,P=P+(O=ch(O^I,8))|0,k=ch(k^P,7),D=D+(O=ch(O^(v=v+R|0),16))|0,v=v+(R=ch(R^D,12))|0,D=D+(O=ch(O^v,8))|0,R=ch(R^D,7),P=P+(N=ch(N^(S=S+_|0),16))|0,S=S+(_=ch(_^P,12))|0,P=P+(N=ch(N^S,8))|0,_=ch(_^P,7),C=C+(L=ch(L^(A=A+k|0),16))|0,A=A+(k=ch(k^C,12))|0,C=C+(L=ch(L^A,8))|0,k=ch(k^C,7),B=B+(x=ch(x^(I=I+T|0),16))|0,I=I+(T=ch(T^B,12))|0,B=B+(x=ch(x^I,8))|0,T=ch(T^B,7);let M=0;n[M++]=o+v|0,n[M++]=a+S|0,n[M++]=l+A|0,n[M++]=c+I|0,n[M++]=u+T|0,n[M++]=h+R|0,n[M++]=d+_|0,n[M++]=p+k|0,n[M++]=f+C|0,n[M++]=g+B|0,n[M++]=m+D|0,n[M++]=y+P|0,n[M++]=i+N|0,n[M++]=b+L|0,n[M++]=w+x|0,n[M++]=E+O|0}let cy=cg(cm,{counterRight:!1,counterLength:4,allowShortKeys:!1}),cb=cg(cm,{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],m=r[0],y=r[1],b=r[2],w=r[3];for(let e=0;e<20;e+=2)d=d+(m=ch(m^(i=i+l|0),16))|0,i=i+(l=ch(l^d,12))|0,d=d+(m=ch(m^i,8))|0,l=ch(l^d,7),p=p+(y=ch(y^(s=s+c|0),16))|0,s=s+(c=ch(c^p,12))|0,p=p+(y=ch(y^s,8))|0,c=ch(c^p,7),f=f+(b=ch(b^(o=o+u|0),16))|0,o=o+(u=ch(u^f,12))|0,f=f+(b=ch(b^o,8))|0,u=ch(u^f,7),g=g+(w=ch(w^(a=a+h|0),16))|0,a=a+(h=ch(h^g,12))|0,g=g+(w=ch(w^a,8))|0,h=ch(h^g,7),f=f+(w=ch(w^(i=i+c|0),16))|0,i=i+(c=ch(c^f,12))|0,f=f+(w=ch(w^i,8))|0,c=ch(c^f,7),g=g+(m=ch(m^(s=s+u|0),16))|0,s=s+(u=ch(u^g,12))|0,g=g+(m=ch(m^s,8))|0,u=ch(u^g,7),d=d+(y=ch(y^(o=o+h|0),16))|0,o=o+(h=ch(h^d,12))|0,d=d+(y=ch(y^o,8))|0,h=ch(h^d,7),p=p+(b=ch(b^(a=a+l|0),16))|0,a=a+(l=ch(l^p,12))|0,p=p+(b=ch(b^a,8))|0,l=ch(l^p,7);let E=0;n[E++]=i,n[E++]=s,n[E++]=o,n[E++]=a,n[E++]=m,n[E++]=y,n[E++]=b,n[E++]=w},allowShortKeys:!1}),cw=new Uint8Array(16),cE=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(cw.subarray(r))},cv=new Uint8Array(32);function cS(e,t,r,n,i){let s=e(t,r,cv),o=co.create(s);i&&cE(o,i),cE(o,n);let a=new Uint8Array(16),l=l3(a);l7(l,0,BigInt(i?i.length:0),!0),l7(l,8,BigInt(n.length),!0),o.update(a);let c=o.digest();return s.fill(0),c}let cA=e=>(t,r,n)=>(l9(t,32),l9(r),{encrypt:(i,s)=>{let o=i.length,a=o+16;s?l9(s,a):s=new Uint8Array(a),e(t,r,i,s,1);let l=cS(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?l9(s,a):s=new Uint8Array(a);let l=i.subarray(0,-16),c=i.subarray(-16),u=cS(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}}),cI=(Object.assign(rp=cA(cy),{blockSize:64,nonceLength:12,tagLength:16}),rp);cA(cb);var cT=r(8289);let cR=BigInt(4294967296-1),c_=BigInt(32);function ck(e,t=!1){return t?{h:Number(e&cR),l:Number(e>>c_&cR)}:{h:0|Number(e>>c_&cR),l:0|Number(e&cR)}}var cC={fromBig:ck,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}=ck(e[i],t);[r[i],n[i]]=[s,o]}return[r,n]},toBig:(e,t)=>BigInt(e>>>0)<<c_|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)},cB=r(2305);let[cD,cP]=cC.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))),cN=new Uint32Array(80),cL=new Uint32Array(80);class cx extends cT.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)cN[r]=e.getUint32(t),cL[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|cN[e-15],r=0|cL[e-15],n=cC.rotrSH(t,r,1)^cC.rotrSH(t,r,8)^cC.shrSH(t,r,7),i=cC.rotrSL(t,r,1)^cC.rotrSL(t,r,8)^cC.shrSL(t,r,7),s=0|cN[e-2],o=0|cL[e-2],a=cC.rotrSH(s,o,19)^cC.rotrBH(s,o,61)^cC.shrSH(s,o,6),l=cC.rotrSL(s,o,19)^cC.rotrBL(s,o,61)^cC.shrSL(s,o,6),c=cC.add4L(i,l,cL[e-7],cL[e-16]),u=cC.add4H(c,n,a,cN[e-7],cN[e-16]);cN[e]=0|u,cL[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:m,Hl:y}=this;for(let e=0;e<80;e++){let t=cC.rotrSH(u,h,14)^cC.rotrSH(u,h,18)^cC.rotrBH(u,h,41),b=cC.rotrSL(u,h,14)^cC.rotrSL(u,h,18)^cC.rotrBL(u,h,41),w=u&d^~u&f,E=h&p^~h&g,v=cC.add5L(y,b,E,cP[e],cL[e]),S=cC.add5H(v,m,t,w,cD[e],cN[e]),A=0|v,I=cC.rotrSH(r,n,28)^cC.rotrBH(r,n,34)^cC.rotrBH(r,n,39),T=cC.rotrSL(r,n,28)^cC.rotrBL(r,n,34)^cC.rotrBL(r,n,39),R=r&i^r&o^i&o,_=n&s^n&a^s&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=cC.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 k=cC.add3L(A,T,_);r=cC.add3H(k,S,I,R),n=0|k}({h:r,l:n}=cC.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=cC.add(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=cC.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:l,l:c}=cC.add(0|this.Dh,0|this.Dl,0|l,0|c)),({h:u,l:h}=cC.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=cC.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=cC.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=cC.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,i,s,o,a,l,c,u,h,d,p,f,g,m,y)}roundClean(){cN.fill(0),cL.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 cO=(0,cB.hE)(()=>new cx);BigInt(0);let cM=BigInt(1),cU=BigInt(2);function cF(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function cV(e){if(!cF(e))throw Error("Uint8Array expected")}let cK=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function cH(e){cV(e);let t="";for(let r=0;r<e.length;r++)t+=cK[e[r]];return t}function cq(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}let c$={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function cz(e){return e>=c$._0&&e<=c$._9?e-c$._0:e>=c$._A&&e<=c$._F?e-(c$._A-10):e>=c$._a&&e<=c$._f?e-(c$._a-10):void 0}function cG(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=cz(e.charCodeAt(i)),s=cz(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 cj(e){return cq(cH(e))}function cW(e){return cV(e),cq(cH(Uint8Array.from(e).reverse()))}function cY(e,t){return cG(e.toString(16).padStart(2*t,"0"))}function cX(e,t){return cY(e,t).reverse()}function cJ(e,t,r){let n;if("string"==typeof t)try{n=cG(t)}catch(r){throw Error(`${e} must be valid hex string, got "${t}". Cause: ${r}`)}else if(cF(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 cQ(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];cV(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 cZ=e=>(cU<<BigInt(e-1))-cM,c0=e=>new Uint8Array(e),c1=e=>Uint8Array.from(e);function c2(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=c0(e),i=c0(e),s=0,o=()=>{n.fill(1),i.fill(0),s=0},a=(...e)=>r(i,n,...e),l=(e=c0())=>{i=a(c1([0]),e),n=a(),0!==e.length&&(i=a(c1([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 cQ(...r)};return(e,t)=>{let r;for(o(),l(e);!(r=t(c()));)l();return o(),r}}let c3={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||cF(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 c4(e,t,r={}){let n=(t,r,n)=>{let i=c3[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 c6=BigInt(0),c8=BigInt(1),c5=BigInt(2),c9=BigInt(3),c7=BigInt(4),ue=BigInt(5),ut=BigInt(8);function ur(e,t){let r=e%t;return r>=c6?r:t+r}function un(e,t,r){if(r<=c6||t<c6)throw Error("Expected power/modulo > 0");if(r===c8)return c6;let n=c8;for(;t>c6;)t&c8&&(n=n*e%r),e=e*e%r,t>>=c8;return n}function ui(e,t,r){let n=e;for(;t-- >c6;)n*=n,n%=r;return n}function us(e,t){if(e===c6||t<=c6)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ur(e,t),n=t,i=c6,s=c8,o=c8,a=c6;for(;r!==c6;){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!==c8)throw Error("invert: does not exist");return ur(i,t)}BigInt(9),BigInt(16);let uo=(e,t)=>(ur(e,t)&c8)===c8,ua=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ul(e,t){let r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function uc(e,t,r=!1,n={}){if(e<=c6)throw Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:s}=ul(e,t);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");let o=function(e){if(e%c7===c9){let t=(e+c8)/c7;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%ut===ue){let t=(e-ue)/ut;return function(e,r){let n=e.mul(r,c5),i=e.pow(n,t),s=e.mul(r,i),o=e.mul(e.mul(s,c5),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-c8)/c5;for(t=e-c8,r=0;t%c5===c6;t/=c5,r++);for(n=c5;n<e&&un(n,i,e)!==e-c8;n++);if(1===r){let t=(e+c8)/c7;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+c8)/c5;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,c8<<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:cZ(i),ZERO:c6,ONE:c8,create:t=>ur(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error(`Invalid field element: expected bigint, got ${typeof t}`);return c6<=t&&t<e},is0:e=>e===c6,isOdd:e=>(e&c8)===c8,neg:t=>ur(-t,e),eql:(e,t)=>e===t,sqr:t=>ur(t*t,e),add:(t,r)=>ur(t+r,e),sub:(t,r)=>ur(t-r,e),mul:(t,r)=>ur(t*r,e),pow:(e,t)=>(function(e,t,r){if(r<c6)throw Error("Expected power > 0");if(r===c6)return e.ONE;if(r===c8)return t;let n=e.ONE,i=t;for(;r>c6;)r&c8&&(n=e.mul(n,i)),i=e.sqr(i),r>>=c8;return n})(a,e,t),div:(t,r)=>ur(t*us(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>us(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?cX(e,s):cY(e,s),fromBytes:e=>{if(e.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?cW(e):cj(e)}});return Object.freeze(a)}function uu(e){if("bigint"!=typeof e)throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function uh(e){let t=uu(e);return t+Math.ceil(t/2)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let ud=BigInt(0),up=BigInt(1);function uf(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>ud;)r&up&&(n=n.add(i)),i=i.double(),r>>=up;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+=up);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 ug(e){return!function(e){let t=ua.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});c4(e,t)}(e.Fp),c4(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ul(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let um=BigInt(0),uy=BigInt(1),ub=BigInt(2),uw=BigInt(8),uE={zip215:!0},uv=BigInt(0),uS=BigInt(1),uA=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),uI=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uT=BigInt(0),uR=BigInt(1),u_=BigInt(2),uk=BigInt(5),uC=BigInt(10),uB=BigInt(20),uD=BigInt(40),uP=BigInt(80);function uN(e){let t=e*e%uA,r=t*e%uA,n=ui(r,u_,uA)*r%uA,i=ui(n,uR,uA)*e%uA,s=ui(i,uk,uA)*i%uA,o=ui(s,uC,uA)*s%uA,a=ui(o,uB,uA)*o%uA,l=ui(a,uD,uA)*a%uA,c=ui(l,uP,uA)*l%uA,u=ui(c,uP,uA)*l%uA,h=ui(u,uC,uA)*s%uA,d=ui(h,u_,uA)*e%uA;return{pow_p_5_8:d,b2:r}}function uL(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function ux(e,t){let r=ur(t*t*t,uA),n=ur(r*r*t,uA),i=uN(e*n).pow_p_5_8,s=ur(e*r*i,uA),o=ur(t*s*s,uA),a=s,l=ur(s*uI,uA),c=o===e,u=o===ur(-e,uA),h=o===ur(-e*uI,uA);return c&&(s=a),(u||h)&&(s=l),uo(s,uA)&&(s=ur(-s,uA)),{isValid:c||u,value:s}}let uO=uc(uA,void 0,!0),uM={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:uO,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:cO,randomBytes:cB.O6,adjustScalarBytes:uL,uvRatio:ux},uU=function(e){let t=function(e){let t=ug(e);return c4(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=ub<<BigInt(8*a)-uy,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:um}}}),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&&um<e,g=(e,t)=>f(e)&&f(t)&&e<t,m=e=>e===um||g(e,c);function y(e,t){if(g(e,t))return e;throw Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function b(e){return e===um?e:y(e,n)}let w=new Map;function E(e){if(!(e instanceof v))throw Error("ExtendedPoint expected")}class v{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!m(e))throw Error("x required");if(!m(t))throw Error("y required");if(!m(r))throw Error("z required");if(!m(n))throw Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof v)throw Error("extended point not allowed");let{x:t,y:r}=e||{};if(!m(t)||!m(r))throw Error("invalid affine point");return new v(t,r,uy,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(v.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),m=u(s*o);if(g!==m)throw Error("bad point: equation left != right (2)")}equals(e){E(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(v.ZERO)}negate(){return new v(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(ub*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),m=u(d*f),y=u(h*f),b=u(p*d);return new v(g,m,b,y)}add(e){E(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===um)return this.double();let n=u(o*ub*d),p=u(a*ub*h),f=p+n,g=t+e,m=p-n,y=u(f*r),b=u(g*m),w=u(f*m),E=u(r*g);return new v(y,b,E,w)}let p=u(i*l),f=u(s*c),g=u(a*n*d),m=u(o*h),y=u((i+s)*(l+c)-p-f),b=m-g,w=m+g,S=u(f-r*p),A=u(y*b),I=u(w*S),T=u(y*S),R=u(b*w);return new v(A,I,R,T)}subtract(e){return this.add(e.negate())}wNAF(e){return I.wNAFCached(this,w,e,v.normalizeZ)}multiply(e){let{p:t,f:r}=this.wNAF(y(e,n));return v.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=b(e);return t===um?A:this.equals(A)||t===uy?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?uw:r.inv(i));let o=u(t*e),a=u(n*e),l=u(i*e);if(s)return{x:um,y:uy};if(l!==uy)throw Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){let{h:e}=t;return e===uy?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){let{d:i,a:s}=t,o=r.BYTES;e=cJ("pointHex",e,o);let a=e.slice(),l=e[o-1];a[o-1]=-129&l;let d=cW(a);d===um||(n?y(d,c):y(d,r.ORDER));let p=u(d*d),f=u(p-uy),g=u(i*p-s),{isValid:m,value:b}=h(f,g);if(!m)throw Error("Point.fromHex: invalid y coordinate");let w=(b&uy)===uy,E=(128&l)!=0;if(!n&&b===um&&E)throw Error("Point.fromHex: x=0 and x_0=1");return E!==w&&(b=u(-b)),v.fromAffine({x:b,y:d})}static fromPrivateKey(e){return T(e).point}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=cX(t,r.BYTES);return n[n.length-1]|=e&uy?128:0,n}toHex(){return cH(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,uy,u(t.Gx*t.Gy)),v.ZERO=new v(um,uy,uy,um);let{BASE:S,ZERO:A}=v,I=uf(v,8*a);function T(e){e=cJ("private key",e,a);let t=cJ("hashed private key",s(e),2*a),r=d(t.slice(0,a)),i=t.slice(a,2*a),o=ur(cW(r),n),l=S.multiply(o),c=l.toRawBytes();return{head:r,prefix:i,scalar:o,point:l,pointBytes:c}}function R(e=new Uint8Array,...t){let r=cQ(...t);return ur(cW(s(p(r,cJ("context",e),!!i))),n)}return S._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return T(e).pointBytes},sign:function(e,t,s={}){e=cJ("message",e),i&&(e=i(e));let{prefix:o,scalar:l,pointBytes:c}=T(t),u=R(s.context,o,e),h=S.multiply(u).toRawBytes(),d=R(s.context,h,c,e),p=ur(u+d*l,n);b(p);let f=cQ(h,cX(p,r.BYTES));return cJ("result",f,2*a)},verify:function(e,t,n,s=uE){let o,a,l;let{context:c,zip215:u}=s,h=r.BYTES;e=cJ("signature",e,2*h),t=cJ("message",t),i&&(t=i(t));let d=cW(e.slice(h,2*h));try{o=v.fromHex(n,u),a=v.fromHex(e.slice(0,h),u),l=S.multiplyUnsafe(d)}catch(e){return!1}if(!u&&o.isSmallOrder())return!1;let p=R(c,a.toRawBytes(),o.toRawBytes(),t),f=a.add(o.multiplyUnsafe(p));return f.subtract(l).clearCofactor().equals(v.ZERO)},ExtendedPoint:v,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=v.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(uM);({...uM});let uF=function(e){let t=(c4(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})),{P:r}=t,n=e=>ur(e,r),i=t.montgomeryBits,s=Math.ceil(i/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>un(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&&uv<=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=cJ("u coordinate",e,s);return 32===o&&(t[31]&=127),cW(t)}(t),d=function(e){let t=cJ("scalar",e),r=t.length;if(r!==s&&r!==o)throw Error(`Expected ${s} or ${o} bytes, got ${r}`);return cW(a(t))}(e),p=function(e,t){let r;let s=u(e),o=u(t),a=uS,d=uv,p=s,f=uS,g=uv;for(let e=BigInt(i-1);e>=uv;e--){let t=o>>e&uS;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,m=n(u*u),y=l-m,b=p+f,w=p-f,E=n(w*i),v=n(b*u),S=E+v,A=E-v;p=n(S*S),f=n(s*n(A*A)),a=n(l*m),d=n(y*(l+n(h*y)))}a=(r=c(g,a,p))[0],p=r[1],d=(r=c(g,d,f))[0],f=r[1];let m=l(d);return n(a*m)}(r,d);if(p===uv)throw Error("Invalid private or public key received");return cX(n(p),s)}let p=cX(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:uA,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{let{pow_p_5_8:t,b2:r}=uN(e);return ur(ui(t,BigInt(3),uA)*r,uA)},adjustScalarBytes:uL,randomBytes:cB.O6}),uV=(uO.ORDER+BigInt(3))/BigInt(8);function uK(e){if(!(e instanceof uX))throw Error("RistrettoPoint expected")}uO.pow(u_,uV),uO.sqrt(uO.neg(uO.ONE)),uO.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)}(uO,uO.neg(BigInt(486664)));let uH=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),uq=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),u$=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),uz=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),uG=e=>ux(uR,e),uj=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),uW=e=>uU.CURVE.Fp.create(bytesToNumberLE(e)&uj);function uY(e){let{d:t}=uU.CURVE,r=uU.CURVE.Fp.ORDER,n=uU.CURVE.Fp.create,i=n(null*e*e),s=n((i+uR)*u$),o=BigInt(-1),a=n((o-t*i)*n(i+t)),{isValid:l,value:c}=ux(s,a),u=n(c*e);isNegativeLE(u,r)||(u=n(-u)),l||(c=u),l||(o=i);let h=n(o*(i-uR)*uz-a),d=c*c,p=n((c+c)*a),f=n(h*uH),g=n(uR-d),m=n(uR+d);return new uU.ExtendedPoint(n(p*m),n(g*f),n(f*m),n(p*g))}class uX{constructor(e){this.ep=e}static fromAffine(e){return new uX(uU.ExtendedPoint.fromAffine(e))}static hashToCurve(e){e=ensureBytes("ristrettoHash",e,64);let t=uW(e.slice(0,32)),r=uY(t),n=uW(e.slice(32,64)),i=uY(n);return new uX(r.add(i))}static fromHex(e){e=ensureBytes("ristrettoHex",e,32);let{a:t,d:r}=uU.CURVE,n=uU.CURVE.Fp.ORDER,i=uU.CURVE.Fp.create,s="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=uW(e);if(!equalBytes(numberToBytesLE(o,32),e)||isNegativeLE(o,n))throw Error(s);let a=i(o*o),l=i(uR+t*a),c=i(uR-t*a),u=i(l*l),h=i(c*c),d=i(t*r*u-h),{isValid:p,value:f}=uG(i(d*h)),g=i(f*c),m=i(f*g*d),y=i((o+o)*g);isNegativeLE(y,n)&&(y=i(-y));let b=i(l*m),w=i(y*b);if(!p||isNegativeLE(w,n)||b===uT)throw Error(s);return new uX(new uU.ExtendedPoint(y,b,uR,w))}toRawBytes(){let e,{ex:t,ey:r,ez:n,et:i}=this.ep,s=uU.CURVE.Fp.ORDER,o=uU.CURVE.Fp.create,a=o(o(n+r)*o(n-r)),l=o(t*r),c=o(l*l),{value:u}=uG(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*uq)}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){uK(e);let{ex:t,ey:r}=this.ep,{ex:n,ey:i}=e.ep,s=uU.CURVE.Fp.create,o=s(t*i)===s(r*n),a=s(r*i)===s(t*n);return o||a}add(e){return uK(e),new uX(this.ep.add(e.ep))}subtract(e){return uK(e),new uX(this.ep.subtract(e.ep))}multiply(e){return new uX(this.ep.multiply(e))}multiplyUnsafe(e){return new uX(this.ep.multiplyUnsafe(e))}double(){return new uX(this.ep.double())}negate(){return new uX(this.ep.negate())}}var uJ=r(5493);class uQ extends cB.kb{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,(0,uJ.vp)(e);let r=(0,cB.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,uJ.Gg)(this),this.iHash.update(e),this}digestInto(e){(0,uJ.Gg)(this),(0,uJ.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 uZ=(e,t,r)=>new uQ(e,t).update(r).digest();uZ.create=(e,t)=>new uQ(e,t);let u0=new Uint8Array([0]),u1=new Uint8Array,u2={hashSHA256:e=>(0,ap.J)(e.subarray()),getHKDF(e,t){var r,n;let i=(r=ap.J,n=e,(0,uJ.vp)(r),void 0===n&&(n=new Uint8Array(r.outputLen)),uZ(r,(0,cB.O0)(n),(0,cB.O0)(t))),s=function(e,t,r,n=32){if((0,uJ.vp)(e),(0,uJ.Rx)(n),n>255*e.outputLen)throw Error("Length should be <= 255*HashLen");let i=Math.ceil(n/e.outputLen);void 0===r&&(r=u1);let s=new Uint8Array(i*e.outputLen),o=uZ.create(e,t),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let t=0;t<i;t++)u0[0]=t+1,a.update(0===t?u1:l).update(r).update(u0).digestInto(l),s.set(l,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),u0.fill(0),s.slice(0,n)}(ap.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=uF.utils.randomPrivateKey(),t=uF.getPublicKey(e);return{publicKey:t,privateKey:e}},generateX25519KeyPairFromSeed(e){let t=uF.getPublicKey(e);return{publicKey:t,privateKey:e}},generateX25519SharedKey:(e,t)=>uF.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>cI(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>cI(n,t,r).decrypt(e.subarray(),i)},u3=e=>{let t=(0,aa.E)(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};u3.bytes=2;let u4=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)};u4.bytes=2;class u6 extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=u6.code}static code="ERR_UNEXPECTED_PEER"}class u8 extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=u8.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}r(9642),r(6204);class u5 extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=u5.code,this.type=u5.type}static code="ABORT_ERR";static type="aborted"}class u9 extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class u7 extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}let he="ERR_TIMEOUT";var ht=r(2595),hr=r(2223),hn=r(9029),hi=r(9137),hs=r(1818);r(2366),r(4196);var ho=r(7519);function ha(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=aO([new Uint8Array(t-r.length),r])}return(0,ho.B)(r,"base64url")}function hl(e){let t=function(e,t){let r=(0,hr.m)(e,"base64urlpad");if(null!=t){if(r.length>t)throw Error("byte array longer than desired length");r=aO([new Uint8Array(t-r.length),r])}return r}(e);return new ht.jsbn.BigInteger((0,ho.B)(t,"base16"),16)}function hc(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}function hu(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 hh=r(9678),hd={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 hp={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function hf(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=hd.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,hr.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",hp,{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",hp,{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 aO([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,hr.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",hp,{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 hh.base64.encode(n)}(rf=su||(su={})).RSA="RSA",rf.Ed25519="Ed25519",rf.Secp256k1="Secp256k1",(rg=sh||(sh={}))[rg.RSA=0]="RSA",rg[rg.Ed25519=1]="Ed25519",rg[rg.Secp256k1=2]="Secp256k1",(su||(su={})).codec=()=>(0,ao.Ji)(sh),(rm=sd||(sd={})).codec=()=>(null==q&&(q=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),su.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=su.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),q),rm.encode=e=>(0,ao.LE)(e,rm.codec()),rm.decode=e=>(0,ao.C6)(e,rm.codec()),(ry=sp||(sp={})).codec=()=>(null==$&&($=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),su.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=su.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),$),ry.encode=e=>(0,ao.LE)(e,ry.codec()),ry.decode=e=>(0,ao.C6)(e,ry.codec());class hg{_key;constructor(e){this._key=hv(e,32)}verify(e,t){var r;return r=this._key,uU.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return sd.encode({Type:su.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return hc(e)?e.then(({bytes:e})=>e):e.bytes}}class hm{_key;_publicKey;constructor(e,t){this._key=hv(e,64),this._publicKey=hv(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return uU.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new hg(this._publicKey)}marshal(){return this._key}get bytes(){return sp.encode({Type:su.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}async hash(){let e;let t=hs.sha256.digest(this.bytes);return hc(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=hi.identity.digest(this.public.bytes);return hn.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return hf(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function hy(e){if(e.length>64){e=hv(e,96);let t=e.subarray(0,64),r=e.subarray(64,e.length);return new hm(t,r)}e=hv(e,64);let t=e.subarray(0,64),r=e.subarray(32);return new hm(t,r)}function hb(e){return new hg(e=hv(e,32))}async function hw(){let{privateKey:e,publicKey:t}=function(){let e=uU.utils.randomPrivateKey(),t=uU.getPublicKey(e),r=hu(e,t);return{privateKey:r,publicKey:t}}();return new hm(e,t)}async function hE(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=uU.getPublicKey(e),r=hu(e,t);return{privateKey:r,publicKey:t}}(e);return new hm(t,r)}function hv(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new u9(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function hS(e,t){return t.map(t=>hl(e[t]))}async function hA(e){let t=await hd.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 h_(t);return{privateKey:r[0],publicKey:r[1]}}async function hI(e){let t=await hd.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),r=[t,await hk(e)],n=await h_({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function hT(e,t){let r=await hd.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await hd.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function hR(e,t,r){let n=await hd.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return hd.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function h_(e){if(null==e.privateKey||null==e.publicKey)throw new u9("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([hd.get().subtle.exportKey("jwk",e.privateKey),hd.get().subtle.exportKey("jwk",e.publicKey)])}async function hk(e){return hd.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 hC(e,t,r,n){let i=t?ht.pki.setRsaPublicKey(...hS(e,["n","e"])):ht.pki.setRsaPrivateKey(...hS(e,["n","e","d","p","q","dp","dq","qi"])),s=(0,ho.B)(r instanceof Uint8Array?r:r.subarray(),"ascii"),o=n(s,i);return(0,hr.m)(o,"ascii")}function hB(e){if("RSA"!==e.kty)throw new u9("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new u9("invalid key modulus","ERR_INVALID_KEY_MODULUS");let t=(0,hr.m)(e.n,"base64url");return 8*t.length}r(8439),r(411);let hD=8192;class hP{_key;constructor(e){this._key=e}verify(e,t){return hR(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new u9("JWK was missing components","ERR_INVALID_PARAMETERS");let t=ht.pki.publicKeyToAsn1({n:hl(e.n),e:hl(e.e)});return(0,hr.m)(ht.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return sd.encode({Type:su.RSA,Data:this.marshal()}).subarray()}encrypt(e){return hC(this._key,!0,e,(e,t)=>t.encrypt(e))}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return hc(e)?e.then(({bytes:e})=>e):e.bytes}}class hN{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(e)||e<=0)throw new u9("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,cB.O6)(e)}(16)}sign(e){return hT(this._key,e)}get public(){if(null==this._publicKey)throw new u9("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new hP(this._publicKey)}decrypt(e){return hC(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 u9("JWK was missing components","ERR_INVALID_PARAMETERS");let t=ht.pki.privateKeyToAsn1({n:hl(e.n),e:hl(e.e),d:hl(e.d),p:hl(e.p),q:hl(e.q),dP:hl(e.dp),dQ:hl(e.dq),qInv:hl(e.qi)});return(0,hr.m)(ht.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return sp.encode({Type:su.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return hc(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,ho.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){let t=new ht.util.ByteBuffer(this.marshal()),r=ht.asn1.fromDer(t),n=ht.pki.privateKeyFromAsn1(r);return ht.pki.encryptRsaPrivateKey(n,e,{algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"})}if("libp2p-key"===t)return hf(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function hL(e){let t=function(e){let t=ht.asn1.fromDer((0,ho.B)(e,"ascii")),r=ht.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:ha(r.n),e:ha(r.e),d:ha(r.d),p:ha(r.p),q:ha(r.q),dp:ha(r.dP),dq:ha(r.dQ),qi:ha(r.qInv),alg:"RS256"}}(e);if(hB(t)>hD)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await hI(t);return new hN(r.privateKey,r.publicKey)}function hx(e){let t=function(e){let t=ht.asn1.fromDer((0,ho.B)(e,"ascii")),r=ht.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:ha(r.n),e:ha(r.e)}}(e);if(hB(t)>hD)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new hP(t)}async function hO(e){if(hB(e)>hD)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await hI(e);return new hN(t.privateKey,t.publicKey)}async function hM(e){if(e>hD)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await hA(e);return new hN(t.privateKey,t.publicKey)}let{bytesToNumberBE:hU,hexToBytes:hF}=o7,hV={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){let{Err:t}=hV;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:hU(n),l:e.subarray(r+2)}},toSig(e){let{Err:t}=hV,r="string"==typeof e?hF(e):e;cV(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}=hV._parseInt(r.subarray(2)),{d:o,l:a}=hV._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}`}},hK=BigInt(0),hH=BigInt(1),hq=(BigInt(2),BigInt(3));BigInt(4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let h$=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),hz=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),hG=BigInt(1),hj=BigInt(2),hW=(e,t)=>(e+t/hj)/t,hY=uc(h$,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%h$,c=l*l*e%h$,u=ui(c,t,h$)*c%h$,h=ui(u,t,h$)*c%h$,d=ui(h,hj,h$)*l%h$,p=ui(d,n,h$)*d%h$,f=ui(p,i,h$)*p%h$,g=ui(f,o,h$)*f%h$,m=ui(g,a,h$)*g%h$,y=ui(m,o,h$)*f%h$,b=ui(y,t,h$)*c%h$,w=ui(b,s,h$)*p%h$,E=ui(w,r,h$)*l%h$,v=ui(E,hj,h$);if(!hY.eql(hY.sqr(v),e))throw Error("Cannot find square root");return v}}),hX=function(e,t){let r=t=>(function(e){let t=function(e){let t=ug(e);return c4(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 ur(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=ug(e);c4(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 cQ(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&&hK<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(cF(e)&&(e=cH(e)),"string"!=typeof e||!n.includes(e.length))throw Error("Invalid key");e=e.padStart(2*i,"0")}try{r="bigint"==typeof e?e:cj(cJ("private key",e,i))}catch(t){throw Error(`private key must be ${i} bytes, hex or bigint, not ${typeof e}`)}return s&&(r=ur(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(cJ("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,hq),{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,hq),m=r.mul(n,o),y=r.mul(i,a),b=r.mul(s,l),w=r.add(n,i),E=r.add(o,a);w=r.mul(w,E),E=r.add(m,y),w=r.sub(w,E),E=r.add(n,s);let v=r.add(o,l);return E=r.mul(E,v),v=r.add(m,b),E=r.sub(E,v),v=r.add(i,s),c=r.add(a,l),v=r.mul(v,c),c=r.add(y,b),v=r.sub(v,c),p=r.mul(f,E),c=r.mul(g,b),p=r.add(c,p),c=r.sub(y,p),p=r.add(y,p),d=r.mul(c,p),y=r.add(m,m),y=r.add(y,m),b=r.mul(f,b),E=r.mul(g,E),y=r.add(y,b),b=r.sub(m,b),b=r.mul(f,b),E=r.add(E,b),m=r.mul(y,E),d=r.add(d,m),m=r.mul(v,E),c=r.mul(w,c),c=r.sub(c,m),m=r.mul(w,y),p=r.mul(v,p),new h(c,d,p=r.add(p,m))}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===hK)return n;if(a(e),e===hH)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>hK||c>hK;)o&hH&&(u=u.add(f)),c&hH&&(d=d.add(f)),f=f.double(),o>>=hH,c>>=hH;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!==hK&&t!==hH&&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===hH)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===hH?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),n(h,this,e)}toHex(e=!0){return cH(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=uf(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=cQ;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=cj(o);if(!(hK<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&hH)===hH;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=>cH(cY(e,t.nByteLength));function d(e){let t=n>>hH;return e>t}let p=(e,t,r)=>cj(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=cJ("compactSignature",e,2*r),0,r),p(e,r,2*r))}static fromDER(e){let{r:t,s:r}=hV.toSig(cJ("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=y(cJ("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=us(u,n),g=o(-c*f),m=o(s*f),b=a.BASE.multiplyAndAddUnsafe(p,g,m);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 cG(this.toDERHex())}toDERHex(){return hV.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return cG(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}function g(e){let t=cF(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 m=t.bits2int||function(e){let r=cj(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},y=t.bits2int_modN||function(e){return o(m(e))},b=cZ(t.nBitLength);function w(e){if("bigint"!=typeof e)throw Error("bigint expected");if(!(hK<=e&&e<b))throw Error(`bigint expected < 2^${t.nBitLength}`);return cY(e,t.nByteLength)}let E={lowS:t.lowS,prehash:!1},v={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=E){let{seed:c,k2sig:h}=function(e,i,s=E){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=cJ("msgHash",e),g&&(e=cJ("prehashed msgHash",c(e)));let v=y(e),S=l(i),A=[w(S),w(v)];if(null!=b&&!1!==b){let e=!0===b?h(r.BYTES):b;A.push(cJ("extraEntropy",e))}let I=cQ(...A);return{seed:I,k2sig:function(e){let t=m(e);if(!u(t))return;let r=us(t,n),i=a.BASE.multiply(t).toAffine(),s=o(i.x);if(s===hK)return;let l=o(r*o(v+s*S));if(l===hK)return;let c=(i.x===s?0:2)|Number(i.y&hH),h=l;return p&&d(l)&&(h=d(l)?o(-l):l,c^=1),new f(s,h,c)}}}(e,i,s),p=c2(t.hash.outputLen,t.nByteLength,t.hmac);return p(c,h)},verify:function(e,r,i,s=v){let l,c;if(r=cJ("msgHash",r),i=cJ("publicKey",i),"strict"in s)throw Error("options.strict was renamed to lowS");let{lowS:u,prehash:h}=s;try{if("string"==typeof e||cF(e))try{c=f.fromDER(e)}catch(t){if(!(t instanceof hV.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=y(r),m=us(p,n),b=o(g*m),w=o(d*m),E=a.BASE.multiplyAndAddUnsafe(l,b,w)?.toAffine();if(!E)return!1;let S=o(E.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=uh(t.n);return function(e,t,r=!1){let n=e.length,i=uu(t),s=uh(t);if(n<16||n<s||n>1024)throw Error(`expected ${s}-1024 bytes of input, got ${n}`);let o=r?cj(e):cW(e),a=ur(o,t-c8)+c8;return r?cX(a,i):cY(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)=>uZ(t,e,(0,cB.eV)(...r)),randomBytes:cB.O6});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:hY,n:hz,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-hG*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=BigInt("0x100000000000000000000000000000000"),s=hW(t*e,hz),o=hW(-r*e,hz),a=ur(e-s*t-o*n,hz),l=ur(-s*r-o*t,hz),c=a>i,u=l>i;if(c&&(a=hz-a),u&&(l=hz-l),a>i||l>i)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:c,k1:a,k2neg:u,k2:l}}}},ap.J);function hJ(e){try{hX.ProjectivePoint.fromHex(e)}catch(e){throw new u9(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),hX.ProjectivePoint;class hQ{_key;constructor(e){hJ(e),this._key=e}verify(e,t){return function(e,t,r){let n=hs.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(hc(n))return n.then(({digest:r})=>hX.verify(t,r,e)).catch(e=>{throw new u9(String(e),"ERR_INVALID_INPUT")});try{return hX.verify(t,n.digest,e)}catch(e){throw new u9(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return function(e){let t=hX.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}get bytes(){return sd.encode({Type:su.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}async hash(){let e;let t=hs.sha256.digest(this.bytes);return hc(t)?{bytes:e}=await t:e=t.bytes,e}}class hZ{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return hX.getPublicKey(e,!0)}catch(e){throw new u9(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{hX.getPublicKey(e,!0)}catch(e){throw new u9(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),hJ(this._publicKey)}sign(e){return function(e,t){let r=hs.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(hc(r))return r.then(({digest:t})=>hX.sign(t,e).toDERRawBytes()).catch(e=>{throw new u9(String(e),"ERR_INVALID_INPUT")});try{return hX.sign(r.digest,e).toDERRawBytes()}catch(e){throw new u9(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new hQ(this._publicKey)}marshal(){return this._key}get bytes(){return sp.encode({Type:su.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return hc(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,ho.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return hf(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function h0(e){return new hZ(e)}function h1(e){return new hQ(e)}async function h2(){let e=hX.utils.randomPrivateKey();return new hZ(e)}let h3={rsa:at,ed25519:ae,secp256k1:ar};function h4(e){let t=Object.keys(h3).join(" / ");return new u9(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}async function h6(e){let t=sp.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case su.RSA:return h3.rsa.unmarshalRsaPrivateKey(r);case su.Ed25519:return h3.ed25519.unmarshalEd25519PrivateKey(r);case su.Secp256k1:return h3.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw h4(t.Type??"RSA")}}let h8=Symbol.for("@libp2p/peer-id");function h5(e){return null!=e&&!!e[h8]}var h9=r(4110),h7=r(8590),de=r(50);let dt=Symbol.for("nodejs.util.inspect.custom"),dr=Object.values(h9.gh).map(e=>e.decoder).reduce((e,t)=>e.or(t),h9.gh.identity.decoder);class dn{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()})`}[h8]=!0;toString(){return null==this.string&&(this.string=hn.base58btc.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return h7.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,aM.f)(this.multihash.bytes,e);if("string"==typeof e)return dl(e).equals(this);if(e?.multihash?.bytes!=null)return(0,aM.f)(this.multihash.bytes,e.multihash.bytes);throw Error("not valid Id")}[dt](){return`PeerId(${this.toString()})`}}class di extends dn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ds extends dn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class da extends dn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function dl(e,t){if(t=t??dr,"1"===e.charAt(0)||"Q"===e.charAt(0)){let t=de.Jx(hn.base58btc.decode(`z${e}`));return e.startsWith("12D")?new ds({multihash:t}):e.startsWith("16U")?new da({multihash:t}):new di({multihash:t})}return dc(dr.decode(e))}function dc(e){try{let t=de.Jx(e);if(t.code===hi.identity.code){if(36===t.digest.length)return new ds({multihash:t});if(37===t.digest.length)return new da({multihash:t})}if(t.code===hs.sha256.code)return new di({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===hs.sha256.code)return new di({multihash:e.multihash});if(t.code===hi.identity.code){if(36===t.digest.length)return new ds({multihash:e.multihash});if(37===t.digest.length)return new da({multihash:e.multihash})}throw Error("Supplied PeerID CID is invalid")}(h7.k0.decode(e))}throw Error("Supplied PeerID CID is invalid")}async function du(e,t){return 36===e.length?new ds({multihash:de.Ue(hi.identity.code,e),privateKey:t}):37===e.length?new da({multihash:de.Ue(hi.identity.code,e),privateKey:t}):new di({multihash:await hs.sha256.digest(e),publicKey:e,privateKey:t})}async function dh(e,t,r){var n;let i=await dd(e,df(t));if(null==e.publicKey)throw Error("PublicKey was missing from local PeerId");return n=e.publicKey,sg.encode({identityKey:n,identitySig:i,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function dd(e,t){if(null==e.privateKey)throw Error("PrivateKey was missing from PeerId");let r=await h6(e.privateKey);return r.sign(t)}async function dp(e){return du(e.identityKey)}function df(e){let t=(0,hr.m)("noise-libp2p-static-key:");return e instanceof Uint8Array?aO([t,e],t.length+e.length):(e.prepend(t),e)}async function dg(e,t,r){let n=await du(t.identityKey);if(!n.equals(r))throw Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=df(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=sd.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case su.RSA:return h3.rsa.unmarshalRsaPublicKey(r);case su.Ed25519:return h3.ed25519.unmarshalEd25519PublicKey(r);case su.Secp256k1:return h3.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw h4(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 dm(e){return!!(e instanceof Uint8Array||aV(e))&&32===e.byteLength}(rb=sf||(sf={})).codec=()=>(null==z&&(z=(0,ao.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})),z),rb.encode=e=>(0,ao.LE)(e,rb.codec()),rb.decode=e=>(0,ao.C6)(e,rb.codec()),(rw=sg||(sg={})).codec=()=>(null==G&&(G=(0,ao.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),sf.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t)=>{let r={identityKey:(0,aa.u)(0),identitySig:(0,aa.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=sf.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),G),rw.encode=e=>(0,ao.LE)(e,rw.codec()),rw.decode=e=>(0,ao.C6)(e,rw.codec());class dy{n;bytes;view;constructor(e=0){this.n=e,this.bytes=(0,aa.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 db{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,aa.u)(32)}isEmptyKey(e){let t=this.createEmptyKey();return(0,aM.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,aa.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,aa.u)(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){let r=this.crypto.hashSHA256(new aK(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 dy}}initializeSymmetric(e){let t=(0,hr.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,aa.u)(0));{let t=(0,aa.u)(32);return t.set(e),t}}split(e){let[t,r]=this.crypto.getHKDF(e.ck,(0,aa.u)(0)),n=this.initializeKey(t),i=this.initializeKey(r);return{cs1:n,cs2:i}}writeMessageRegular(e,t){let r=this.encryptWithAd(e,(0,aa.u)(0),t),n=this.createEmptyKey(),i=(0,aa.u)(0);return{ne:n,ns:i,ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,(0,aa.u)(0),t.ciphertext)}}class dw extends db{initializeInitiator(e,t,r,n){let i=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");this.mixHash(i,e);let s=(0,aa.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,aa.u)(32);return{ss:i,s:t,rs:r,psk:n,re:s}}writeMessageA(e,t,r){let n=(0,aa.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 dm(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(dm(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&&dm(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&&dm(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,aa.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,aa.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 dE(e,t){t.enabled&&l0&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${(0,ho.B)(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${(0,ho.B)(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function dv(e,t){t.enabled&&l0&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${(0,ho.B)(e.subarray(),"hex")}`)}class dS{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 dw(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&&l0&&(t(`LOCAL_STATIC_PUBLIC_KEY ${(0,ho.B)(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${(0,ho.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,aa.u)(0));await this.connection.write(new aK(e.ne,e.ciphertext)),this.log.trace("Stage 0 - Initiator finished sending first message."),dE(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,aa.u)(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new u8("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),dv(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 u8("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),dv(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&l0&&t(`REMOTE_STATIC_PUBLIC_KEY ${(0,ho.B)(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{let e=sg.decode(n);this.remotePeer=this.remotePeer||await dp(e),await dg(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new u6(`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 aK(e.ne,e.ns,e.ciphertext)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),dE(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 aK(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,aa.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 u8("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{let e=sg.decode(t);this.remotePeer=this.remotePeer||await dp(e),await dg(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new u6(`Error occurred while verifying signed payload: ${e.message}`)}}e=this.session,(t=this.log).enabled&&l0&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${(0,ho.B)(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${(0,ho.B)(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){let r=this.getCS(t);return this.xx.encryptWithAd(r,(0,aa.u)(0),e)}decrypt(e,t,r){let n=this.getCS(t,!1);return this.xx.decryptWithAd(n,(0,aa.u)(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new u8("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 dA{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??u2,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,aa.u)(0)}async secureOutbound(e,t,r){let n=lQ(t,{lengthEncoder:u3,lengthDecoder:u4,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=lQ(t,{lengthEncoder:u3,lengthDecoder:u4,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 dh(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 dS(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=lZ(),t=lZ();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),o=e.unwrap();return await a0(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 aK(u3(i.byteLength),i)}}),o,e=>aj(e,{lengthDecoder:u4}),(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 dI=Symbol.for("@libp2p/peer-discovery");class dT{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 dR=new dT;parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var d_=r(8273);function dk(e){return!!function(e){if(!(e.length>15))return dR.new(e).parseWith(()=>dR.readIPv4Addr())}(e)}function dC(e){return!!function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return dR.new(e).parseWith(()=>dR.readIPv6Addr())}(e)}function dB(e){return!!function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return dR.new(e).parseWith(()=>dR.readIPAddr())}(e)}let dD=function(e){let t=0;if(dk(e=e.toString().trim())){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(e=>{r[t++]=255&parseInt(e,10)}),r}if(dC(e)){let r;let n=e.split(":",8);for(r=0;r<n.length;r++){let e;let t=dk(n[r]);t&&(e=dD(n[r]),n[r]=(0,ho.B)(e.slice(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,(0,ho.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")},dP=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""},dN={},dL={};function dx(e){if("number"==typeof e){if(null!=dL[e])return dL[e];throw Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=dN[e])return dN[e];throw Error(`no protocol with name: ${e}`)}throw Error(`invalid protocol id type: ${typeof e}`)}function dO(e,t){let r=dx(e);switch(r.code){case 4:case 41:return function(e){let t=dP(e,0,e.length);if(null==t)throw Error("ipBuff is required");if(!dB(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 function(e){let t=ax.Jx(e);if((e=e.slice(ax.P$(t))).length!==t)throw Error("inconsistent lengths");return(0,ho.B)(e)}(t);case 6:case 273:case 33:case 132:return dK(t).toString();case 421:return function(e){let t=ax.Jx(e),r=e.slice(ax.P$(t));if(r.length!==t)throw Error("inconsistent lengths");return(0,ho.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,ho.B)(t,"base32"),i=dK(r);return`${n}:${i}`}(t);case 466:return function(e){let t=ax.Jx(e),r=e.slice(ax.P$(t));if(r.length!==t)throw Error("inconsistent lengths");return"u"+(0,ho.B)(r,"base64url")}(t);default:return(0,ho.B)(t,"base16")}}function dM(e,t){let r=dx(e);switch(r.code){case 4:case 41:return function(e){if(!dB(e))throw Error("invalid ip address");return dD(e)}(t);case 42:case 53:case 54:case 55:case 56:case 400:case 449:case 777:return function(e){let t=(0,hr.m)(e),r=Uint8Array.from(ax.cv(t.length));return aO([r,t],r.length+t.length)}(t);case 6:case 273:case 33:case 132:return dV(parseInt(t,10));case 421:return function(e){let t;t="Q"===e[0]||"1"===e[0]?de.Jx(hn.base58btc.decode(`z${e}`)).bytes:h7.k0.parse(e).multihash.bytes;let r=Uint8Array.from(ax.cv(t.length));return aO([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=d_.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=dV(n);return aO([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=d_.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=dV(n);return aO([r,i],r.length+i.length)}(t);case 466:return function(e){let t=dF.decode(e),r=Uint8Array.from(ax.cv(t.length));return aO([r,t],r.length+t.length)}(t);default:return(0,hr.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"],[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);dL[t.code]=t,dN[t.name]=t}),dx("ip4"),dx("ip6"),dx("ipcidr");let dU=Object.values(h9.gh).map(e=>e.decoder),dF=(j=dU[0].or(dU[1]),dU.slice(2).forEach(e=>j=j.or(e)),j);function dV(e){let t=new ArrayBuffer(2),r=new DataView(t);return r.setUint16(0,e),new Uint8Array(t)}function dK(e){let t=new DataView(e.buffer);return t.getUint16(e.byteOffset)}function dH(e){let t=[],r=[],n=null,i=0;for(;i<e.length;){let s=ax.Jx(e,i),o=ax.P$(s),a=dx(s),l=function(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{let e=ax.Jx(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ax.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 dG("Invalid address Uint8Array: "+(0,ho.B)(e,"base16"));t.push([s,c]);let u=dO(s,c);if(r.push([s,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:dq(r),tuples:t,stringTuples:r,path:n}}function dq(e){let t=[];return e.map(e=>{let r=dx(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null}),dz(t.join("/"))}function d$(e){return aO(e.map(e=>{let t=dx(e[0]),r=Uint8Array.from(ax.cv(t.code));return e.length>1&&null!=e[1]&&(r=aO([r,e[1]])),r}))}function dz(e){return"/"+e.trim().split("/").filter(e=>e).join("/")}function dG(e){return Error("Error parsing address: "+e)}let dj=Symbol.for("nodejs.util.inspect.custom"),dW=Symbol.for("@multiformats/js-multiaddr/multiaddr"),dY=[dx("dns").code,dx("dns4").code,dx("dns6").code,dx("dnsaddr").code];class dX{bytes;#t;#r;#n;#i;[dW]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=dH(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=dz(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=dx(o);if(0===a.size){t.push([a.code]),r.push([a.code]);continue}if(++s>=i.length)throw dG("invalid address: "+e);if(!0===a.path){n=dz(i.slice(s).join("/")),t.push([a.code,dM(a.code,n)]),r.push([a.code,n]);break}let l=dM(a.code,i[s]);t.push([a.code,l]),r.push([a.code,dO(a.code,l)])}return{string:dq(r),bytes:d$(t),tuples:t,stringTuples:r,path:n}}(e)}else{var r;if(r=e,r?.[dW])t=dH(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=dx("tcp"),o=dx("udp"),a=dx("ip4"),l=dx("ip6"),c=dx("dns6"),u=dx("ip6zone");for(let[h,d]of this.stringTuples())h===u.code&&(i=`%${d??""}`),dY.includes(h)&&(t=s.name,n=443,r=`${d??""}${i}`,e=h===c.code?6:4),(h===s.code||h===o.code)&&(t=dx(h).name,n=parseInt(d??"")),(h===a.code||h===l.code)&&(t=dx(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({},dx(e)))}protoCodes(){return this.#r.map(([e])=>e)}protoNames(){return this.#r.map(([e])=>dx(e).name)}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new dX(e),new dX(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 dX(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 dX(d$(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([t,r])=>{t===dN.p2p.code&&e.push([t,r]),t===dN["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,ho.B)(hn.base58btc.decode(`z${e}`),"base58btc");return(0,ho.B)(h7.k0.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#i}equals(e){return(0,aM.f)(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(e=>e.resolvable);if(null==t)return[this];let r=dJ.get(t.name);if(null==r)throw new u9(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");let n=await r(this,e);return n.map(e=>dQ(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)}[dj](){return`Multiaddr(${this.#t})`}}let dJ=new Map;function dQ(e){return new dX(e)}let dZ=pE("dns4"),d0=pE("dns6"),d1=pE("dnsaddr"),d2=pw(pE("dns"),d1,dZ,d0),d3=pw(pE("ip4"),pE("ip6")),d4=pw(pb(d3,pE("tcp")),pb(d2,pE("tcp"))),d6=pb(d3,pE("udp")),d8=pb(d6,pE("utp")),d5=pb(d6,pE("quic")),d9=pb(d6,pE("quic-v1")),d7=pw(pb(d4,pE("ws")),pb(d2,pE("ws"))),pe=pw(pb(d7,pE("p2p")),d7),pt=pw(pb(d4,pE("wss")),pb(d2,pE("wss")),pb(d4,pE("tls"),pE("ws")),pb(d2,pE("tls"),pE("ws"))),pr=pw(pb(pt,pE("p2p")),pt),pn=pw(pb(d4,pE("http")),pb(d3,pE("http")),pb(d2,pE("http"))),pi=pw(pb(d4,pE("https")),pb(d3,pE("https")),pb(d2,pE("https"))),ps=pb(d6,pE("webrtc-direct"),pE("certhash")),po=pw(pb(ps,pE("p2p")),ps),pa=pb(d9,pE("webtransport"),pE("certhash"),pE("certhash")),pl=pw(pb(pa,pE("p2p")),pa),pc=pw(pb(pe,pE("p2p-webrtc-star"),pE("p2p")),pb(pr,pE("p2p-webrtc-star"),pE("p2p")),pb(pe,pE("p2p-webrtc-star")),pb(pr,pE("p2p-webrtc-star")));pw(pb(pe,pE("p2p-websocket-star"),pE("p2p")),pb(pr,pE("p2p-websocket-star"),pE("p2p")),pb(pe,pE("p2p-websocket-star")),pb(pr,pE("p2p-websocket-star")));let pu=pw(pb(pn,pE("p2p-webrtc-direct"),pE("p2p")),pb(pi,pE("p2p-webrtc-direct"),pE("p2p")),pb(pn,pE("p2p-webrtc-direct")),pb(pi,pE("p2p-webrtc-direct"))),ph=pw(d7,pt,pn,pi,pc,pu,d4,d8,d5,d2,po,pl);pw(pb(ph,pE("p2p-stardust"),pE("p2p")),pb(ph,pE("p2p-stardust")));let pd=pw(pb(ph,pE("p2p")),pc,pu,po,pl,pE("p2p")),pp=pw(pb(pd,pE("p2p-circuit"),pd),pb(pd,pE("p2p-circuit")),pb(pE("p2p-circuit"),pd),pb(ph,pE("p2p-circuit")),pb(pE("p2p-circuit"),ph),pE("p2p-circuit")),pf=()=>pw(pb(pp,pf),pp),pg=pf(),pm=pw(pb(pg,pd,pg),pb(pd,pg),pb(pg,pd),pg,pd);function py(e){return function(t){let r;try{r=dQ(t)}catch(e){return!1}let n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function pb(...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:py(t),partialMatch:t}}function pw(...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:py(t),partialMatch:t};return r}function pE(e){return{toString:function(){return e},matches:function(t){let r;try{r=dQ(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}}}pw(pb(pg,pE("webrtc"),pE("p2p")),pb(pg,pE("webrtc")),pb(ph,pE("webrtc"),pE("p2p")),pb(ph,pE("webrtc")),pE("webrtc"));class pv extends lM{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(!pm.matches(r)){this.log.error("Invalid multiaddr");continue}let e=dQ(r),t=e.getPeerId();if(null==t){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let n={id:dl(t),multiaddrs:[e]};this.list.push(n)}this._init=t}[dI]=this;[Symbol.toStringTag]="@libp2p/bootstrap";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 pS=Uint8Array.from([3,1]);(rv=(rE=sm||(sm={})).AddressInfo||(rE.AddressInfo={})).codec=()=>(null==Y&&(Y=(0,ao.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})),Y),rv.encode=e=>(0,ao.LE)(e,rv.codec()),rv.decode=e=>(0,ao.C6)(e,rv.codec()),rE.codec=()=>(null==W&&(W=(0,ao.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),rE.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(rE.AddressInfo.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r})),W),rE.encode=e=>(0,ao.LE)(e,rE.codec()),rE.decode=e=>(0,ao.C6)(e,rE.codec());class pA{static createFromProtobuf=e=>{let t=sm.decode(e),r=dc(t.peerId),n=(t.addresses??[]).map(e=>dQ(e.multiaddr)),i=t.seq;return new pA({peerId:r,multiaddrs:n,seqNumber:i})};static DOMAIN="libp2p-peer-record";static CODEC=pS;peerId;multiaddrs;seqNumber;domain=pA.DOMAIN;codec=pA.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=sm.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!!(e instanceof pA&&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 pI(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}function pT(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 pR={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 p_={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};async function pk(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=pR.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,hr.m)(l)),0===l.length){c=await a.subtle.importKey("jwk",p_,{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",p_,{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 aO([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,hr.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",p_,{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 hh.base64.encode(n)}(rS=sy||(sy={})).RSA="RSA",rS.Ed25519="Ed25519",rS.Secp256k1="Secp256k1",(rA=sb||(sb={}))[rA.RSA=0]="RSA",rA[rA.Ed25519=1]="Ed25519",rA[rA.Secp256k1=2]="Secp256k1",(sy||(sy={})).codec=()=>(0,ao.Ji)(sb),(rI=sw||(sw={})).codec=()=>(null==X&&(X=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),sy.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=sy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),X),rI.encode=e=>(0,ao.LE)(e,rI.codec()),rI.decode=e=>(0,ao.C6)(e,rI.codec()),(rT=sE||(sE={})).codec=()=>(null==J&&(J=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),sy.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=sy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r})),J),rT.encode=e=>(0,ao.LE)(e,rT.codec()),rT.decode=e=>(0,ao.C6)(e,rT.codec());class pC{_key;constructor(e){this._key=px(e,32)}verify(e,t){var r;return r=this._key,uU.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}marshal(){return this._key}get bytes(){return sw.encode({Type:sy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return pI(e)?e.then(({bytes:e})=>e):e.bytes}}class pB{_key;_publicKey;constructor(e,t){this._key=px(e,64),this._publicKey=px(t,32)}sign(e){return function(e,t){let r=e.subarray(0,32);return uU.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new pC(this._publicKey)}marshal(){return this._key}get bytes(){return sE.encode({Type:sy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}async hash(){let e;let t=hs.sha256.digest(this.bytes);return pI(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let e=hi.identity.digest(this.public.bytes);return hn.base58btc.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return pk(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function pD(e){if(e.length>64){e=px(e,96);let t=e.subarray(0,64),r=e.subarray(64,e.length);return new pB(t,r)}e=px(e,64);let t=e.subarray(0,64),r=e.subarray(32);return new pB(t,r)}function pP(e){return new pC(e=px(e,32))}async function pN(){let{privateKey:e,publicKey:t}=function(){let e=uU.utils.randomPrivateKey(),t=uU.getPublicKey(e),r=pT(e,t);return{privateKey:r,publicKey:t}}();return new pB(e,t)}async function pL(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=uU.getPublicKey(e),r=pT(e,t);return{privateKey:r,publicKey:t}}(e);return new pB(t,r)}function px(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new u9(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function pO(e){let t=await pR.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 pV(t);return{privateKey:r[0],publicKey:r[1]}}async function pM(e){let t=await pR.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),r=[t,await pK(e)],n=await pV({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function pU(e,t){let r=await pR.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await pR.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function pF(e,t,r){let n=await pR.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return pR.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function pV(e){if(null==e.privateKey||null==e.publicKey)throw new u9("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([pR.get().subtle.exportKey("jwk",e.privateKey),pR.get().subtle.exportKey("jwk",e.publicKey)])}async function pK(e){return pR.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 pH(e){if("RSA"!==e.kty)throw new u9("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new u9("invalid key modulus","ERR_INVALID_KEY_MODULUS");let t=(0,hr.m)(e.n,"base64url");return 8*t.length}async function pq(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,uJ.vp)(e);let i=(0,cB.U5)({dkLen:32,asyncTick:10},n),{c:s,dkLen:o,asyncTick:a}=i;if((0,uJ.Rx)(s),(0,uJ.Rx)(o),(0,uJ.Rx)(a),s<1)throw Error("PBKDF2: iterations (c) should be >= 1");let l=(0,cB.O0)(t),c=(0,cB.O0)(r),u=new Uint8Array(o),h=uZ.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,cB.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,cB.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 p$=r(3033);function pz(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 pG(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 pj(...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 pW(){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=pz(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=pz(s,8);return o-n}function pY(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 pX(){if("undefined"==typeof BigInt)throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function pJ(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 pQ(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 pZ{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return pJ(this.items)}}let p0=[new Uint8Array([1])],p1="0123456789",p2=new ArrayBuffer(0),p3=new Uint8Array(0),p4="EndOfContent",p6="OCTET STRING",p8="BIT STRING";function p5(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?p$.vJ.toUint8Array(r.valueHex):p3}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(!pQ(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",p2)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:p$.ep.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class p9{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=p3}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=p$.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:p$.ep.ToHex(this.valueBeforeDecodeView)}}}p9.NAME="baseBlock";class p7 extends p9{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'")}}p7.NAME="valueBlock";class fe extends p5(p9){constructor({idBlock:e={}}={}){var t,r,n,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?p$.vJ.toUint8Array(e.valueHex):p3,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",p2}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=pG(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=p$.vJ.toUint8Array(e);if(!pQ(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=pz(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}}}fe.NAME="identificationBlock";class ft extends p9{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=p$.vJ.toUint8Array(e);if(!pQ(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=pz(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=pG(this.length,8);if(n.byteLength>127)return this.error="Too big length",p2;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}}}ft.NAME="lengthBlock";let fr={};class fn extends p9{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 fe(n),this.lenBlock=new ft(n),this.valueBlock=i?new i(n):new p7(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 pZ;t||function e(t){if(t instanceof fr.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?p2: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():p$.ep.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${p$.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)}}fn.NAME="BaseBlock";class fi extends fn{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}'`}}fi.NAME="BaseStringBlock";class fs extends p5(p7){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}fs.NAME="PrimitiveValueBlock";class fo extends fn{constructor(e={}){super(e,fs),this.idBlock.isConstructed=!1}}function fa(e,t=0,r=e.length){let n=t,i=new fn({},p7),s=new p9;if(!pQ(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=fn;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=fr.EndOfContent;break;case 1:l=fr.Boolean;break;case 2:l=fr.Integer;break;case 3:l=fr.BitString;break;case 4:l=fr.OctetString;break;case 5:l=fr.Null;break;case 6:l=fr.ObjectIdentifier;break;case 10:l=fr.Enumerated;break;case 12:l=fr.Utf8String;break;case 13:l=fr.RelativeObjectIdentifier;break;case 14:l=fr.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=fr.Sequence;break;case 17:l=fr.Set;break;case 18:l=fr.NumericString;break;case 19:l=fr.PrintableString;break;case 20:l=fr.TeletexString;break;case 21:l=fr.VideotexString;break;case 22:l=fr.IA5String;break;case 23:l=fr.UTCTime;break;case 24:l=fr.GeneralizedTime;break;case 25:l=fr.GraphicString;break;case 26:l=fr.VisibleString;break;case 27:l=fr.GeneralString;break;case 28:l=fr.UniversalString;break;case 29:l=fr.CharacterString;break;case 30:l=fr.BmpString;break;case 31:l=fr.DATE;break;case 32:l=fr.TimeOfDay;break;case 33:l=fr.DateTime;break;case 34:l=fr.Duration;break;default:{let e=i.idBlock.isConstructed?new fr.Constructed:new fr.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else l=i.idBlock.isConstructed?fr.Constructed:fr.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 fl(e){if(!e.byteLength){let e=new fn({},p7);return e.error="Input buffer has zero length",{offset:-1,result:e}}return fa(p$.vJ.toUint8Array(e).slice(),0,e.byteLength)}fr.Primitive=fo,fo.NAME="PRIMITIVE";class fc extends p7{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){var n,i;let s=p$.vJ.toUint8Array(e);if(!pQ(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=fa(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===p4)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===p4?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){let r=t||new pZ;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?p2:r.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}}fc.NAME="ConstructedValueBlock";class fu extends fn{constructor(e={}){super(e,fc),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} :`}}fr.Constructed=fu,fu.NAME="CONSTRUCTED";class fh extends p7{fromBER(e,t,r){return t}toBER(e){return p2}}fh.override="EndOfContentValueBlock";class fd extends fn{constructor(e={}){super(e,fh),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}fr.EndOfContent=fd,fd.NAME=p4;class fp extends fn{constructor(e={}){super(e,p7),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}`}}fr.Null=fp,fp.NAME="NULL";class ff extends p5(p7){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=p$.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=p$.vJ.toUint8Array(e);return pQ(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,pW.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ff.NAME="BooleanValueBlock";class fg extends fn{constructor(e={}){super(e,ff),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}`}}fr.Boolean=fg,fg.NAME="BOOLEAN";class fm extends p5(fc){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=fc.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===p4){if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;break}if(t!==p6)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?fc.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}fm.NAME="OctetStringValueBlock";class fy extends fn{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},fm),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=fa(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?fu.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${p$.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 fy&&e.push(t.valueBlock.valueHexView);return p$.vJ.concat(e)}}fr.OctetString=fy,fy.NAME=p6;class fb extends p5(fc){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=fc.prototype.fromBER.call(this,e,t,r)))return n;for(let e of this.value){let t=e.constructor.NAME;if(t===p4){if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1;break}if(t!==p8)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=p$.vJ.toUint8Array(e);if(!pQ(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=fa(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 fc.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return p2;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}}}fb.NAME="BitStringValueBlock";class fw extends fn{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},fb),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 fu.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 fE(e){if(e>=p0.length)for(let t=p0.length;t<=e;t++){let e=new Uint8Array([0]),r=p0[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=pj(e,r)),p0.push(r)}return p0[e]}fr.BitString=fw,fw.NAME=p8;class fv extends p5(p7){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=pW.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=pG(e,8,n),s=new Uint8Array(i);return s[0]|=128,i}let i=pG(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()}(fE(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=pj(new Uint8Array([c%10]),s):s[o-h]=c%10;return r[0]>0&&(s=pj(r,s)),s}(r,fE(n))),n++,e>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(s+=p1.charAt(r[e]));return!1===o&&(s+=p1.charAt(0)),s}}fv.NAME="IntegerValueBlock",Object.defineProperty(fv.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class fS extends fn{constructor(e={}){super(e,fv),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return pX(),BigInt(this.valueBlock.toString())}static fromBigInt(e){pX();let t=BigInt(e),r=new pZ,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(p$.ep.FromHex(n));if(t<0){let e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;let n=BigInt(`0x${p$.ep.ToHex(e)}`),s=p$.vJ.toUint8Array(p$.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 fS({valueHex:r.final()});return s}convertToDER(){let e=new fS({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new fS({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}fr.Integer=fS,fS.NAME="INTEGER";class fA extends fS{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}fr.Enumerated=fA,fA.NAME="ENUMERATED";class fI extends p5(p7){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=p$.vJ.toUint8Array(e);if(!pQ(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=pz(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){pX();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=pG(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",p2;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=p$.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}}}fI.NAME="sidBlock";class fT extends p7{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 fI;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,p2;t.push(n)}return pJ(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 fI;if(n>Number.MAX_SAFE_INTEGER){pX();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}}fT.NAME="ObjectIdentifierValueBlock";class fR extends fn{constructor(e={}){super(e,fT),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()}}}fr.ObjectIdentifier=fR,fR.NAME="OBJECT IDENTIFIER";class f_ extends p5(p9){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;let n=p$.vJ.toUint8Array(e);if(!pQ(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=pz(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=pG(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",p2;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?p$.ep.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}f_.NAME="relativeSidBlock";class fk extends p7{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 f_;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,p2;r.push(n)}return pJ(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 f_;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}}fk.NAME="RelativeObjectIdentifierValueBlock";class fC extends fn{constructor(e={}){super(e,fk),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()}}}fr.RelativeObjectIdentifier=fC,fC.NAME="RelativeObjectIdentifier";class fB extends fu{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}fr.Sequence=fB,fB.NAME="SEQUENCE";class fD extends fu{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}fr.Set=fD,fD.NAME="SET";class fP extends p5(p7){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=""}toJSON(){return{...super.toJSON(),value:this.value}}}fP.NAME="StringValueBlock";class fN extends fP{}fN.NAME="SimpleStringValueBlock";class fL extends fi{constructor({...e}={}){super(e,fN)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,p$.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}}fL.NAME="SIMPLE STRING";class fx extends fL{fromBuffer(e){this.valueBlock.valueHexView=p$.vJ.toUint8Array(e);try{this.valueBlock.value=p$.ep.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=p$.ep.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(p$.ep.FromUtf8String(e)),this.valueBlock.value=e}}fx.NAME="Utf8StringValueBlock";class fO extends fx{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}fr.Utf8String=fO,fO.NAME="UTF8String";class fM extends fL{fromBuffer(e){this.valueBlock.value=p$.ep.ToUtf16String(e),this.valueBlock.valueHexView=p$.vJ.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(p$.ep.FromUtf16String(e))}}fM.NAME="BmpStringValueBlock";class fU extends fM{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}fr.BmpString=fU,fU.NAME="BMPString";class fF extends fL{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=pG(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}}fF.NAME="UniversalStringValueBlock";class fV extends fF{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}fr.UniversalString=fV,fV.NAME="UniversalString";class fK extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}fr.NumericString=fK,fK.NAME="NumericString";class fH extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}fr.PrintableString=fH,fH.NAME="PrintableString";class fq extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}fr.TeletexString=fq,fq.NAME="TeletexString";class f$ extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}fr.VideotexString=f$,f$.NAME="VideotexString";class fz extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}fr.IA5String=fz,fz.NAME="IA5String";class fG extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}fr.GraphicString=fG,fG.NAME="GraphicString";class fj extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}fr.VisibleString=fj,fj.NAME="VisibleString";class fW extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}fr.GeneralString=fW,fW.NAME="GeneralString";class fY extends fL{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}fr.CharacterString=fY,fY.NAME="CharacterString";class fX extends fj{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,p$.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]=pY(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=pY(this.month,2),e[2]=pY(this.day,2),e[3]=pY(this.hour,2),e[4]=pY(this.minute,2),e[5]=pY(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}}}fr.UTCTime=fX,fX.NAME="UTCTime";class fJ extends fX{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(pY(this.year,4)),e.push(pY(this.month,2)),e.push(pY(this.day,2)),e.push(pY(this.hour,2)),e.push(pY(this.minute,2)),e.push(pY(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(pY(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}fr.GeneralizedTime=fJ,fJ.NAME="GeneralizedTime";class fQ extends fO{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}fr.DATE=fQ,fQ.NAME="DATE";class fZ extends fO{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}fr.TimeOfDay=fZ,fZ.NAME="TimeOfDay";class f0 extends fO{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}fr.DateTime=f0,f0.NAME="DateTime";class f1 extends fO{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}fr.Duration=f1,f1.NAME="Duration";class f2 extends fO{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}function f3(e){if(isNaN(e)||e<=0)throw new u9("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return(0,cB.O6)(e)}function f4(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 f6(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 f8(e,t){let r=pR.get(),n=new fB({value:[new fS({value:0}),new fB({value:[new fR({value:"1.2.840.113549.1.1.1"}),new fp]}),new fy({valueHex:e.marshal()})]}),i=n.toBER(),s=new Uint8Array(i,0,i.byteLength),o=f3(16),a=await pq(cO,t,o,{c:1e4,dkLen:32}),l=f3(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 fB({value:[new fy({valueHex:o}),new fS({value:1e4}),new fS({value:32}),new fB({value:[new fR({value:"1.2.840.113549.2.11"}),new fp]})]}),d=new fB({value:[new fR({value:"1.2.840.113549.1.5.13"}),new fB({value:[new fB({value:[new fR({value:"1.2.840.113549.1.5.12"}),h]}),new fB({value:[new fR({value:"2.16.840.1.101.3.4.1.42"}),new fy({valueHex:l})]})]})]}),p=new fB({value:[d,new fy({valueHex:u})]}),f=p.toBER(),g=new Uint8Array(f,0,f.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...(0,ho.B)(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}fr.TIME=f2,f2.NAME="TIME";let f5=8192;class f9{_key;constructor(e){this._key=e}verify(e,t){return pF(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new u9("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new fB({value:[new fB({value:[new fR({value:"1.2.840.113549.1.1.1"}),new fp]}),new fw({valueHex:new fB({value:[fS.fromBigInt(f6((0,hr.m)(e.n,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.e,"base64url")))]}).toBER()})]}),r=t.toBER();return new Uint8Array(r,0,r.byteLength)}(this._key)}get bytes(){return sw.encode({Type:sy.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return pI(e)?e.then(({bytes:e})=>e):e.bytes}}class f7{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return f3(16)}sign(e){return pU(this._key,e)}get public(){if(null==this._publicKey)throw new u9("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new f9(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 u9("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new fB({value:[new fS({value:0}),fS.fromBigInt(f6((0,hr.m)(e.n,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.e,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.d,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.p,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.q,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.dp,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.dq,"base64url"))),fS.fromBigInt(f6((0,hr.m)(e.qi,"base64url")))]}),r=t.toBER();return new Uint8Array(r,0,r.byteLength)}(this._key)}get bytes(){return sE.encode({Type:sy.RSA,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return pI(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,ho.B)(e,"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return f8(this,e);if("libp2p-key"===t)return pk(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function ge(e){let t=function(e){let{result:t}=fl(e),r=t.valueBlock.value,n={n:(0,ho.B)(f4(r[1].toBigInt()),"base64url"),e:(0,ho.B)(f4(r[2].toBigInt()),"base64url"),d:(0,ho.B)(f4(r[3].toBigInt()),"base64url"),p:(0,ho.B)(f4(r[4].toBigInt()),"base64url"),q:(0,ho.B)(f4(r[5].toBigInt()),"base64url"),dp:(0,ho.B)(f4(r[6].toBigInt()),"base64url"),dq:(0,ho.B)(f4(r[7].toBigInt()),"base64url"),qi:(0,ho.B)(f4(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"};return n}(e);if(pH(t)>f5)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await pM(t);return new f7(r.privateKey,r.publicKey)}function gt(e){let t=function(e){let{result:t}=fl(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:(0,ho.B)(f4(r[0].toBigInt()),"base64url"),e:(0,ho.B)(f4(r[1].toBigInt()),"base64url")}}(e);if(pH(t)>f5)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new f9(t)}async function gr(e){if(pH(e)>f5)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await pM(e);return new f7(t.privateKey,t.publicKey)}async function gn(e){if(e>f5)throw new u9("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await pO(e);return new f7(t.privateKey,t.publicKey)}function gi(e){try{hX.ProjectivePoint.fromHex(e)}catch(e){throw new u9(String(e),"ERR_INVALID_PUBLIC_KEY")}}class gs{_key;constructor(e){gi(e),this._key=e}verify(e,t){return function(e,t,r){let n=hs.sha256.digest(r instanceof Uint8Array?r:r.subarray());if(pI(n))return n.then(({digest:r})=>hX.verify(t,r,e)).catch(e=>{throw new u9(String(e),"ERR_INVALID_INPUT")});try{return hX.verify(t,n.digest,e)}catch(e){throw new u9(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return function(e){let t=hX.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}get bytes(){return sw.encode({Type:sy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}async hash(){let e;let t=hs.sha256.digest(this.bytes);return pI(t)?{bytes:e}=await t:e=t.bytes,e}}class go{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return hX.getPublicKey(e,!0)}catch(e){throw new u9(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{hX.getPublicKey(e,!0)}catch(e){throw new u9(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),gi(this._publicKey)}sign(e){return function(e,t){let r=hs.sha256.digest(t instanceof Uint8Array?t:t.subarray());if(pI(r))return r.then(({digest:t})=>hX.sign(t,e).toDERRawBytes()).catch(e=>{throw new u9(String(e),"ERR_INVALID_INPUT")});try{return hX.sign(r.digest,e).toDERRawBytes()}catch(e){throw new u9(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new gs(this._publicKey)}marshal(){return this._key}get bytes(){return sE.encode({Type:sy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return(0,aM.f)(this.bytes,e.bytes)}hash(){let e=hs.sha256.digest(this.bytes);return pI(e)?e.then(({bytes:e})=>e):e.bytes}async id(){let e=await this.public.hash();return(0,ho.B)(e,"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return pk(this.bytes,e);throw new u9(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function ga(e){return new go(e)}function gl(e){return new gs(e)}async function gc(){let e=hX.utils.randomPrivateKey();return new go(e)}let gu={rsa:ai,ed25519:an,secp256k1:as};function gh(e){let t=Object.keys(gu).join(" / ");return new u9(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function gd(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return gu[e];throw gh(e)}async function gp(e,t){return gd(e).generateKeyPair(t??2048)}function gf(e){let t=sw.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case sy.RSA:return gu.rsa.unmarshalRsaPublicKey(r);case sy.Ed25519:return gu.ed25519.unmarshalEd25519PublicKey(r);case sy.Secp256k1:return gu.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw gh(t.Type??"unknown")}}function gg(e,t){return gd(t=(t??"rsa").toLowerCase()),e.bytes}async function gm(e){let t=sE.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case sy.RSA:return gu.rsa.unmarshalRsaPrivateKey(r);case sy.Ed25519:return gu.ed25519.unmarshalEd25519PrivateKey(r);case sy.Secp256k1:return gu.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw gh(t.Type??"RSA")}}let gy={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};(rR=sv||(sv={})).codec=()=>(null==Q&&(Q=(0,ao.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})),Q),rR.encode=e=>(0,ao.LE)(e,rR.codec()),rR.decode=e=>(0,ao.C6)(e,rR.codec());class gb{static createFromProtobuf=async e=>{let t=sv.decode(e),r=await du(t.publicKey);return new gb({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=gw(r,n,i),o=await gm(t.privateKey),a=await o.sign(s.subarray());return new gb({peerId:t,payloadType:n,payload:i,signature:a})};static openAndCertify=async(e,t)=>{let r=await gb.createFromProtobuf(e),n=await r.validate(t);if(!n)throw new u9("envelope signature is not valid for the given domain",gy.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=sv.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return(0,aM.f)(this.marshal(),e.marshal())}async validate(e){let t=gw(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw Error("Missing public key");let r=gf(this.peerId.publicKey);return r.verify(t.subarray(),this.signature)}}let gw=(e,t,r)=>{let n=(0,hr.m)(e),i=ax.cv(n.byteLength),s=ax.cv(t.length),o=ax.cv(r.length);return new aK(i,n,s,t,o,r)},gE=e=>e.toString().split("/").slice(1),gv=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),gS=e=>({match:t=>gv(t=>t===e).match(t),pattern:e}),gA=()=>({match:e=>gv(e=>"string"==typeof e).match(e),pattern:"{string}"}),gI=()=>({match:e=>gv(e=>!isNaN(parseInt(e))).match(e),pattern:"{number}"}),gT=()=>({match:e=>{if(e.length<2||"p2p"!==e[0]&&"ipfs"!==e[0]||!(e[1].startsWith("Q")||e[1].startsWith("1")))return!1;try{hn.base58btc.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),gR=()=>({match:e=>{if(e.length<2||"certhash"!==e[0])return!1;try{hh.base64url.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),g_=e=>({match:t=>{let r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),gk=(...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(", ")})`}),gC=(...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 gB(...e){function t(t){let r=gE(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 gD=gC(gS("dns4"),gA()),gP=gC(gS("dns6"),gA()),gN=gC(gS("dnsaddr"),gA()),gL=gC(gS("dns"),gA());gB(gD),gB(gP),gB(gN),gB(gk(gL,gN,gD,gP));let gx=gC(gS("ip4"),gv(dk)),gO=gC(gS("ip6"),gv(dC)),gM=gk(gx,gO),gU=gk(gM,gL,gD,gP,gN),gF=gB(gU);gB(gx),gB(gO),gB(gM);let gV=gC(gU,gS("tcp"),gI()),gK=gC(gU,gS("udp"),gI()),gH=gk(gV,gK);gB(gV),gB(gK);let gq=gC(gK,gS("quic")),g$=gC(gK,gS("quic-v1")),gz=gk(gq,g$);gB(gq),gB(g$);let gG=gk(gU,gV,gK,gq,g$),gj=gk(gC(gG,gS("ws"),g_(gT())));gB(gj);let gW=gk(gC(gG,gS("wss"),g_(gT())),gC(gG,gS("tls"),gS("ws"),g_(gT())));gB(gW);let gY=gC(gH,gS("webrtc-direct"),gR(),g_(gR()),g_(gT()));gB(gY);let gX=gC(g$,gS("webtransport"),gR(),gR(),g_(gT()));gB(gX);let gJ=gk(gj,gW,gC(gV,g_(gT())),gC(gz,g_(gT())),gC(gU,g_(gT())),gY,gX,gT());gB(gJ);let gQ=gC(gJ,gS("p2p-circuit"),gT()),gZ=gB(gQ),g0=gk(gC(gJ,gS("p2p-circuit"),gS("webrtc"),gT()),gC(gJ,gS("webrtc"),g_(gT())),gS("webrtc"));gB(g0);let g1=gk(gC(gU,gS("tcp"),gI(),gS("http"),g_(gT())),gC(gU,gS("http"),g_(gT())));gB(g1);let g2=gk(gC(gU,gS("tcp"),gk(gC(gS("443"),gS("http")),gC(gI(),gS("https"))),g_(gT())),gC(gU,gS("tls"),gS("http"),g_(gT())),gC(gU,gS("https"),g_(gT())));function g3(e,t){let r=lQ(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}gB(g2);var g4=r(9598);let g6="object"==typeof window&&"object"==typeof document&&9===document.nodeType,g8=g4(),g5=g6&&!g8,g9=g8&&!g6,g7=g8&&g6,me=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!g8,mt="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 mr="undefined"!=typeof navigator&&"ReactNative"===navigator.product;(r_=sS||(sS={})).codec=()=>(null==Z&&(Z=(0,ao.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})),Z),r_.encode=e=>(0,ao.LE)(e,r_.codec()),r_.decode=e=>(0,ao.C6)(e,r_.codec());let mn={protocolPrefix:"ipfs",timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0};class mi{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??mn.protocolPrefix}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??mn.protocolPrefix}/id/push/1.0.0`,this.timeout=t.timeout??mn.timeout,this.maxInboundStreams=t.maxInboundStreams??mn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??mn.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??mn.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??mn.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??mn.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??mn.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??mn.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??mn.protocolPrefix}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??mn.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}`&&(me||g9?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(g5||mt||g7||mr)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:(0,hr.m)(this.host.agentVersion),ProtocolVersion:(0,hr.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(dx("p2p").code)),r=new pA({peerId:this.peerId,multiaddrs:t}),n=await gb.seal(r,this.peerId),i=this.registrar.getProtocols(),s=await this.peerStore.get(this.peerId),o=(0,ho.B)(s.metadata.get("AgentVersion")??(0,hr.m)(this.host.agentVersion)),a=(0,ho.B)(s.metadata.get("ProtocolVersion")??(0,hr.m)(this.host.protocolVersion)),l=e.map(async e=>{let r;let s=AbortSignal.timeout(this.timeout);lO(1/0,s);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:s,runOnTransientConnection:this.runOnTransientConnection});let l=g3(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(sS);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);lO(1/0,e),t={...t,signal:e}}try{r=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});let n=g3(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(sS),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 u9("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");let o=await du(n);if(!e.remotePeer.equals(o))throw new u9("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new u9("identified peer is our own peer id?","ERR_INVALID_PEER");let a=function(e){if(null!=e&&e.length>0)try{return dQ(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);lO(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(dx("p2p").code)),o=i.peerRecordEnvelope;if(s.length>0&&null==o){let e=new pA({peerId:this.peerId,multiaddrs:s}),t=await gb.seal(e,this.peerId);o=t.marshal().subarray()}let a=t.remoteAddr.bytes;gF.matches(t.remoteAddr)||(a=void 0);let l=g3(r).pb(sS);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=g3(r,{maxDataLength:this.maxIdentifyMessageSize??8192}).pb(sS),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 u9("message was null or undefined","ERR_INVALID_MESSAGE");let n={};if(t.listenAddrs.length>0&&(n.addresses=t.listenAddrs.map(e=>({isCertified:!1,multiaddr:dQ(e)}))),t.protocols.length>0&&(n.protocols=t.protocols),null!=t.publicKey){n.publicKey=t.publicKey;let r=await du(t.publicKey);if(!r.equals(e.remotePeer))throw new u9("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 gb.openAndCertify(s,pA.DOMAIN),a=pA.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new u9("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new u9("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 gb.createFromProtobuf(i.peerRecordEnvelope),t=pA.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,hr.m)(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=(0,hr.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=>dQ(e)),observedAddr:null==t.observedAddr?void 0:dQ(t.observedAddr),protocols:t.protocols,signedPeerRecord:r,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:i}),i}}function ms(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 mo=()=>{let e=Error("Delay aborted");return e.name="AbortError",e},ma=new WeakMap,ml=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:i}={})=>{let s,o,a;if(i?.aborted)return Promise.reject(mo());let l=e??clearTimeout,c=()=>{l(s),a(mo())},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}),ma.set(h,()=>{l(s),s=null,o()}),h}}();class mc{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 mu}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 u9("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 ml(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 mu{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)}}(rk=sA||(sA={}))[rk.NEW_STREAM=0]="NEW_STREAM",rk[rk.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",rk[rk.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",rk[rk.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",rk[rk.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",rk[rk.RESET_RECEIVER=5]="RESET_RECEIVER",rk[rk.RESET_INITIATOR=6]="RESET_INITIATOR";let mh=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),md=Object.freeze({NEW_STREAM:sA.NEW_STREAM,MESSAGE:sA.MESSAGE_INITIATOR,CLOSE:sA.CLOSE_INITIATOR,RESET:sA.RESET_INITIATOR}),mp=Object.freeze({MESSAGE:sA.MESSAGE_RECEIVER,CLOSE:sA.CLOSE_RECEIVER,RESET:sA.RESET_RECEIVER});class mf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=1048576,t=4194304){this._buffer=new aK,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===sA.NEW_STREAM||r===sA.MESSAGE_INITIATOR||r===sA.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}=mg(e),{value:n,offset:i}=mg(e,r),s=7&t;if(null==mh[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 mg(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 mm{_pool;_poolOffset;constructor(){this._pool=(0,aa.E)(10240),this._poolOffset=0}write(e,t){let r=this._pool,n=this._poolOffset;ax.cv(e.id<<3|e.type,r,n),n+=ax.P$(e.id<<3|e.type),(e.type===sA.NEW_STREAM||e.type===sA.MESSAGE_INITIATOR||e.type===sA.MESSAGE_RECEIVER)&&null!=e.data?(ax.cv(e.data.length,r,n),n+=ax.P$(e.data.length)):(ax.cv(0,r,n),n+=ax.P$(0));let i=r.subarray(this._poolOffset,n);10240-n<100?(this._pool=(0,aa.E)(10240),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===sA.NEW_STREAM||e.type===sA.MESSAGE_INITIATOR||e.type===sA.MESSAGE_RECEIVER)&&null!=e.data&&t.append(e.data)}}let my=new mm;async function*mb(e){for await(let t of e){let e=new aK;my.write(t,e),yield e}}function mw(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class mE{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=aW(),this.closed=aW(),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=aQ({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 u9(`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);mw(e)&&await e}let r=()=>{ms(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 aK(n):n;let e=this.sendData(n,t);mw(e)&&(this.sendingData=aW(),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 lj(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 lj(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await lj(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await lj(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();mw(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 u9("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 mv extends mE{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?md:mp,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:md.NEW_STREAM,data:new aK((0,hr.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 mS(e){let t={...e,type:`${mh[e.type]} (${e.type})`};return e.type===sA.NEW_STREAM&&(t.data=(0,ho.B)(e.data instanceof Uint8Array?e.data:e.data.subarray())),(e.type===sA.MESSAGE_INITIATOR||e.type===sA.MESSAGE_RECEIVER)&&(t.data=(0,ho.B)(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class mA{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=aQ({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=a0(this._source,e=>mb(e)),this.closeController=new AbortController,this.rateLimiter=new mc({points:t.disconnectThreshold??5,duration:1})}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 u9("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,mS(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 mv({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=()=>{ms(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{let t=new mf(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",mS(e)),e.type===sA.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:sA.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,ho.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,mh[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 sA.MESSAGE_INITIATOR:case sA.MESSAGE_RECEIVER:if(i.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===sA.MESSAGE_INITIATOR?sA.RESET_RECEIVER:sA.RESET_INITIATOR}),new u9("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");i.sourcePush(e.data);break;case sA.CLOSE_INITIATOR:case sA.CLOSE_RECEIVER:i.remoteCloseWrite();break;case sA.RESET_INITIATOR:case sA.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 mI{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new mA(this.components,{...e,...this._init})}}var mT=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 mR="ERR_WRONG_PING_ACK";class m_{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)}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();a0(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=f3(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 u9("ping timeout",he))},t.signal?.addEventListener("abort",o,{once:!0});let e=await a0([i],r,async e=>mT(e)),a=Date.now()-n;if(null==e)throw new u9(`Did not receive a ping ack after ${a}ms`,mR);if(!(0,aM.f)(i,e.subarray()))throw new u9(`Received wrong ping ack after ${a}ms`,mR);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 mk=Symbol.for("@libp2p/transport");(rC=sI||(sI={}))[rC.FATAL_ALL=0]="FATAL_ALL",rC[rC.NO_FATAL=1]="NO_FATAL";let mC=[dx("tcp").code,dx("dns").code,dx("dnsaddr").code,dx("dns4").code,dx("dns6").code];function mB(e){let t;try{t=dx("sni").code}catch(e){return null}for(let[r,n]of e)if(r===t&&void 0!==n)return n;return null}function mD(e){return e.some(([e,t])=>e===dx("tls").code)}function mP(e,t,r){let n=mN[dx(e).name];if(void 0===n)throw Error(`Can't interpret protocol ${dx(e).name}`);let i=n(t,r);return e===dx("ip6").code?`[${i}]`:i}let mN={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://${mP(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://${mP(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`${mP(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`${mP(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{let r=mD(t),n=mB(t);if(r&&null!==n)return`https://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=mP(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${r?"https://":"http://"}${s}`},tls:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return mP(r[0],r[1]??"",t)},sni:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");return mP(r[0],r[1]??"",t)},https:(e,t)=>{let r=t.pop();if(void 0===r)throw Error("Unexpected end of multiaddr");let n=mP(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{let r=mD(t),n=mB(t);if(r&&null!==n)return`wss://${n}`;let i=t.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=mP(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=mP(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`${mP(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`${mP(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`${mP(r[0],r[1]??"",t)}/p2p-webrtc-direct`}};var mL=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)})},mx=(e,t)=>{(t=t??{}).closeOnEnd=!1!==t.closeOnEnd;let r=async r=>{for await(let t of r){try{await mL(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},mO=r(5986);function mM(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&"number"==typeof e?.byteLength}var mU=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 mO.zN(({push:t,stop:r,fail:n})=>{let i=e=>{let r=null;"string"==typeof e.data&&(r=(0,hr.m)(e.data)),mM(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 mM(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})},mF=(e,t)=>{t=t??{};let r=mU(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:mx(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},mV=WebSocket;let mK={"http:":"ws:","https:":"wss:"};var mH=(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(mK))r.protocol===e&&(r.protocol=t);return r};function mq(e){return e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return pe.matches(t)||pr.matches(t)})}class m${log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[mk]=!0;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 u9("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 u5;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=aW(),s=function(e,t){let r="undefined"==typeof window?void 0:window.location;t=t??{};let n=mH(e,r),i=new mV(n.toString(),t.websocket);return mF(i,t)}(function(e,t){let r=dQ(e),n=r.stringTuples(),i=n.pop();if(void 0===i)throw Error("Unexpected end of multiaddr");let s=dx(i[0]),o=mN[s.name];if(null==o)throw Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return mC.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 u9(`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 u5),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})}filter(e){return(e=Array.isArray(e)?e:[e],this.init?.filter!=null)?this.init?.filter(e):g5||mt?e.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return pr.matches(t)}):mq(e)}}let mz="StrictSign",mG="StrictNoSign";(rB=sT||(sT={})).Accept="accept",rB.Ignore="ignore",rB.Reject="reject";let mj="/floodsub/1.0.0",mW="/meshsub/1.0.0",mY="/meshsub/1.1.0",mX={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};(rP=(rD=sR||(sR={})).SubOpts||(rD.SubOpts={})).codec=()=>(null==et&&(et=(0,ao.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})),et),rP.encode=e=>(0,ao.LE)(e,rP.codec()),rP.decode=(e,t)=>(0,ao.C6)(e,rP.codec(),t),(rN=rD.Message||(rD.Message={})).codec=()=>(null==er&&(er=(0,ao.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})),er),rN.encode=e=>(0,ao.LE)(e,rN.codec()),rN.decode=(e,t)=>(0,ao.C6)(e,rN.codec(),t),(rL=rD.ControlMessage||(rD.ControlMessage={})).codec=()=>(null==en&&(en=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.ihave)for(let r of e.ihave)t.uint32(10),rD.ControlIHave.codec().encode(r,t);if(null!=e.iwant)for(let r of e.iwant)t.uint32(18),rD.ControlIWant.codec().encode(r,t);if(null!=e.graft)for(let r of e.graft)t.uint32(26),rD.ControlGraft.codec().encode(r,t);if(null!=e.prune)for(let r of e.prune)t.uint32(34),rD.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 ao.sv('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");n.ihave.push(rD.ControlIHave.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.iwant!=null&&n.iwant.length===r.limits.iwant)throw new ao.sv('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");n.iwant.push(rD.ControlIWant.codec().decode(e,e.uint32()));break;case 3:if(r.limits?.graft!=null&&n.graft.length===r.limits.graft)throw new ao.sv('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");n.graft.push(rD.ControlGraft.codec().decode(e,e.uint32()));break;case 4:if(r.limits?.prune!=null&&n.prune.length===r.limits.prune)throw new ao.sv('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");n.prune.push(rD.ControlPrune.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return n})),en),rL.encode=e=>(0,ao.LE)(e,rL.codec()),rL.decode=(e,t)=>(0,ao.C6)(e,rL.codec(),t),(rx=rD.ControlIHave||(rD.ControlIHave={})).codec=()=>(null==ei&&(ei=(0,ao.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 ao.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})),ei),rx.encode=e=>(0,ao.LE)(e,rx.codec()),rx.decode=(e,t)=>(0,ao.C6)(e,rx.codec(),t),(rO=rD.ControlIWant||(rD.ControlIWant={})).codec=()=>(null==es&&(es=(0,ao.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 ao.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})),es),rO.encode=e=>(0,ao.LE)(e,rO.codec()),rO.decode=(e,t)=>(0,ao.C6)(e,rO.codec(),t),(rM=rD.ControlGraft||(rD.ControlGraft={})).codec=()=>(null==eo&&(eo=(0,ao.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})),eo),rM.encode=e=>(0,ao.LE)(e,rM.codec()),rM.decode=(e,t)=>(0,ao.C6)(e,rM.codec(),t),(rU=rD.ControlPrune||(rD.ControlPrune={})).codec=()=>(null==ea&&(ea=(0,ao.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),rD.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 ao.sv('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");n.peers.push(rD.PeerInfo.codec().decode(e,e.uint32()));break;case 3:n.backoff=e.uint64Number();break;default:e.skipType(7&t)}}return n})),ea),rU.encode=e=>(0,ao.LE)(e,rU.codec()),rU.decode=(e,t)=>(0,ao.C6)(e,rU.codec(),t),(rF=rD.PeerInfo||(rD.PeerInfo={})).codec=()=>(null==el&&(el=(0,ao.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})),el),rF.encode=e=>(0,ao.LE)(e,rF.codec()),rF.decode=(e,t)=>(0,ao.C6)(e,rF.codec(),t),rD.codec=()=>(null==ee&&(ee=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.subscriptions)for(let r of e.subscriptions)t.uint32(10),rD.SubOpts.codec().encode(r,t);if(null!=e.messages)for(let r of e.messages)t.uint32(18),rD.Message.codec().encode(r,t);null!=e.control&&(t.uint32(26),rD.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 ao.sv('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");n.subscriptions.push(rD.SubOpts.codec().decode(e,e.uint32()));break;case 2:if(r.limits?.messages!=null&&n.messages.length===r.limits.messages)throw new ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(rD.Message.codec().decode(e,e.uint32()));break;case 3:n.control=rD.ControlMessage.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return n})),ee),rD.encode=e=>(0,ao.LE)(e,rD.codec()),rD.decode=(e,t)=>(0,ao.C6)(e,rD.codec(),t);class mJ{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 mQ(e){switch(e){case sT.Ignore:return sC.Ignore;case sT.Reject:return sC.Reject;default:throw Error("Unreachable")}}(rV=s_||(s_={})).StrictSign="StrictSign",rV.StrictNoSign="StrictNoSign",(rK=sk||(sk={}))[rK.Signing=0]="Signing",rK[rK.Anonymous=1]="Anonymous",(rH=sC||(sC={})).Error="error",rH.Ignore="ignore",rH.Reject="reject",rH.Blacklisted="blacklisted",(rq=sB||(sB={})).InvalidSignature="invalid_signature",rq.InvalidSeqno="invalid_seqno",rq.InvalidPeerId="invalid_peerid",rq.SignaturePresent="signature_present",rq.SeqnoPresent="seqno_present",rq.FromPresent="from_present",rq.TransformFailed="transform_failed",(r$=sD||(sD={})).duplicate="duplicate",r$.invalid="invalid",r$.valid="valid",(rz=sP||(sP={})).forward="forward",rz.publish="publish",(rG=sN||(sN={})).Fanout="fanout",rG.Random="random",rG.Subscribed="subscribed",rG.Outbound="outbound",rG.NotEnough="not_enough",rG.Opportunistic="opportunistic",(rj=sL||(sL={})).Dc="disconnected",rj.BadScore="bad_score",rj.Prune="prune",rj.Excess="excess",(rW=sx||(sx={})).GraftBackoff="graft_backoff",rW.BrokenPromise="broken_promise",rW.MessageDeficit="message_deficit",rW.IPColocation="IP_colocation",(rY=sO||(sO={})).LowScore="low_score",rY.MaxIhave="max_ihave",rY.MaxIasked="max_iasked",(rX=sM||(sM={})).graylist="graylist",rX.publish="publish",rX.gossip="gossip",rX.mesh="mesh";let mZ="ERR_INVALID_PEER_SCORE_PARAMS",m0={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},m1={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},m2={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function m3(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 m4 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 m6(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 m8=r(2185);(rJ=sU||(sU={}))[rJ.unknown=0]="unknown",rJ[rJ.valid=1]="valid",rJ[rJ.invalid=2]="invalid",rJ[rJ.ignored=3]="ignored";class m5{records;queue;constructor(){this.records=new Map,this.queue=new m8}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:sU.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 m9{params;metrics;peerStats=new Map;peerIPs=new m4(()=>new Set);scoreCache=new Map;deliveryRecords=new m5;_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 u9("invalid topic weight; must be >= 0",mZ);if(0===e.timeInMeshQuantum)throw new u9("invalid TimeInMeshQuantum; must be non zero",mZ);if(e.timeInMeshWeight<0)throw new u9("invalid TimeInMeshWeight; must be positive (or 0 to disable)",mZ);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new u9("invalid TimeInMeshQuantum; must be positive",mZ);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new u9("invalid TimeInMeshCap; must be positive",mZ);if(e.firstMessageDeliveriesWeight<0)throw new u9("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",mZ);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new u9("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",mZ);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new u9("invalid FirstMessageDeliveriesCap; must be positive",mZ);if(e.meshMessageDeliveriesWeight>0)throw new u9("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",mZ);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new u9("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",mZ);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new u9("invalid MeshMessageDeliveriesCap; must be positive",mZ);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new u9("invalid MeshMessageDeliveriesThreshold; must be positive",mZ);if(e.meshMessageDeliveriesWindow<0)throw new u9("invalid MeshMessageDeliveriesWindow; must be non-negative",mZ);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new u9("invalid MeshMessageDeliveriesActivation; must be at least 1s",mZ);if(e.meshFailurePenaltyWeight>0)throw new u9("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",mZ);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new u9("invalid MeshFailurePenaltyDecay; must be between 0 and 1",mZ);if(e.invalidMessageDeliveriesWeight>0)throw new u9("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",mZ);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new u9("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",mZ)})(r)}catch(e){throw new u9(`invalid score parameters for topic ${t}: ${e.message}`,mZ)}if(e.topicScoreCap<0)throw new u9("invalid topic score cap; must be positive (or 0 for no cap)",mZ);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new u9("missing application specific score function",mZ);if(e.IPColocationFactorWeight>0)throw new u9("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",mZ);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new u9("invalid IPColocationFactorThreshold; must be at least 1",mZ);if(e.behaviourPenaltyWeight>0)throw new u9("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",mZ);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new u9("invalid BehaviourPenaltyDecay; must be between 0 and 1",mZ);if(e.decayInterval<1e3)throw new u9("invalid DecayInterval; must be at least 1s",mZ);if(e.decayToZero<=0||e.decayToZero>=1)throw new u9("invalid DecayToZero; must be between 0 and 1",mZ)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??m6,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!==sU.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,sU[n.status]);return}n.status=sU.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 sC.Error:this.markInvalidMessageDelivery(e,r);return;case sC.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==sU.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,sU[i.status]);return}if(n===sC.Ignore){i.status=sU.ignored,i.peers.clear();return}i.status=sU.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 sU.unknown:n.peers.add(e);break;case sU.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case sU.invalid:this.markInvalidMessageDelivery(e,r);case sU.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 m7{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=aQ(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(t=>{e.abort(t)})}),a0(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(a$.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 ye{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=a0(this.rawStream,e=>aj(e,t))}async close(){this.closeController.abort()}}class yt{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!==sC.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 yr=(0,hr.m)("libp2p-pubsub:");async function yn(e,t,r,n){switch(e.type){case sk.Signing:{let i={from:e.author.toBytes(),data:n,seqno:f3(8),topic:t,signature:void 0,key:void 0},s=aO([yr,sR.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,ho.B)(i.seqno,"base16")}`),topic:t,signature:i.signature,key:i.key};return{raw:i,msg:o}}case sk.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 yi(e,t){switch(e){case mG:if(null!=t.signature)return{valid:!1,error:sB.SignaturePresent};if(null!=t.seqno)return{valid:!1,error:sB.SeqnoPresent};if(null!=t.key)return{valid:!1,error:sB.FromPresent};return{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case mz:{let e,r;if(null==t.seqno||8!==t.seqno.length)return{valid:!1,error:sB.InvalidSeqno};if(null==t.signature)return{valid:!1,error:sB.InvalidSignature};if(null==t.from)return{valid:!1,error:sB.InvalidPeerId};try{e=dc(t.from)}catch(e){return{valid:!1,error:sB.InvalidPeerId}}if(null!=t.key){if(r=gf(t.key),void 0!==e.publicKey&&!(0,aM.f)(r.bytes,e.publicKey))return{valid:!1,error:sB.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:sB.InvalidPeerId};r=gf(e.publicKey)}let n={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},i=aO([yr,sR.Message.encode(n)]);if(!await r.verify(i,t.signature))return{valid:!1,error:sB.InvalidSignature};return{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${(0,ho.B)(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??gg(r)}}}default:throw Error("Unreachable")}}function ys(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 yo(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function ya(e){return(0,ho.B)(e,"base64")}function yl(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 yc=(e,t)=>{let r=(0,hr.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 yu(e){if("signed"!==e.type)throw Error("expected signed message type");if(null==e.sequenceNumber)throw Error("missing seqno field");return yc(e.from.toBytes(),e.sequenceNumber)}async function yh(e){return hs.sha256.encode(e.data)}async function yd(e,t){switch(e){case mz:{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 gm(t.privateKey);return{type:sk.Signing,author:t,key:t.publicKey,privateKey:e}}case mG:return{type:sk.Anonymous};default:throw Error(`Unknown signature policy "${e}"`)}}(rQ=sF||(sF={}))[rQ.ip4=4]="ip4",rQ[rQ.ip6=41]="ip6";class yp{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()}}(rZ=sV||(sV={}))[rZ.started=0]="started",rZ[rZ.stopped=1]="stopped";class yf extends lM{globalSignaturePolicy;multicodecs=[mY,mW];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=aQ({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=mY;opts;decodeRpcLimits;metrics;status={code:sV.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{...m0,...e,topics:null!=e.topics?Object.entries(e.topics).reduce((e,[t,r])=>(e[t]=function(e={}){return{...m1,...e}}(r),e),{}):{}}}(t.scoreParams),scoreThresholds:function(e={}){return{...m2,...e}}(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??mX,this.globalSignaturePolicy=r.globalSignaturePolicy??mz,r.fallbackToFloodsub&&this.multicodecs.push(mj),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 yp({validityMs:r.seenTTL}),this.publishedMessageIds=new yp({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case mz:this.msgIdFn=yu;break;case mG:this.msgIdFn=yh;break;default:throw Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new yp({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??ya,this.mcache=t.messageCache??new mJ(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 sN.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case sN.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case sN.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case sN.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case sN.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case sN.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 sL.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case sL.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case sL.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case sL.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 sT.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case sT.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case sT.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 sD.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case sD.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case sD.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){let r=this.toTopic(e),n=t.reason===sC.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:sM.graylist},r),this.peersByScoreThreshold.set({threshold:sM.publish},n),this.peersByScoreThreshold.set({threshold:sM.gossip},i),this.peersByScoreThreshold.set({threshold:sM.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 yt(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new m9(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=>dl(e))}isStarted(){return this.status.code===sV.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await yd(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=aQ({objectMode:!0}),a0(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:sV.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!==sV.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:sV.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 m7(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===mj&&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 ye(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 sF.ip4:case sF.ip6:return dO(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,sL.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===sV.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=>dl(e))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await a0(t,async t=>{for await(let r of t)try{let t=r.subarray(),n=sR.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 sD.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 sD.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 sD.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:sD.duplicate,msgIdStr:n};let i=await yi(this.globalSignaturePolicy,t);if(!i.valid)return{code:sD.invalid,reason:sC.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:sD.invalid,reason:sC.Error,error:sB.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:sD.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=sT.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===e?sT.Reject:sT.Ignore}if(t!==sT.Accept)return{code:sD.invalid,reason:mQ(t),msgIdStr:a}}return{code:sD.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,ys(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:sO.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:sO.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:sO.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 yl(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,sx.GraftBackoff),s=!1;let n=a+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<n&&this.score.addPenalty(e,1,sx.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,sN.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,sL.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,sx.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&&(yl(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async e=>{if(null==e.peerID)return;let r=dc(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=dl(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!==sV.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!==sV.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!==sV.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,sN.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,sN.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!==sV.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,ys([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 yn(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=ys([s]);if(f)this.sendRpcInBatch(u,g);else for(let e of u){let t=this.sendRpc(e,g);t||u.delete(e)}let m=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=s.data?s.data.length:0,m),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=>dl(e))}}sendRpcInBatch(e,t){let r=sR.encode(t),n=a$.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===sT.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=mQ(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=ys([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){let r=[await this.makePrune(e,t,this.opts.doPX,!0)],n=ys([],{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=sR.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=yo(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=yo(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,ys([],{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,ys([],{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||(yl(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=yl(Array.from(s)).slice(0,n),s.forEach(t=>{let n=r;r.length>5e3&&(n=yl(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,ys([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ys([],{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===mW)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=dl(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===sV.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=yl(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)},m=(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,sL.BadScore),u.set(e,!0))}),s.size<t){let t=e-s.size,r=m3(p,t,()=>!0);r.forEach(e=>{m(e,sN.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(yl(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,sL.Excess)})}if(s.size>=t){let e=0;if(s.forEach(t=>{this.outbound.get(t)&&e++}),e<i){let t=i-e,r=m3(p,t,e=>!0===this.outbound.get(e));r.forEach(e=>{m(e,sN.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=m3(p,e,e=>a(e)>r);for(let e of t)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",e,o),m(e,sN.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=yl(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=yl(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 m=t.invalidMessageDeliveries*t.invalidMessageDeliveries;p+=m*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)}}(r0=sK||(sK={})).Relay="relay",r0.Store="store",r0.LightPush="lightpush",r0.Filter="filter",(r1=sH||(sH={})).GENERIC_FAIL="Generic error",r1.ENCODE_FAILED="Failed to encode",r1.DECODE_FAILED="Failed to decode",r1.EMPTY_PAYLOAD="Payload is empty",r1.SIZE_TOO_BIG="Size is too big",r1.TOPIC_NOT_CONFIGURED="Topic not configured",r1.NO_PEER_AVAILABLE="No peer available",r1.REMOTE_PEER_FAULT="Remote peer fault",r1.REMOTE_PEER_REJECTED="Remote peer rejected",r1.REQUEST_TIMEOUT="Request timeout",(r2=sq||(sq={})).BACKWARD="backward",r2.FORWARD="forward",(r3=s$||(s$={})).BOOTSTRAP="bootstrap",r3.PEER_EXCHANGE="peer-exchange",r3.LOCAL="local-peer-cache",(r4=sz||(sz={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",r4.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",r4.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",r4.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(sG||(sG={})).CONNECTION_STATUS="waku:connection";let yg="/waku/2/default-waku/proto",ym=["/vac/waku/relay/2.0.0"];(r6=sj||(sj={})).codec=()=>(null==ec&&(ec=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),ec),r6.encode=e=>(0,ao.LE)(e,r6.codec()),r6.decode=(e,t)=>(0,ao.C6)(e,r6.codec(),t),(r8=sW||(sW={})).codec=()=>(null==eu&&(eu=(0,ao.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),sj.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,aa.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=sj.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),eu),r8.encode=e=>(0,ao.LE)(e,r8.codec()),r8.decode=(e,t)=>(0,ao.C6)(e,r8.codec(),t),(r9=(r5=sY||(sY={})).ContentFilter||(r5.ContentFilter={})).codec=()=>(null==ed&&(ed=(0,ao.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})),ed),r9.encode=e=>(0,ao.LE)(e,r9.codec()),r9.decode=(e,t)=>(0,ao.C6)(e,r9.codec(),t),r5.codec=()=>(null==eh&&(eh=(0,ao.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),r5.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(r5.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&t)}}return n})),eh),r5.encode=e=>(0,ao.LE)(e,r5.codec()),r5.decode=(e,t)=>(0,ao.C6)(e,r5.codec(),t),(r7=sX||(sX={})).codec=()=>(null==ep&&(ep=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(10),sZ.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(sZ.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),ep),r7.encode=e=>(0,ao.LE)(e,r7.codec()),r7.decode=(e,t)=>(0,ao.C6)(e,r7.codec(),t),(ne=sJ||(sJ={})).codec=()=>(null==ef&&(ef=(0,ao.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),sY.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),sX.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=sY.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=sX.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),ef),ne.encode=e=>(0,ao.LE)(e,ne.codec()),ne.decode=(e,t)=>(0,ao.C6)(e,ne.codec(),t),(nt=sQ||(sQ={})).codec=()=>(null==eg&&(eg=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),eg),nt.encode=e=>(0,ao.LE)(e,nt.codec()),nt.decode=(e,t)=>(0,ao.C6)(e,nt.codec(),t),(nr=sZ||(sZ={})).codec=()=>(null==em&&(em=(0,ao.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),sQ.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,aa.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=sQ.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),em),nr.encode=e=>(0,ao.LE)(e,nr.codec()),nr.decode=(e,t)=>(0,ao.C6)(e,nr.codec(),t),(nn=s0||(s0={})).codec=()=>(null==ey&&(ey=(0,ao.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})),ey),nn.encode=e=>(0,ao.LE)(e,nn.codec()),nn.decode=(e,t)=>(0,ao.C6)(e,nn.codec(),t),(ns=eb=(ni=s1||(s1={})).FilterSubscribeType||(ni.FilterSubscribeType={})).SUBSCRIBER_PING="SUBSCRIBER_PING",ns.SUBSCRIBE="SUBSCRIBE",ns.UNSUBSCRIBE="UNSUBSCRIBE",ns.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL",(no=ew||(ew={}))[no.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",no[no.SUBSCRIBE=1]="SUBSCRIBE",no[no.UNSUBSCRIBE=2]="UNSUBSCRIBE",no[no.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL",(eb=ni.FilterSubscribeType||(ni.FilterSubscribeType={})).codec=()=>(0,ao.Ji)(ew),ni.codec=()=>(null==eE&&(eE=(0,ao.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!==ew[e.filterSubscribeType]&&(t.uint32(16),ni.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:eb.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=ni.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 ao.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})),eE),ni.encode=e=>(0,ao.LE)(e,ni.codec()),ni.decode=(e,t)=>(0,ao.C6)(e,ni.codec(),t),(na=s2||(s2={})).codec=()=>(null==ev&&(ev=(0,ao.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})),ev),na.encode=e=>(0,ao.LE)(e,na.codec()),na.decode=(e,t)=>(0,ao.C6)(e,na.codec(),t),(nl=s3||(s3={})).codec=()=>(null==eS&&(eS=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),s6.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=s6.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),eS),nl.encode=e=>(0,ao.LE)(e,nl.codec()),nl.decode=(e,t)=>(0,ao.C6)(e,nl.codec(),t),(nc=s4||(s4={})).codec=()=>(null==eA&&(eA=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),eA),nc.encode=e=>(0,ao.LE)(e,nc.codec()),nc.decode=(e,t)=>(0,ao.C6)(e,nc.codec(),t),(nu=s6||(s6={})).codec=()=>(null==eI&&(eI=(0,ao.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),s4.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,aa.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=s4.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),eI),nu.encode=e=>(0,ao.LE)(e,nu.codec()),nu.decode=(e,t)=>(0,ao.C6)(e,nu.codec(),t),(nh=s8||(s8={})).codec=()=>(null==eT&&(eT=(0,ao.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),oe.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=oe.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),eT),nh.encode=e=>(0,ao.LE)(e,nh.codec()),nh.decode=(e,t)=>(0,ao.C6)(e,nh.codec(),t),(nd=s5||(s5={})).codec=()=>(null==eR&&(eR=(0,ao.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})),eR),nd.encode=e=>(0,ao.LE)(e,nd.codec()),nd.decode=(e,t)=>(0,ao.C6)(e,nd.codec(),t),(np=s9||(s9={})).codec=()=>(null==e_&&(e_=(0,ao.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),s8.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),s5.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=s8.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=s5.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),e_),np.encode=e=>(0,ao.LE)(e,np.codec()),np.decode=(e,t)=>(0,ao.C6)(e,np.codec(),t),(nf=s7||(s7={})).codec=()=>(null==ek&&(ek=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),ek),nf.encode=e=>(0,ao.LE)(e,nf.codec()),nf.decode=(e,t)=>(0,ao.C6)(e,nf.codec(),t),(ng=oe||(oe={})).codec=()=>(null==eC&&(eC=(0,ao.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),s7.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,aa.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=s7.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),eC),ng.encode=e=>(0,ao.LE)(e,ng.codec()),ng.decode=(e,t)=>(0,ao.C6)(e,ng.codec(),t),(nm=ot||(ot={})).codec=()=>(null==eB&&(eB=(0,ao.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,aa.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})),eB),nm.encode=e=>(0,ao.LE)(e,nm.codec()),nm.decode=(e,t)=>(0,ao.C6)(e,nm.codec(),t),(nb=(ny=or||(or={})).Direction||(ny.Direction={})).BACKWARD="BACKWARD",nb.FORWARD="FORWARD",(nw=eD||(eD={}))[nw.BACKWARD=0]="BACKWARD",nw[nw.FORWARD=1]="FORWARD",(ny.Direction||(ny.Direction={})).codec=()=>(0,ao.Ji)(eD),ny.codec=()=>(null==eP&&(eP=(0,ao.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),ot.codec().encode(e.cursor,t)),null!=e.direction&&(t.uint32(24),ny.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=ot.codec().decode(e,e.uint32(),{limits:r.limits?.cursor});break;case 3:n.direction=ny.Direction.codec().decode(e);break;default:e.skipType(7&t)}}return n})),eP),ny.encode=e=>(0,ao.LE)(e,ny.codec()),ny.decode=(e,t)=>(0,ao.C6)(e,ny.codec(),t),(nE=on||(on={})).codec=()=>(null==eN&&(eN=(0,ao.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})),eN),nE.encode=e=>(0,ao.LE)(e,nE.codec()),nE.decode=(e,t)=>(0,ao.C6)(e,nE.codec(),t),(nv=oi||(oi={})).codec=()=>(null==eL&&(eL=(0,ao.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),on.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),or.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(on.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=or.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})),eL),nv.encode=e=>(0,ao.LE)(e,nv.codec()),nv.decode=(e,t)=>(0,ao.C6)(e,nv.codec(),t),(nA=ex=(nS=os||(os={})).HistoryError||(nS.HistoryError={})).NONE="NONE",nA.INVALID_CURSOR="INVALID_CURSOR",nA.TOO_MANY_RESULTS="TOO_MANY_RESULTS",nA.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",(nI=eO||(eO={}))[nI.NONE=0]="NONE",nI[nI.INVALID_CURSOR=1]="INVALID_CURSOR",nI[nI.TOO_MANY_RESULTS=429]="TOO_MANY_RESULTS",nI[nI.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",(ex=nS.HistoryError||(nS.HistoryError={})).codec=()=>(0,ao.Ji)(eO),nS.codec=()=>(null==eM&&(eM=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(18),ol.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(26),or.codec().encode(e.pagingInfo,t)),null!=e.error&&0!==eO[e.error]&&(t.uint32(32),nS.HistoryError.codec().encode(e.error,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[],error:ex.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(ol.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 3:n.pagingInfo=or.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 4:n.error=nS.HistoryError.codec().decode(e);break;default:e.skipType(7&t)}}return n})),eM),nS.encode=e=>(0,ao.LE)(e,nS.codec()),nS.decode=(e,t)=>(0,ao.C6)(e,nS.codec(),t),(nT=oo||(oo={})).codec=()=>(null==eU&&(eU=(0,ao.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),oi.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),os.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=oi.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=os.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),eU),nT.encode=e=>(0,ao.LE)(e,nT.codec()),nT.decode=(e,t)=>(0,ao.C6)(e,nT.codec(),t),(nR=oa||(oa={})).codec=()=>(null==eF&&(eF=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),eF),nR.encode=e=>(0,ao.LE)(e,nR.codec()),nR.decode=(e,t)=>(0,ao.C6)(e,nR.codec(),t),(n_=ol||(ol={})).codec=()=>(null==eV&&(eV=(0,ao.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),oa.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,aa.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=oa.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),eV),n_.encode=e=>(0,ao.LE)(e,n_.codec()),n_.decode=(e,t)=>(0,ao.C6)(e,n_.codec(),t),(nk=oc||(oc={})).codec=()=>(null==eK&&(eK=(0,ao.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})),eK),nk.encode=e=>(0,ao.LE)(e,nk.codec()),nk.decode=(e,t)=>(0,ao.C6)(e,nk.codec(),t),(nC=ou||(ou={})).codec=()=>(null==eH&&(eH=(0,ao.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})),eH),nC.encode=e=>(0,ao.LE)(e,nC.codec()),nC.decode=(e,t)=>(0,ao.C6)(e,nC.codec(),t),(nB=oh||(oh={})).codec=()=>(null==eq&&(eq=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(let r of e.peerInfos)t.uint32(10),oc.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 ao.sv('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(oc.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),eq),nB.encode=e=>(0,ao.LE)(e,nB.codec()),nB.decode=(e,t)=>(0,ao.C6)(e,nB.codec(),t),(nD=od||(od={})).codec=()=>(null==e$&&(e$=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),ou.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),oh.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=ou.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=oh.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),e$),nD.encode=e=>(0,ao.LE)(e,nD.codec()),nD.decode=(e,t)=>(0,ao.C6)(e,nD.codec(),t),(nP=op||(op={})).codec=()=>(null==ez&&(ez=(0,ao.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 ao.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})),ez),nP.encode=e=>(0,ao.LE)(e,nP.codec()),nP.decode=(e,t)=>(0,ao.C6)(e,nP.codec(),t),(nN=of||(of={})).codec=()=>(null==eG&&(eG=(0,ao.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 ao.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})),eG),nN.encode=e=>(0,ao.LE)(e,nN.codec()),nN.decode=(e,t)=>(0,ao.C6)(e,nN.codec(),t);let yy=new a_("relay");function yb(e,t){let r=performance.now();yy.info(`validating message from ${e} received on ${t.topic}`);let n=sT.Accept;try{let e=sW.decode(t.data);e.contentTopic&&e.contentTopic.length&&e.payload&&e.payload.length||(n=sT.Reject)}catch(e){n=sT.Reject}let i=performance.now(),s=i-r;return s>100?yy.warn(`message validation took ${s}ms for peer ${e} on topic ${t.topic}. This should be less than 100ms.`):yy.info(`message validation took ${s}ms for peer ${e} on topic ${t.topic}`),n}class yw{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 yE{pubsubTopic=yg;contentTopic="";fromWireToProtoObj(e){let t=s0.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 yw(e,t)}}let yv=new a_("relay");class yS{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 ${yS.multicodec}`);this.gossipSub=e.services.pubsub,this.pubsubTopics=new Set(t),this.gossipSub.isStarted()&&this.subscribeToAllTopics(),this.observers=new Map,this.defaultDecoder=new yE}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 yv.error("Failed to send waku relay: topic not configured"),{successes:r,failures:[{error:sH.TOPIC_NOT_CONFIGURED}]};let i=await e.toWire(t);if(!i)return yv.error("Failed to encode message, aborting publish"),{successes:r,failures:[{error:sH.ENCODE_FAILED}]};if(!ad(i))return yv.error("Failed to send waku relay: message is bigger that 1MB"),{successes:r,failures:[{error:sH.SIZE_TOO_BIG}]};let{recipients:s}=await this.gossipSub.publish(n,i);return{successes:s}}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};!function(e,t,r){let n=e.get(t);void 0===n&&(e.set(t,new Set),n=e.get(t)),n.add(r)}(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 au(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=yg){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){yv.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){yv.error("Internal error: message previously decoded failed on 2nd pass.");return}let o=await n.fromProtoObj(e,s);o?await i(o):yv.error("Failed to decode messages on",r.contentTopic)}catch(e){yv.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=>yv.error("Failed to process incoming message",e))}),this.gossipSub.topicValidators.set(e,yb),this.gossipSub.subscribe(e)}isRelayPubsub(e){return e?.multicodecs?.includes(yS.multicodec)??!1}}let yA=Symbol.for("@libp2p/content-routing"),yI=Symbol.for("@libp2p/peer-routing");function yT(){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`),aT.enabled(`${e}:trace`)&&null!=aT.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(t=aT(`${e}:trace`)),Object.assign(aT(e),{error:aT(`${e}:error`),trace:t})}}}function yR(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}aT.formatters.b=e=>null==e?"undefined":hn.base58btc.baseEncode(e),aT.formatters.t=e=>null==e?"undefined":d_.base32.baseEncode(e),aT.formatters.m=e=>null==e?"undefined":hh.base64.baseEncode(e),aT.formatters.p=e=>null==e?"undefined":e.toString(),aT.formatters.c=e=>null==e?"undefined":e.toString(),aT.formatters.k=e=>null==e?"undefined":e.toString(),aT.formatters.a=e=>null==e?"undefined":e.toString();class y_{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 yR(this.set.entries(),e=>{let t=dl(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let r=dl(t);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return yR(this.set.values(),e=>dl(e))}intersection(e){let t=new y_;for(let r of e)this.has(r)&&t.add(r);return t}difference(e){let t=new y_;for(let r of this)e.has(r)||t.add(r);return t}union(e){let t=new y_;for(let r of e)t.add(r);for(let e of this)t.add(e);return t}}let yk=async()=>{let e=await gp("Ed25519"),t=await yB(e);if("Ed25519"===t.type)return t;throw Error(`Generated unexpected PeerId type "${t.type}"`)};async function yC(e){return du(gg(e))}async function yB(e){var t;return du(gg(e.public),(gd(t=(t??"rsa").toLowerCase()),e.bytes))}async function yD(e){return yP((0,hr.m)(e.id,"base58btc"),null!=e.privKey?(0,hr.m)(e.privKey,"base64pad"):void 0,null!=e.pubKey?(0,hr.m)(e.pubKey,"base64pad"):void 0)}async function yP(e,t,r){if(null!=t){let e=await gm(t);return yB(e)}if(null!=r){let e=gf(r);return yC(e)}return dc(e)}class yN{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 yR(this.map.entries(),e=>[dl(e[0]),e[1]])}forEach(e){this.map.forEach((t,r)=>{e(t,dl(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 yR(this.map.keys(),e=>dl(e))}values(){return this.map.values()}get size(){return this.map.size}}var yL=r(8729);class yx{#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 yO extends yL{#a;#l;#c=0;#u;#h;#d=0;#p;#f;#o;#g;#m=0;#y;#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:yx,...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 #E(){return this.#l||this.#c<this.#u}get #v(){return this.#m<this.#y}#S(){this.#m--,this.#A(),this.emit("next")}#I(){this.#T(),this.#R(),this.#f=void 0}get #_(){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.#m:0}return!1}#A(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#m&&this.emit("idle"),!1;if(!this.#b){let e=!this.#_;if(this.#E&&this.#v){let t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#R(),!0)}}return!1}#R(){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.#m&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#c=this.#a?this.#m:0,this.#k()}#k(){for(;this.#A(););}get concurrency(){return this.#y}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.#y=e,this.#k()}async #C(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.#m++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=lk(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#C(t.signal)]));let i=await n;r(i),this.emit("completed",i)}catch(e){if(e instanceof lI&&!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.#k()),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.#m||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.#m}get isPaused(){return this.#b}}let yM={},yU=e=>{e.addEventListener("message",t=>{yU.dispatchEvent("message",e,t)}),null!=e.port&&e.port.addEventListener("message",t=>{yU.dispatchEvent("message",e,t)})};yU.addEventListener=(e,t)=>{null==yM[e]&&(yM[e]=[]),yM[e].push(t)},yU.removeEventListener=(e,t)=>{null!=yM[e]&&(yM[e]=yM[e].filter(e=>e===t))},yU.dispatchEvent=function(e,t,r){null!=yM[e]&&yM[e].forEach(e=>e(t,r))};let yF="lock:worker:request-read",yV="lock:worker:release-read",yK="lock:master:grant-read",yH="lock:worker:request-write",yq="lock:worker:release-write",y$="lock:master:grant-write",yz=(e=21)=>Math.random().toString().substring(2),yG=(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)})}}}))},yj=(e,t,r,n)=>async()=>{let i=yz();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)})},yW={singleProcess:!1};var yY=e=>{e=Object.assign({},yW,e);let t=!!globalThis.document||e.singleProcess;if(t){let e=new EventTarget;return yU.addEventListener("message",yG(e,"requestReadLock",yF,yV,yK)),yU.addEventListener("message",yG(e,"requestWriteLock",yH,yq,y$)),e}return{isWorker:!0,readLock:e=>yj(e,yF,yK,yV),writeLock:e=>yj(e,yH,y$,yq)}};let yX={};async function yJ(e,t){let r;let n=new Promise(e=>{r=e});return e.add(async()=>lk((async()=>{await new Promise(e=>{r(()=>{e()})})})(),{milliseconds:t.timeout})),n}let yQ=(e,t)=>{let r;if(!0===i.isWorker)return{readLock:i.readLock(e,t),writeLock:i.writeLock(e,t)};let n=new yO({concurrency:1});return{async readLock(){if(null!=r)return yJ(r,t);r=new yO({concurrency:t.concurrency,autoStart:!1});let e=r,i=yJ(r,t);return n.add(async()=>{e.start(),await e.onIdle().then(()=>{r===e&&(r=null)})}),i},writeLock:async()=>(r=null,yJ(n,t))}},yZ={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1},y0={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};function y1(e,t){let r=og.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new di(e);if("Ed25519"===e.type)return new ds(e);if("secp256k1"===e.type)return new da(e);throw new u9("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:dQ(e),isCertified:t??!1})),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}(nx=(nL=og||(og={})).Peer$metadataEntry||(nL.Peer$metadataEntry={})).codec=()=>(null==eW&&(eW=(0,ao.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})),eW),nx.encode=e=>(0,ao.LE)(e,nx.codec()),nx.decode=e=>(0,ao.C6)(e,nx.codec()),(nO=nL.Peer$tagsEntry||(nL.Peer$tagsEntry={})).codec=()=>(null==eY&&(eY=(0,ao.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),oy.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=oy.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r})),eY),nO.encode=e=>(0,ao.LE)(e,nO.codec()),nO.decode=e=>(0,ao.C6)(e,nO.codec()),nL.codec=()=>(null==ej&&(ej=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.addresses)for(let r of e.addresses)t.uint32(10),om.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),nL.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),nL.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(om.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=nL.Peer$metadataEntry.codec().decode(e,e.uint32());r.metadata.set(t.key,t.value);break}case 7:{let t=nL.Peer$tagsEntry.codec().decode(e,e.uint32());r.tags.set(t.key,t.value);break}default:e.skipType(7&t)}}return r})),ej),nL.encode=e=>(0,ao.LE)(e,nL.codec()),nL.decode=e=>(0,ao.C6)(e,nL.codec()),(nM=om||(om={})).codec=()=>(null==eX&&(eX=(0,ao.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})),eX),nM.encode=e=>(0,ao.LE)(e,nM.codec()),nM.decode=e=>(0,ao.C6)(e,nM.codec()),(nU=oy||(oy={})).codec=()=>(null==eJ&&(eJ=(0,ao.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})),eJ),nU.encode=e=>(0,ao.LE)(e,nU.codec()),nU.decode=e=>(0,ao.C6)(e,nU.codec());let y2=new TextEncoder().encode("/"),y3=y2[0];class y4{_buf;constructor(e,t){if("string"==typeof e)this._buf=(0,hr.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]!==y3)throw Error("Invalid key")}toString(e="utf8"){return(0,ho.B)(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new y4(e.join("/"))}static random(){return new y4(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new y4(e):"function"==typeof e.uint8Array?new y4(e.uint8Array()):null}clean(){if((null==this._buf||0===this._buf.byteLength)&&(this._buf=y2),this._buf[0]!==y3){let e=new Uint8Array(this._buf.byteLength+1);e.fill(y3,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===y3;)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 y4.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 y4(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith("/")||(e+="/"),new y4(e+=this.type())}parent(){let e=this.list();return new y4(1===e.length?"/":e.slice(0,-1).join("/"))}child(e){return"/"===this.toString()?e:"/"===e.toString()?this:new y4(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 y4.withNamespaces([...this.namespaces(),...[].concat(...e.map(e=>e.namespaces()))])}}let y6="/peers/";function y8(e){if(!h5(e)||null==e.type)throw new u9("Invalid PeerId",y0.ERR_INVALID_PARAMETERS);let t=e.toCID().toString();return new y4(`${y6}${t}`)}async function y5(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=dQ(s.multiaddr)),i=s.multiaddr,!i?.[dW])throw new u9("Multiaddr was invalid",y0.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 y9(e,t,r,n){if(null==t)throw new u9("Invalid PeerData",y0.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!(0,aM.f)(t.publicKey,e.publicKey))throw new u9("publicKey bytes do not match peer id publicKey bytes",y0.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(null!=i&&!e.equals(i.id))throw new u9("peer id did not match existing peer id",y0.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=y7(e,{validate:be})}if(null!=t.tags){let e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);l=y7(e,{validate:bt,map:br})}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=y7([...a.entries()],{validate:be})}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=y7([...r.entries()],{validate:bt,map:br})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}let u={addresses:await y5(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 y7(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 be(e,t){if("string"!=typeof e)throw new u9("Metadata key must be a string",y0.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new u9("Metadata value must be a Uint8Array",y0.ERR_INVALID_PARAMETERS)}function bt(e,t){if("string"!=typeof e)throw new u9("Tag name must be a string",y0.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new u9("Tag value must be an integer",y0.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new u9("Tag value must be between 0-100",y0.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new u9("Tag ttl must be an integer",y0.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new u9("Tag ttl must be between greater than 0",y0.ERR_INVALID_PARAMETERS)}}function br(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 bn(e,t,r){let n=e.toString().split("/")[2],i=d_.base32.decode(n),s=dc(i),o=r.get(s);if(null!=o)return o;let a=y1(s,t);return r.set(s,a),a}class bi{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({},yZ,e);return null==i&&!0!==(i=yY(t)).isWorker&&(i.addEventListener("requestReadLock",e=>{null!=yX[e.data.name]&&yX[e.data.name].readLock().then(async t=>e.data.handler().finally(()=>{t()}))}),i.addEventListener("requestWriteLock",async e=>{null!=yX[e.data.name]&&yX[e.data.name].writeLock().then(async t=>e.data.handler().finally(()=>{t()}))})),null==yX[t.name]&&(yX[t.name]=yQ(t.name,t)),yX[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(y8(e))}async delete(e){if(this.peerId.equals(e))throw new u9("Cannot delete self peer",y0.ERR_INVALID_PARAMETERS);await this.datastore.delete(y8(e))}async load(e){let t=await this.datastore.get(y8(e));return y1(e,t)}async save(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await y9(e,t,"patch",{addressFilter:this.addressFilter});return this.#P(e,i,r,n)}async patch(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await y9(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#P(e,i,r,n)}async merge(e,t){let{existingBuf:r,existingPeer:n}=await this.#D(e),i=await y9(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#P(e,i,r,n)}async *all(e){var t;let r=new yN;for await(let{key:n,value:i}of this.datastore.query(null==(t=e??{})?{}:{prefix:y6,filters:(t.filters??[]).map(e=>({key:t,value:n})=>e(bn(t,n,r))),orders:(t.orders??[]).map(e=>(t,n)=>e(bn(t.key,t.value,r),bn(n.key,n.value,r)))})){let e=bn(n,i,r);e.id.equals(this.peerId)||(yield e)}}async #D(e){try{let t=await this.datastore.get(y8(e)),r=y1(e,t);return{existingBuf:t,existingPeer:r}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async #P(e,t,r,n){let i=og.encode(t);return null!=r&&(0,aM.f)(i,r)?{peer:y1(e,i),previous:n,updated:!1}:(await this.datastore.put(y8(e),i),{peer:y1(e,i),previous:n,updated:!0})}}class bs{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 bi(e,t)}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 aL(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 gb.openAndCertify(e,pA.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=pA.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 gb.createFromProtobuf(r.peerRecordEnvelope),t=pA.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 bo=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(let t of e);})();for(let t of e);},ba=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}}},bl=function(e,t){if(null!=e[Symbol.asyncIterator])return async function*(){for await(let r of e)await t(r)&&(yield r)}();let r=ba(e),{value:n,done:i}=r.next();if(!0===i)return function*(){}();let s=t(n);return"function"==typeof s.then?async function*(){for await(let e of(await s&&(yield n),r))await t(e)&&(yield e)}():function*(){for(let e of(!0===s&&(yield n),r))t(e)&&(yield e)}()},bc=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=await aL(e);yield*r.sort(t)}():function*(){let r=aL(e);yield*r.sort(t)}()},bu=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 bh{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 bo(this.putMany(e,r)),e=[],await bo(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=bl(r,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>bl(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>bc(e,t),r)),null!=e.offset){let t=0,n=e.offset;r=bl(r,()=>t++>=n)}return null!=e.limit&&(r=bu(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){let t=e.prefix;r=bl(r,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>bl(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>bc(e,t),r)),null!=e.offset){let t=e.offset,n=0;r=bl(r,()=>n++>=t)}return null!=e.limit&&(r=bu(r,e.limit)),r}}class bd extends bh{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 az(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 y4(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new y4(e)}}let bp=e=>e;function bf(e,t){let r=e.getPeerId();if(null!=r){let n=dl(r);n.equals(t)&&(e=e.decapsulate(dQ(`/p2p/${t.toString()}`)))}return e}class bg{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??bp,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()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([e,t])=>t.confident).map(([e])=>dQ(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=>dQ(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>dQ(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>dQ(e))}addObservedAddr(e){e=bf(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=bf(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=bf(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=>dQ(e))).map(e=>e.protos().pop()?.path===!0||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`))}}class bm{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=yT())}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 by=["metrics","connectionProtector","dns"],bb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var bw=r(5194);let bE=["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 bw.Netmask(e));function bv(e){return dk(e)?function(e){for(let t of bE)if(t.contains(e))return!0;return!1}(e):dC(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 bS(e){try{let{address:t}=e.nodeAddress();return!!bv(t)}catch{return!0}}function bA(e,t){let r=function(e,t){let r=bS(e.multiaddr),n=bS(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;let n=function(e,t){let r=gZ.exactMatch(e.multiaddr),n=gZ.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 bI extends Event{constructor(e,t){super(e),this.detail=t}}function bT(e){let t=[ob.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function bR(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:ob[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:ob[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?(0,ho.B)(e.data):e.data}))}}function b_(e,t={}){let r=new yO({concurrency:t.queryConcurrency??4});return async(t,n={})=>{let i=new URLSearchParams;i.set("name",t),bT(n.types).forEach(e=>{i.append("type",ob[e])}),n.onProgress?.(new bI("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=bR(await t.json());return n.onProgress?.(new bI("dns:response",{detail:r})),r},{signal:n.signal});if(null==s)throw Error("No DNS response received");return s}}var bk=r(3746);class bC{lru;constructor(e){this.lru=bk(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 bR({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:ob[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 bB{resolvers;cache;constructor(e){this.resolvers={},this.cache=new bC(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["."]=[b_("https://cloudflare-dns.com/dns-query"),b_("https://dns.google/resolve")])}async query(e,t={}){let r=bT(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new bI("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 bI("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(nF=ob||(ob={}))[nF.A=1]="A",nF[nF.CNAME=5]="CNAME",nF[nF.TXT=16]="TXT",nF[nF.AAAA=28]="AAAA";let{code:bD}=dx("dnsaddr"),bP=async function(e,t={}){let r=t.maxRecursiveDepth??32;if(0===r)throw new u9("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,n]=e.stringTuples().find(([e])=>e===bD)??[],i=t?.dns??function(e={}){return new bB(e)}(),s=await i.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[ob.TXT]}),o=e.getPeerId(),a=[];for(let e of s.Answer){let n=e.data.split("=")[1];if(null==n||null!=o&&!n.includes(o))continue;let i=dQ(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 bN=r(3498);(nV=ow||(ow={})).NOT_STARTED_YET="The libp2p node is not started yet",nV.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",nV.NOT_FOUND="Not found",(nK=oE||(oE={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",nK.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",nK.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",nK.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",nK.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",nK.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",nK.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",nK.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",nK.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",nK.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",nK.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",nK.ERR_DIALED_SELF="ERR_DIALED_SELF",nK.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",nK.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",nK.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",nK.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",nK.ERR_INVALID_KEY="ERR_INVALID_KEY",nK.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",nK.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",nK.ERR_INVALID_PEER="ERR_INVALID_PEER",nK.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",nK.ERR_NOT_FOUND="ERR_NOT_FOUND",nK.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",nK.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",nK.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",nK.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",nK.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",nK.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",nK.ERR_FIND_SELF="ERR_FIND_SELF",nK.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",nK.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",nK.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",nK.ERR_INVALID_CMS="ERR_INVALID_CMS",nK.ERR_MISSING_KEYS="ERR_MISSING_KEYS",nK.ERR_NO_KEY="ERR_NO_KEY",nK.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",nK.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",nK.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",nK.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",nK.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",nK.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",nK.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",nK.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",nK.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",nK.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",nK.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",nK.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",nK.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",nK.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",nK.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",nK.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",nK.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",nK.ERR_INVALID_RECORD="ERR_INVALID_RECORD",nK.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",nK.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",nK.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",nK.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",nK.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",nK.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";let bL={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:bP},addressSorter:bA},transportManager:{faultTolerance:sI.FATAL_ALL}};async function bx(e){let t=bN(bL,e);if(null===t.connectionProtector&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new u9(ow.ERR_PROTECTOR_REQUIRED,oE.ERR_PROTECTOR_REQUIRED);if(!(await du(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new u9("Private key doesn't match peer id",oE.ERR_INVALID_KEY);return t}function bO(e){let t;if(h5(e))return{peerId:e,multiaddrs:[]};if(Array.isArray(e)||(e=[e]),e.length>0){let r=e[0].getPeerId();t=null==r?void 0:dl(r),e.forEach(e=>{if(!e?.[dW])throw new u9("Invalid Multiaddr",oE.ERR_INVALID_MULTIADDR);let r=e.getPeerId();if(null==r){if(null!=t)throw new u9("Multiaddrs must all have the same peer id or have no peer id",oE.ERR_INVALID_PARAMETERS)}else{let e=dl(r);if(null==t||!t.equals(e))throw new u9("Multiaddrs must all have the same peer id or have no peer id",oE.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}class bM 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 bU(e,t,r,n){let i=new bM(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(i):new Promise((s,o)=>{let a=i=>{try{if(n?.filter?.(i)===!1)return}catch(n){e.removeEventListener(t,a),r?.removeEventListener("abort",l),o(n);return}e.removeEventListener(t,a),r?.removeEventListener("abort",l),s(i)},l=()=>{e.removeEventListener(t,a),r?.removeEventListener("abort",l),o(i)};e.addEventListener(t,a),r?.addEventListener("abort",l)})}class bF{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=aW(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new u5)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class bV{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,r=0){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.priority=r,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,lO(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 u5),this.cleanup())}async join(e={}){let t=new bF(Error("where").stack,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 lj(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 bK extends lM{concurrency;queue;pending;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.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){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=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.queue,e,(e,t)=>t.priority-e.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let r=new bV(e,t,t?.priority),n=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});return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),n}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new u5)}),this.clear()}async onEmpty(e){0!==this.size&&await bU(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await bU(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){(0!==this.pending||0!==this.size)&&await bU(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=aQ({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 u9("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 bH extends bK{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}let bq="last-dial-failure",b$={minConnections:5,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:42e4,autoDialDiscoveredPeersDebounce:10};class bz{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??b$.minConnections,this.autoDialPriority=t.autoDialPriority??b$.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??b$.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??b$.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??b$.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??b$.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new bH({concurrency:t.autoDialConcurrency??b$.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 y_(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 yN;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(bq);if(null==t)return!0;let r=parseInt((0,ho.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 bG={maxConnections:100,allow:[]};class bj{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??bG.maxConnections,this.allow=t.allow??bG.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,r=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,r);let n=new yN;for(let t of e){let e=t.remotePeer;if(!n.has(e)){n.set(e,0);try{let t=await this.peerStore.get(e);n.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 i=e.sort((e,t)=>{let r=n.get(e.remotePeer)??0,i=n.get(t.remotePeer)??0;if(r>i)return 1;if(r<i)return -1;let s=e.timeline.open,o=t.timeline.open;return s<o?1:s>o?-1:0}),s=[];for(let e of i){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===r)break}await Promise.all(s.map(async e=>{try{await e.close()}catch(e){this.log.error(e)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}}async function bW(e,t){let r=!1;for(let t of dJ.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 bY={addressSorter:bA,maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3};class bX{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){for(let[r,n]of(this.addressSorter=t.addressSorter??bY.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??bY.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??bY.maxDialQueueLength,this.dialTimeout=t.dialTimeout??bY.dialTimeout,this.connections=t.connections??new yN,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,lO(1/0,this.shutDownController.signal),Object.entries(t.resolvers??{})))dJ.set(r,n);this.queue=new bK({concurrency:t.maxParallelDials??bY.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,lO(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:r,multiaddrs:n}=bO(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 u9("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 u9("Peer had more than maxPeerAddrsToDial",oE.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:{[bq]:(0,hr.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 u9(e.message,he);s.push(e)}}if(1===s.length)throw s[0];throw new u7(s,"All multiaddr dials failed",oE.ERR_TRANSPORT_DIAL_FAILED)}finally{n.clear()}},{peerId:r,priority:t.priority,multiaddrs:new Set(n.map(e=>e.toString())),signal:t.signal})}createDialAbortController(e){let t=function(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}([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return lO(1/0,t),t}async calculateMultiaddrs(e,t=new Set,r={}){let n=[...t].map(e=>({multiaddr:dQ(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new u9("Tried to dial self",oE.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new u9("The dial request is blocked by gater.allowDialPeer",oE.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!==oE.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!==oE.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 bW(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.transportForMultiaddr(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 u9("The dial request has no valid addresses",oE.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 u9("The connection gater denied all addresses in the dial request",oE.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=>!gZ.matches(e.multiaddr));return!0}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}let bJ={minConnections:5,maxConnections:100,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100};class bQ{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??bJ.maxConnections;let r=t.minConnections??bJ.minConnections;if(this.maxConnections<r)throw new u9("Connection Manager maxConnections must be greater than minConnections",oE.ERR_INVALID_PARAMETERS);this.connections=new yN,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=>dQ(e)),this.deny=(t.deny??[]).map(e=>dQ(e)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??bJ.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new mc({points:t.inboundConnectionThreshold??bJ.inboundConnectionThreshold,duration:1}),this.autoDial=new bz({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??bJ.autoDialConcurrency,autoDialPriority:t.autoDialPriority??bJ.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??bJ.autoDialMaxQueueLength}),this.connectionPruner=new bj({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new bX(e,{addressSorter:t.addressSorter??bA,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:bP},connections:this.connections})}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 u9("Not started",oE.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:r}=bO(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??50}),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=>dQ(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class bZ{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}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 u9("No content routers available",oE.ERR_NO_ROUTERS_AVAILABLE);let r=new y_;for await(let n of aZ(...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 u9("No content routers available",oE.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 u9(ow.NOT_STARTED_YET,oE.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 u9(ow.NOT_STARTED_YET,oE.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async r=>r.get(e,t)))}}let b0=globalThis.CustomEvent??Event;async function*b1(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=aW(),l=aW(),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=aW(),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 b0("task-complete"))},t=>{e.done=!0,e.err=t,s.dispatchEvent(new b0("task-complete"))})}c=!0,s.dispatchEvent(new b0("task-complete"))}catch(e){r=e,s.dispatchEvent(new b0("task-complete"))}});;){if(h()||(l=aW(),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 b2{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??[]}async findPeer(e,t){if(0===this.routers.length)throw new u9("No peer routers available",oE.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new u9("Should not try to find self",oE.ERR_FIND_SELF);let r=this,n=aZ(...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 u9(ow.NOT_FOUND,oE.ERR_NOT_FOUND)}async *getClosestPeers(e,t={}){if(0===this.routers.length)throw new u9("No peer routers available",oE.ERR_NO_ROUTERS_AVAILABLE);let r=this,n=new y_;for await(let i of b1(async function*(){let n=aZ(...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)||(n.add(i.id),yield i))}}class b3{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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(null==t)throw new u9(`No handler registered for protocol ${e}`,oE.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 u9(`Handler already registered for protocol ${e}`,oE.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let n=bN.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 u9("invalid topology",oE.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.onDisconnect?.(t)}}).catch(e=>{e.code!==oE.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.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.onConnect?.(n,r)}}}class b4 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 b6{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 b4({name:t,metrics:r}):new Map}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??sI.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(null==t)throw new u9("Transport must have a valid tag",oE.ERR_INVALID_KEY);if(this.transports.has(t))throw new u9(`There is already a transport with the tag ${t}`,oE.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.transportForMultiaddr(e);if(null==r)throw new u9(`No transport available for address ${String(e)}`,oE.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=oE.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()}transportForMultiaddr(e){for(let t of this.transports.values()){let r=t.filter([e]);if(r.length>0)return t}}async listen(e){if(!this.isStarted())throw new u9("Not started",oE.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.filter(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!==sI.NO_FATAL)throw new u9(`Transport (${r}) could not listen on any available address`,oE.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===sI.FATAL_ALL)throw new u9(e,oE.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 b8="/multistream/1.0.0",b5=(0,hr.m)("\n");async function b9(e,t,r){await e.write(t,r)}async function b7(e,t,r){await e.writeV(t,r)}async function we(e,t){let r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==b5[0])throw t.log.error("Invalid mss message - missing newline",r),new u9("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function wt(e,t){let r=await we(e,t);return(0,ho.B)(r.subarray())}async function wr(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);let n=lQ(e,{...r,maxDataLength:1024,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");let e=await wt(n,r);if(r.log.trace('handle: read "%s"',e),e===b8){r.log.trace('handle: respond with "%s" for "%s"',b8,e),await b9(n,(0,hr.m)(`${b8}
|
|
`),r),r.log.trace('handle: responded with "%s" for "%s"',b8,e);continue}if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await b9(n,(0,hr.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 aK(...t.map(e=>a$.single((0,hr.m)(`${e}
|
|
`))),(0,hr.m)("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await b9(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 b9(n,(0,hr.m)("na\n"),r),r.log('handle: responded with "na" for "%s"',e)}}async function wn(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=aW(),l=!1,c=!1,u=aW(),h=!1,d=!1,p=aW(),f=lQ({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 m()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await y())}finally{o=!1,s=!0,a.resolve()}}async function m(){if(c){await u.promise;return}c=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',b8,t),await f.writeV([(0,hr.m)(`${b8}
|
|
`),(0,hr.m)(`${t}
|
|
`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',b8,t)}finally{l=!0,c=!1,u.resolve()}}async function y(){if(d){await p.promise;return}d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await wt(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===b8&&(e=await wt(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new u9("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',b8,t,i.byteLength);let e=`${t}
|
|
`;yield new aK(Uint8Array.from([19]),(0,hr.m)(`${b8}
|
|
`),ax.cv(e.length),(0,hr.m)(e),i).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',b8,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 lj(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=lQ(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"]',b8,i);let s=(0,hr.m)(`${b8}
|
|
`),o=(0,hr.m)(`${i}
|
|
`);await b7(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await wt(n,r);if(r.log.trace('select: read "%s"',a),a===b8&&(r.log.trace("select: reading protocol response"),a=await wt(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 b9(n,(0,hr.m)(`${e}
|
|
`),r),r.log.trace("select: reading protocol response");let t=await wt(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new u9("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}let wi=Symbol.for("@libp2p/connection");class ws{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";[wi]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new u9("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new u9("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new u9("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);lO(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 wo(e,t,r){let n=0;return r.streams.forEach(r=>{r.direction===t&&r.protocol===e&&n++}),n}class wa{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}async shouldBlockConnection(e,t,r){let n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new u9(`The multiaddr connection is blocked by gater.${r}`,oE.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 u9("connection denied",oE.ERR_CONNECTION_DENIED);let l=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new u9("inbound upgrade timeout",he))};l.addEventListener("abort",c,{once:!0}),lO(1/0,l);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new u9("The multiaddr connection is blocked by gater.acceptConnection",oE.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 u9("inbound connection that skipped encryption must have a peer id",oE.ERR_INVALID_MULTIADDR);let r=dl(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=dl(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 u9("Encryption was skipped but no peer id was passed",oE.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 wr(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!==oE.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(i,this.components.registrar),o=wo(i,"inbound",n);if(o===s){let t=new u9(`Too many inbound protocol streams for protocol "${i}" - limit ${s}`,oE.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 u9("Stream is not multiplexed",oE.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);lO(1/0,t),r={...r,signal:t}}i.log.trace("selecting protocol from protocols %s",e);let{stream:t,protocol:s}=await wn(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!==oE.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,r),a=wo(s,"outbound",n);if(a>=o){let e=new u9(`Too many outbound protocol streams for protocol "${s}" - limit ${o}`,oE.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 u9(String(t),oE.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 ws({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 u9("connection is not multiplexed",oE.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 u9("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 wr(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 to %p failed",t),new u9(t.message,oE.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 wn(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(t){throw e.log.error("encrypting outbound connection to %p failed",t),new u9(t.message,oE.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 wn(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 u9(String(t),oE.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 wr(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 u9(String(t),oE.ERR_MUXER_UNAVAILABLE)}}}class wl extends lM{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new lM,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},lO(1/0,t),this.peerId=e.peerId,this.logger=e.logger??yT(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=this.components=function(e={}){let t=new bm(e),r=new Proxy(t,{get(e,r,n){if("string"==typeof r&&!bb.includes(r)){let e=t.components[r];if(null==e&&!by.includes(r))throw new u9(`${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.4.2"},logger:this.logger,events:t,datastore:e.datastore??new bd,connectionGater:function(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!bv(`${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 bs(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 wa(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 b6(this.components,e.transportManager)),this.configureComponent("connectionManager",new bQ(this.components,e.connectionManager)),this.configureComponent("registrar",new b3(this.components)),this.configureComponent("addressManager",new bg(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 b2(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 bZ(this.components,{routers:s})),(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[yA]&&(this.log("registering service %s for content routing",t),s.push(n[yA])),null!=n[yI]&&(this.log("registering service %s for peer routing",t),i.push(n[yI])),null!=n[dI]&&(this.log("registering service %s for peer discovery",t),n[dI].addEventListener?.("peer",e=>{this.#L(e)}))}}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 y_;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 u9("no protocols were provided to open a stream",oE.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?.[dW]&&(e=dl(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!==oE.ERR_NOT_FOUND)throw e}let r=aO([(0,hr.m)("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return gf(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(oE.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error(e)})}}async function wc(e={}){let t=e.peerId??=await yk();if(null==t.privateKey)throw new u9("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await gm(t.privateKey),new wl(await bx(e))}async function wu(e={}){let t=await wc(e);return!1!==e.start&&await t.start(),t}class wh{numPeers;constructor(e){this.numPeers=e?.numPeersToUse??3}}let wd=new a_("sdk:light-push");class wp extends wh{protocol;constructor(e,t){super({numPeersToUse:t?.numPeersToUse??3}),this.protocol=new ly(e,t)}async send(e,t){let r=[],n=[],{pubsubTopic:i}=e;try{ab(i,this.protocol.pubsubTopics)}catch(e){return wd.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:sn.TOPIC_NOT_CONFIGURED}],successes:[]}}let s=await this.protocol.getPeers();if(!s.length)return{successes:r,failures:[{error:sn.NO_PEER_AVAILABLE}]};let o=s.map(r=>this.protocol.send(e,t,r)),a=await Promise.allSettled(o);for(let e of a)if("fulfilled"===e.status){let{failure:t,success:i}=e.value;i&&r.push(i),t&&n.push(t)}else wd.error("Failed to send message to peer",e.reason),n.push({error:sn.GENERIC_FAIL});return{successes:r,failures:n}}}let wf=new a_("waku:store:protocol");class wg extends wh{protocol;constructor(e,t){super({numPeersToUse:1}),this.protocol=new lA(e,t)}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.numPeers,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,af.iY)(e.contentTopic),r=(0,ap.J)((0,af.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(ab(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||wf.warn("No start time provided"),i||wf.warn("No end time provided");let s=Object.assign({pubsubTopic:e,pageDirection:si.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(al);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===si.BACKWARD}}async function wm(e={}){let t=await v6(e),r=function(e={}){return t=>new wg(t,e)}(e),n=function(e={}){return t=>new wp(t,e)}(e),i=function(e={pubsubTopics:[]}){return t=>new lp(t,e)}(e);return new wE(e,t,r,n,i)}async function wy(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=am(n),s=aE(t);if(!i.includes(s))throw Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await lD(e,[sr.Filter]);let o=new aP(av(t,s),t);o&&(o=o??o);let a=await e.filter.createSubscription(s);return{decoder:o,subscription:a}}async function wb(e,t,r){r.waku=r.waku??await wm({shardInfo:{contentTopics:[e]}});let{decoder:n,subscription:i}=await wy(r.waku,e,r.peer);return await i.subscribe(n,t),{subscription:i,waku:r.waku}}let ww=new a_("waku");class wE{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r,n,i,s){if(0==e.pubsubTopics.length)throw Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r&&(this.store=r(t)),i&&(this.filter=i(t)),n&&(this.lightPush=n(t)),s&&(this.relay=s(t));let o=e.pingKeepAlive||300,a=this.relay?e.relayKeepAlive||300:0,l=this.libp2p.peerId.toString();this.connectionManager=lH.create(l,t,{pingKeepAlive:o,relayKeepAlive:a},this.pubsubTopics,this.relay),ww.info("Waku node created",l,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){let r=t??[],n=h5(e)?e:dQ(e);void 0===t&&(this.relay&&r.push(sr.Relay),this.store&&r.push(sr.Store),this.filter&&r.push(sr.Filter),this.lightPush&&r.push(sr.LightPush));let i=[];return r.includes(sr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(e=>i.push(e)):ww.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(sr.Store)&&(this.store?i.push(this.store.protocol.multicodec):ww.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(sr.LightPush)&&(this.lightPush?i.push(this.lightPush.protocol.multicodec):ww.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(sr.Filter)&&(this.filter?i.push(this.filter.multicodec):ww.error("Filter codec not included in dial codec: protocol not mounted locally")),ww.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 wb(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 wv="bootstrap",wS={store:2,filter:1,lightPush:1};var wA=r(4755),wI=r(6398);function wT(e){return new Uint8Array(wI.keccak256.arrayBuffer(e))}function wR(e,t,r){try{let n=wA.Pc.fromCompact(e.slice(0,64));return wA.T(n,t,r)}catch{return!1}}let w_="Invalid record id";function wk(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 wC 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,af.Md)(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(w_)}get rs(){let e=this.get("rs");if(e)return aA(e)}get rsv(){let e=this.get("rsv");if(e)return aA(e)}get ip(){return wB(this,"ip","ip4")}set ip(e){wP(this,"ip","ip4",e)}get tcp(){return wD(this,"tcp","tcp")}set tcp(e){wN(this,"tcp","tcp",e)}get udp(){return wD(this,"udp","udp")}set udp(e){wN(this,"udp","udp",e)}get ip6(){return wB(this,"ip6","ip6")}set ip6(e){wP(this,"ip6","ip6",e)}get tcp6(){return wD(this,"tcp6","tcp")}set tcp6(e){wN(this,"tcp6","tcp",e)}get udp6(){return wD(this,"udp6","udp")}set udp6(e){wN(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(dQ(s))}return t}(e)}set multiaddrs(e){wL(this,"multiaddrs",e,wk)}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){wL(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 wB(e,t,r){let n=e.get(t);if(n)return dO(r,n)}function wD(e,t,r){let n=e.get(t);if(n)return Number(dO(r,n))}function wP(e,t,r,n){wL(e,t,n,dM.bind({},r))}function wN(e,t,r,n){wP(e,t,r,n?.toString(10))}function wL(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function wx(e,t){return wA.Xx(wT(t),e,{der:!1})}let wO=new a_("enr");(nH=ov||(ov={})).TCP="tcp",nH.UDP="udp",(nq=oS||(oS={})).TCP4="tcp4",nq.UDP4="udp4",nq.TCP6="tcp6",nq.UDP6="udp6";class wM extends wC{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){let n=new wM(e,t,r);try{let e=n.publicKey;e&&(n.peerId=await function(e){let t=new gu.secp256k1.Secp256k1PublicKey(e);return du(t.bytes,void 0)}(e))}catch(e){wO.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){let t=wA.E9.fromHex(e),r=t.toRawBytes(!1);return(0,af.ci)(wT(r.slice(1)))}(this.publicKey):void 0;throw Error(w_)}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,dQ("/"+a+"/"+dO(a,s)).encapsulate(dQ("/"+o+"/"+dO(o,l)))}}).bind({},this);get shardInfo(){return this.rs&&this.rsv&&wO.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(oS)){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(w_);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return wR(t,wT(e),this.publicKey)}async sign(e,t){if("v4"===this.id)this.signature=await wx(t,e);else throw Error(w_);return this.signature}}let wU=!1,wF=!1,wV={debug:1,default:2,info:2,warning:3,error:4,off:5},wK=2,wH=null,wq=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}();(n$=oA||(oA={})).DEBUG="DEBUG",n$.INFO="INFO",n$.WARNING="WARNING",n$.ERROR="ERROR",n$.OFF="OFF",(nz=oI||(oI={})).UNKNOWN_ERROR="UNKNOWN_ERROR",nz.NOT_IMPLEMENTED="NOT_IMPLEMENTED",nz.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",nz.NETWORK_ERROR="NETWORK_ERROR",nz.SERVER_ERROR="SERVER_ERROR",nz.TIMEOUT="TIMEOUT",nz.BUFFER_OVERRUN="BUFFER_OVERRUN",nz.NUMERIC_FAULT="NUMERIC_FAULT",nz.MISSING_NEW="MISSING_NEW",nz.INVALID_ARGUMENT="INVALID_ARGUMENT",nz.MISSING_ARGUMENT="MISSING_ARGUMENT",nz.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",nz.CALL_EXCEPTION="CALL_EXCEPTION",nz.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",nz.NONCE_EXPIRED="NONCE_EXPIRED",nz.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",nz.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",nz.TRANSACTION_REPLACED="TRANSACTION_REPLACED",nz.ACTION_REJECTED="ACTION_REJECTED";let w$="0123456789abcdef";class wz{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){let r=e.toLowerCase();null==wV[r]&&this.throwArgumentError("invalid log level name","logLevel",e),wK>wV[r]||console.log.apply(console,t)}debug(...e){this._log(wz.levels.DEBUG,e)}info(...e){this._log(wz.levels.INFO,e)}warn(...e){this._log(wz.levels.WARNING,e)}makeError(e,t,r){if(wF)return this.makeError("censored error",t,{});t||(t=wz.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+=w$[t[e]>>4]+w$[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 oI.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 oI.CALL_EXCEPTION:case oI.INSUFFICIENT_FUNDS:case oI.MISSING_NEW:case oI.NONCE_EXPIRED:case oI.REPLACEMENT_UNDERPRICED:case oI.TRANSACTION_REPLACED:case oI.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,wz.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"),wq&&this.throwError("platform missing String.prototype.normalize",wz.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:wq})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,wz.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,wz.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,wz.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,wz.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){(e===Object||null==e)&&this.throwError("missing new",wz.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",wz.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||null==e)&&this.throwError("missing new",wz.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return wH||(wH=new wz("logger/5.7.0")),wH}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",wz.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),wU){if(!e)return;this.globalLogger().throwError("error censorship permanent",wz.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}wF=!!e,wU=!!t}static setLogLevel(e){let t=wV[e.toLowerCase()];if(null==t){wz.globalLogger().warn("invalid log level - "+e);return}wK=t}static from(e){return new wz(e)}}wz.errors=oI,wz.levels=oA;let wG=new wz("bytes/5.7.0");function wj(e){return!!e.toHexString}function wW(e){return e.slice||(e.slice=function(){let t=Array.prototype.slice.call(arguments);return wW(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function wY(e){return"number"==typeof e&&e==e&&e%1==0}function wX(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e||!wY(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){let r=e[t];if(!wY(r)||r<0||r>=256)return!1}return!0}function wJ(e,t){if(t||(t={}),"number"==typeof e){wG.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),wW(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),wj(e)&&(e=e.toHexString()),wQ(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":wG.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 wW(new Uint8Array(n))}return wX(e)?wW(new Uint8Array(e)):wG.throwArgumentError("invalid arrayify value","value",e)}function wQ(e,t){return"string"==typeof e&&!!e.match(/^0x[0-9A-Fa-f]*$/)&&(!t||e.length===2+2*t)}let wZ="0123456789abcdef";function w0(e,t){if(t||(t={}),"number"==typeof e){wG.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=wZ[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),wj(e))return e.toHexString();if(wQ(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":wG.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(wX(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=wZ[(240&n)>>4]+wZ[15&n]}return t}return wG.throwArgumentError("invalid hexlify value","value",e)}let w1=new wz("rlp/5.7.0");function w2(e){let t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function w3(e,t,r){let n=0;for(let i=0;i<r;i++)n=256*n+e[t+i];return n}function w4(e,t,r,n){let i=[];for(;r<t+1+n;){let s=w6(e,r);i.push(s.result),(r+=s.consumed)>t+1+n&&w1.throwError("child data too short",wz.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:i}}function w6(e,t){if(0===e.length&&w1.throwError("data too short",wz.errors.BUFFER_OVERRUN,{}),e[t]>=248){let r=e[t]-247;t+1+r>e.length&&w1.throwError("data short segment too short",wz.errors.BUFFER_OVERRUN,{});let n=w3(e,t+1,r);return t+1+r+n>e.length&&w1.throwError("data long segment too short",wz.errors.BUFFER_OVERRUN,{}),w4(e,t,t+1+r,r+n)}if(e[t]>=192){let r=e[t]-192;return t+1+r>e.length&&w1.throwError("data array too short",wz.errors.BUFFER_OVERRUN,{}),w4(e,t,t+1,r)}if(e[t]>=184){let r=e[t]-183;t+1+r>e.length&&w1.throwError("data array too short",wz.errors.BUFFER_OVERRUN,{});let n=w3(e,t+1,r);t+1+r+n>e.length&&w1.throwError("data array too short",wz.errors.BUFFER_OVERRUN,{});let i=w0(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&&w1.throwError("data too short",wz.errors.BUFFER_OVERRUN,{});let n=w0(e.slice(t+1,t+1+r));return{consumed:1+r,result:n}}return{consumed:1,result:w0(e[t])}}let w8=new a_("enr:decoder");class w5{static fromString(e){if(!e.startsWith(wM.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${wM.RECORD_PREFIX}'`);return w5.fromRLP((0,hr.m)(e.slice(4),"base64url"))}static fromRLP(e){let t=(function(e){let t=wJ(e),r=w6(t,0);return r.consumed!==t.length&&w1.throwArgumentError("invalid rlp data","data",e),r.result})(e).map(af.nr);return w9(t)}}async function w9(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,af.Md)(n[e])]=n[e+1]}catch(t){w8.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}let s=r.length?BigInt("0x"+(0,af.ci)(r)):BigInt(0),o=await wM.create(i,s,t);return function(e,t,r,n){let i=(0,af.nr)(w0(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=w2(r.length);return n.unshift(247+n.length),n.concat(r)}wQ(t)&&!(t.length%2)||wX(t)||w1.throwArgumentError("RLP object must be BytesLike","object",t);let r=Array.prototype.slice.call(wJ(t));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;let n=w2(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 w7=/^(\d{1,3}\.){3,3}\d{1,3}$/,Ee=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Et={name:"v4",size:4,isFormat:e=>w7.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]}`)},Er={name:"v6",size:16,isFormat:e=>e.length>0&&Ee.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 En(e){if(Et.isFormat(e))return Et.size;if(Er.isFormat(e))return Er.size;throw Error(`Invalid ip address: ${e}`)}function Ei(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 Es(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 Eo(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 Ea(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 El(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 Ec(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 Eu(e,t,r){let n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(Ec(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 Eu.bytes=i-r,t}function Eh(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 Eh.bytes=r-t,n}Eu.bytes=0,Eh.bytes=0;let Ed=e=>e instanceof Uint8Array;function Ep(e){return"string"==typeof e?Ec(e):e.byteLength}function Ef(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Eu(e)}function Eg(e,t,r){if("string"!=typeof t)throw Error("unknown input type");return Eu(t,e,r),Eu.bytes}let Em=(e,t)=>16777216*e[t]+65536*e[t+1]+256*e[t+2]+e[t+3],Ey=(e,t)=>e[t]<<8|e[t+1],Eb=(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),Ew=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function EE(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 Ev({bytes:e=0,encode:t,decode:r,encodingLength:n}){return t.bytes=e,r.bytes=e,{encode:t,decode:r,encodingLength:n||(()=>e)}}let ES=Ev({encode(e,t,r){t||(t=new Uint8Array(ES.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=Eg(t,e[n],r+1);t[r]=i,r+=i+1}}return t[r++]=0,ES.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(Eh(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=Ey(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 ES.decode.bytes=s,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:Ep(e.replace(/^\.|\.$/gm,""))+2}),EA=Ev({encode(e,t,r){t||(t=new Uint8Array(EA.encodingLength(e))),r||(r=0);let n=Eg(t,e,r+1);return t[r]=n,EA.encode.bytes=n+1,t},decode(e,t){t||(t=0);let r=e[t],n=Eh(e,t+1,t+1+r);return EA.decode.bytes=r+1,n},encodingLength:e=>Ep(e)+1}),EI=Ev({bytes:12,encode(e,t,r){t||(t=new Uint8Array(EI.encodingLength(e))),r||(r=0);let n=32767&(e.flags||0),i="response"===e.type?32768:0;return Ew(t,e.id||0,r),Ew(t,n|i,r+2),Ew(t,e.questions.length,r+4),Ew(t,e.answers.length,r+6),Ew(t,e.authorities.length,r+8),Ew(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=Ey(e,t+2);return{id:Ey(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(Ey(e,t+4)),answers:Array(Ey(e,t+6)),authorities:Array(Ey(e,t+8)),additionals:Array(Ey(e,t+10))}},encodingLength:()=>12}),ET=Ev({encode(e,t,r){t||(t=new Uint8Array(ET.encodingLength(e))),r||(r=0);let n=e.length;return Ew(t,n,r),EE(e,t,r+2,0,n),ET.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=Ey(e,t),n=e.slice(t+2,t+2+r);return ET.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),ER=Ev({encode:(e,t,r)=>(t||(t=new Uint8Array(ER.encodingLength(e))),r||(r=0),ES.encode(e,t,r+2),Ew(t,ES.encode.bytes,r),ER.encode.bytes=ES.encode.bytes+2,t),decode(e,t){t||(t=0);let r=Ey(e,t),n=ES.decode(e,t+2);return ER.decode.bytes=r+2,n},encodingLength:e=>ES.encodingLength(e)+2}),E_=Ev({encode(e,t,r){t||(t=new Uint8Array(E_.encodingLength(e))),r||(r=0);let n=r;return r+=2,ES.encode(e.mname,t,r),r+=ES.encode.bytes,ES.encode(e.rname,t,r),r+=ES.encode.bytes,Eb(t,e.serial||0,r),r+=4,Eb(t,e.refresh||0,r),r+=4,Eb(t,e.retry||0,r),r+=4,Eb(t,e.expire||0,r),r+=4,Eb(t,e.minimum||0,r),r+=4,Ew(t,r-n-2,n),E_.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mname=ES.decode(e,t),t+=ES.decode.bytes,n.rname=ES.decode(e,t),t+=ES.decode.bytes,n.serial=Em(e,t),t+=4,n.refresh=Em(e,t),t+=4,n.retry=Em(e,t),t+=4,n.expire=Em(e,t),t+=4,n.minimum=Em(e,t),t+=4,E_.decode.bytes=t-r,n},encodingLength:e=>22+ES.encodingLength(e.mname)+ES.encodingLength(e.rname)}),Ek=Ev({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++)if("string"==typeof e[t]&&(e[t]=Ef(e[t])),!Ed(e[t]))throw Error("Must be a Buffer");t||(t=new Uint8Array(Ek.encodingLength(e))),r||(r=0);let n=r;return r+=2,e.forEach(function(e){t[r++]=e.length,EE(e,t,r,0,e.length),r+=e.length}),Ew(t,r-n-2,n),Ek.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=Ey(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 Ek.decode.bytes=t-r,i},encodingLength(e){Array.isArray(e)||(e=[e]);let t=2;return e.forEach(function(e){"string"==typeof e?t+=Ep(e)+1:t+=e.length+1}),t}}),EC=Ev({encode(e,t,r){t||(t=new Uint8Array(EC.encodingLength(e))),r||(r=0),"string"==typeof e&&(e=Ef(e)),e||(e=new Uint8Array(0));let n=r;r+=2;let i=e.length;return EE(e,t,r,0,i),r+=i,Ew(t,r-n-2,n),EC.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=Ey(e,t);t+=2;let i=e.slice(t,t+n);return t+=n,EC.decode.bytes=t-r,i},encodingLength:e=>e?(Ed(e)?e.length:Ep(e))+2:2}),EB=Ev({encode(e,t,r){t||(t=new Uint8Array(EB.encodingLength(e))),r||(r=0);let n=r;return r+=2,EA.encode(e.cpu,t,r),r+=EA.encode.bytes,EA.encode(e.os,t,r),r+=EA.encode.bytes,Ew(t,r-n-2,n),EB.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.cpu=EA.decode(e,t),t+=EA.decode.bytes,n.os=EA.decode(e,t),t+=EA.decode.bytes,EB.decode.bytes=t-r,n},encodingLength:e=>EA.encodingLength(e.cpu)+EA.encodingLength(e.os)+2}),ED=Ev({encode:(e,t,r)=>(t||(t=new Uint8Array(ED.encodingLength(e))),r||(r=0),ES.encode(e,t,r+2),Ew(t,ES.encode.bytes,r),ED.encode.bytes=ES.encode.bytes+2,t),decode(e,t){t||(t=0);let r=ES.decode(e,t+2);return ED.decode.bytes=ES.decode.bytes+2,r},encodingLength:e=>ES.encodingLength(e)+2}),EP=Ev({encode(e,t,r){t||(t=new Uint8Array(EP.encodingLength(e))),r||(r=0),Ew(t,e.priority||0,r+2),Ew(t,e.weight||0,r+4),Ew(t,e.port||0,r+6),ES.encode(e.target,t,r+8);let n=ES.encode.bytes+6;return Ew(t,n,r),EP.encode.bytes=n+2,t},decode(e,t){t||(t=0);let r=Ey(e,t),n={};return n.priority=Ey(e,t+2),n.weight=Ey(e,t+4),n.port=Ey(e,t+6),n.target=ES.decode(e,t+8),EP.decode.bytes=r+2,n},encodingLength:e=>8+ES.encodingLength(e.target)}),EN=Ev({encode(e,t,r){let n=EN.encodingLength(e);return t||(t=new Uint8Array(EN.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=EN.ISSUER_CRITICAL),Ew(t,n-2,r),t[r+=2]=e.flags||0,r+=1,EA.encode(e.tag,t,r),r+=EA.encode.bytes,Eg(t,e.value,r),r+=Ep(e.value),EN.encode.bytes=n,t},decode(e,t){t||(t=0);let r=Ey(e,t);t+=2;let n=t,i={};return i.flags=e[t],t+=1,i.tag=EA.decode(e,t),t+=EA.decode.bytes,i.value=Eh(e,t,n+r),i.issuerCritical=!!(i.flags&EN.ISSUER_CRITICAL),EN.decode.bytes=r+2,i},encodingLength:e=>EA.encodingLength(e.tag)+EA.encodingLength(e.value)+2});EN.ISSUER_CRITICAL=128;let EL=Ev({encode(e,t,r){t||(t=new Uint8Array(EL.encodingLength(e))),r||(r=0);let n=r;return r+=2,Ew(t,e.preference||0,r),r+=2,ES.encode(e.exchange,t,r),r+=ES.encode.bytes,Ew(t,r-n-2,n),EL.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.preference=Ey(e,t),t+=2,n.exchange=ES.decode(e,t),t+=ES.decode.bytes,EL.decode.bytes=t-r,n},encodingLength:e=>4+ES.encodingLength(e.exchange)}),Ex=Ev({encode:(e,t,r)=>(t||(t=new Uint8Array(Ex.encodingLength(e))),r||(r=0),Ew(t,4,r),r+=2,Et.encode(e,t,r),t),decode(e,t){t||(t=0),t+=2;let r=Et.decode(e,t);return r},bytes:6}),EO=Ev({encode:(e,t,r)=>(t||(t=new Uint8Array(EO.encodingLength(e))),r||(r=0),Ew(t,16,r),r+=2,Er.encode(e,t,r),EO.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;let r=Er.decode(e,t);return EO.decode.bytes=18,r},bytes:18}),EM=e=>new Uint8Array(e),EU=Ev({encode(e,t,r){t||(t=new Uint8Array(EU.encodingLength(e))),r||(r=0);let n=r,i=El(e.code);if(Ew(t,i,r),r+=2,e.data)Ew(t,e.data.length,r),r+=2,EE(e.data,t,r),r+=e.data.length;else switch(i){case 8:{let n=e.sourcePrefixLength||0,i=e.family||(En(e.ip)===Et.size?1:2),s=function(e,t,r){r=~~r;let n=En(e);return("function"==typeof t&&(t=t(r+n)),n===Et.size)?Et.encode(e,t,r):Er.encode(e,t,r)}(e.ip,EM),o=Math.ceil(n/8);Ew(t,o+4,r),r+=2,Ew(t,i,r),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,EE(s,t,r,0,o),r+=o}break;case 11:e.timeout?(Ew(t,2,r),r+=2,Ew(t,e.timeout,r)):Ew(t,0,r),r+=2;break;case 12:{let n=e.length||0;Ew(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(Ew(t,n,r),r+=2,e.tags))Ew(t,i,r),r+=2}break;default:throw Error(`Unknown roption code: ${e.code}`)}return EU.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={};r.code=Ey(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=Ey(e,t);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=Ey(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{let i=new Uint8Array(1===r.family?4:16);EE(e,i,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===Et.size)return Et.decode(e,t,r);if(r===Er.size)return Er.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${Et.size} for v4 or ${Er.size} for v6.`)}(i)}break;case 11:n>0&&(r.timeout=Ey(e,t),t+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(Ey(e,t)),t+=2}return EU.decode.bytes=n+4,r},encodingLength(e){if(e.data)return e.data.length+4;let t=El(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}`)}}),EF=Ev({encode(e,t,r){t||(t=new Uint8Array(EF.encodingLength(e))),r||(r=0);let n=r,i=E3(e,EU);return Ew(t,i,r),r=E4(e,EU,t,r+2),EF.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r=t,n=[],i=Ey(e,t);t+=2;let s=0;for(;i>0;)n[s++]=EU.decode(e,t),t+=EU.decode.bytes,i-=EU.decode.bytes;return EF.decode.bytes=t-r,n},encodingLength:e=>2+E3(e||[],EU)}),EV=Ev({encode(e,t,r){t||(t=new Uint8Array(EV.encodingLength(e))),r||(r=0);let n=r,i=e.key;if(!Ed(i))throw Error("Key must be a Buffer");return r+=2,Ew(t,e.flags,r),t[r+=2]=EV.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,r+=1,EE(i,t,r,0,i.length),r+=i.length,EV.encode.bytes=r-n,Ew(t,EV.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=Ey(e,t);if(t+=2,n.flags=Ey(e,t),e[t+=2]!==EV.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,EV.decode.bytes=t-r,n},encodingLength:e=>6+Ep(e.key)});EV.PROTOCOL_DNSSEC=3,EV.ZONE_KEY=128,EV.SECURE_ENTRYPOINT=32768;let EK=Ev({encode(e,t,r){t||(t=new Uint8Array(EK.encodingLength(e))),r||(r=0);let n=r,i=e.signature;if(!Ed(i))throw Error("Signature must be a Buffer");return r+=2,Ew(t,Es(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,Eb(t,e.originalTTL,r),r+=4,Eb(t,e.expiration,r),r+=4,Eb(t,e.inception,r),r+=4,Ew(t,e.keyTag,r),r+=2,ES.encode(e.signersName,t,r),r+=ES.encode.bytes,EE(i,t,r,0,i.length),r+=i.length,EK.encode.bytes=r-n,Ew(t,EK.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=Ey(e,t);return t+=2,n.typeCovered=Ei(Ey(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=Em(e,t),t+=4,n.expiration=Em(e,t),t+=4,n.inception=Em(e,t),t+=4,n.keyTag=Ey(e,t),t+=2,n.signersName=ES.decode(e,t),t+=ES.decode.bytes,n.signature=e.slice(t,r+i+2),t+=n.signature.length,EK.decode.bytes=t-r,n},encodingLength:e=>20+ES.encodingLength(e.signersName)+Ep(e.signature)}),EH=Ev({encode(e,t,r){t||(t=new Uint8Array(EH.encodingLength(e))),r||(r=0);let n=r;return r+=2,ES.encode(e.mbox||".",t,r),r+=ES.encode.bytes,ES.encode(e.txt||".",t,r),r+=ES.encode.bytes,EH.encode.bytes=r-n,Ew(t,EH.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={};return t+=2,n.mbox=ES.decode(e,t)||".",t+=ES.decode.bytes,n.txt=ES.decode(e,t)||".",t+=ES.decode.bytes,EH.decode.bytes=t-r,n},encodingLength:e=>2+ES.encodingLength(e.mbox||".")+ES.encodingLength(e.txt||".")}),Eq=Ev({encode(e,t,r){t||(t=new Uint8Array(Eq.encodingLength(e))),r||(r=0);let n=r,i=[];for(let t=0;t<e.length;t++){let r=Es(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=Ef(i[e]);t[r]=e,t[r+=1]=n.length,r+=1,EE(n,t,r,0,n.length),r+=n.length}return Eq.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=Ei(r<<8|s<<3|e);i.push(t)}}t+=n}return Eq.decode.bytes=t-n,i},encodingLength(e){let t=[];for(let r=0;r<e.length;r++){let n=Es(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}}),E$=Ev({encode(e,t,r){t||(t=new Uint8Array(E$.encodingLength(e))),r||(r=0);let n=r;return r+=2,ES.encode(e.nextDomain,t,r),r+=ES.encode.bytes,Eq.encode(e.rrtypes,t,r),r+=Eq.encode.bytes,E$.encode.bytes=r-n,Ew(t,E$.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=Ey(e,t);return t+=2,n.nextDomain=ES.decode(e,t),t+=ES.decode.bytes,n.rrtypes=Eq.decode(e,t,i-(t-r)),t+=Eq.decode.bytes,E$.decode.bytes=t-r,n},encodingLength:e=>2+ES.encodingLength(e.nextDomain)+Eq.encodingLength(e.rrtypes)}),Ez=Ev({encode(e,t,r){t||(t=new Uint8Array(Ez.encodingLength(e))),r||(r=0);let n=r,i=e.salt;if(!Ed(i))throw Error("salt must be a Buffer");let s=e.nextDomain;if(!Ed(s))throw Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,Ew(t,e.iterations,r),t[r+=2]=i.length,r+=1,EE(i,t,r,0,i.length),t[r+=i.length]=s.length,r+=1,EE(s,t,r,0,s.length),r+=s.length,Eq.encode(e.rrtypes,t,r),r+=Eq.encode.bytes,Ez.encode.bytes=r-n,Ew(t,Ez.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=Ey(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=Ey(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=Eq.decode(e,t,i-(t-r)),t+=Eq.decode.bytes,Ez.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+Eq.encodingLength(e.rrtypes)}),EG=Ev({encode(e,t,r){t||(t=new Uint8Array(EG.encodingLength(e))),r||(r=0);let n=r,i=e.digest;if(!Ed(i))throw Error("Digest must be a Buffer");return r+=2,Ew(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,r+=1,EE(i,t,r,0,i.length),r+=i.length,EG.encode.bytes=r-n,Ew(t,EG.encode.bytes-2,n),t},decode(e,t){t||(t=0);let r=t,n={},i=Ey(e,t);return t+=2,n.keyTag=Ey(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,EG.decode.bytes=t-r,n},encodingLength:e=>6+Ep(e.digest)});function Ej(e){switch(e.toUpperCase()){case"A":return Ex;case"PTR":case"CNAME":case"DNAME":return ED;case"TXT":return Ek;case"NULL":return EC;case"AAAA":return EO;case"SRV":return EP;case"HINFO":return EB;case"CAA":return EN;case"NS":return ER;case"SOA":return E_;case"MX":return EL;case"OPT":return EF;case"DNSKEY":return EV;case"RRSIG":return EK;case"RP":return EH;case"NSEC":return E$;case"NSEC3":return Ez;case"DS":return EG}return ET}let EW=Ev({encode(e,t,r){t||(t=new Uint8Array(EW.encodingLength(e))),r||(r=0);let n=r;if(ES.encode(e.name,t,r),r+=ES.encode.bytes,Ew(t,Es(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw Error("OPT name must be root.");Ew(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,Ew(t,e.flags||0,r+6),r+=8,EF.encode(e.options||[],t,r),r+=EF.encode.bytes}else{let n=Ea(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),Ew(t,n,r+2),Eb(t,e.ttl||0,r+4),r+=8;let i=Ej(e.type);i.encode(e.data,t,r),r+=i.encode.bytes}return EW.encode.bytes=r-n,t},decode(e,t){t||(t=0);let r={},n=t;if(r.name=ES.decode(e,t),t+=ES.decode.bytes,r.type=Ei(Ey(e,t)),"OPT"===r.type)r.udpPayloadSize=Ey(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=Ey(e,t+6),r.flag_do=(r.flags>>15&1)==1,r.options=EF.decode(e,t+8),t+=8+EF.decode.bytes;else{let n=Ey(e,t+2);r.ttl=Em(e,t+4),r.class=Eo(-32769&n),r.flush=!!(32768&n);let i=Ej(r.type);r.data=i.decode(e,t+8),t+=8+i.decode.bytes}return EW.decode.bytes=t-n,r},encodingLength(e){let t=null!==e.data&&void 0!==e.data?e.data:e.options;return ES.encodingLength(e.name)+8+Ej(e.type).encodingLength(t)}}),EY=Ev({encode(e,t,r){t||(t=new Uint8Array(EY.encodingLength(e))),r||(r=0);let n=r;return ES.encode(e.name,t,r),r+=ES.encode.bytes,Ew(t,Es(e.type),r),r+=2,Ew(t,Ea(void 0===e.class?"IN":e.class),r),r+=2,EY.encode.bytes=r-n,e},decode(e,t){t||(t=0);let r=t,n={};n.name=ES.decode(e,t),t+=ES.decode.bytes,n.type=Ei(Ey(e,t)),t+=2,n.class=Eo(Ey(e,t)),t+=2;let i=!!(32768&n.class);return i&&(n.class&=-32769),EY.decode.bytes=t-r,n},encodingLength:e=>ES.encodingLength(e.name)+4}),EX={encode:function(e,t,r){let n=!t;n&&(t=new Uint8Array(E2(e))),r||(r=0);let i=r;return(e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),EI.encode(e,t,r),r+=EI.encode.bytes,r=E4(e.questions,EY,t,r),r=E4(e.answers,EW,t,r),r=E4(e.authorities,EW,t,r),r=E4(e.additionals,EW,t,r),EX.encode.bytes=r-i,n&&E0.bytes!==t.length)?t.slice(0,E0.bytes):t},decode:function(e,t){t||(t=0);let r=t,n=EI.decode(e,t);return t+=EI.decode.bytes,t=E6(n.questions,EY,e,t),t=E6(n.answers,EW,e,t),t=E6(n.authorities,EW,e,t),t=E6(n.additionals,EW,e,t),EX.decode.bytes=t-r,n},encodingLength:function(e){return EI.encodingLength(e)+E3(e.questions||[],EY)+E3(e.answers||[],EW)+E3(e.authorities||[],EW)+E3(e.additionals||[],EW)}};function EJ(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}EX.encode.bytes=0,EX.decode.bytes=0;let EQ={encode:function(e,t,r){return t=EX.encode(EJ(e,"query"),t,r),EQ.encode.bytes=EX.encode.bytes,t},decode:function(e,t){let r=EX.decode(e,t);return EQ.decode.bytes=EX.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r}};EQ.encode.bytes=0,EQ.decode.bytes=0;let EZ={encode:function(e,t,r){return t=EX.encode(EJ(e,"response"),t,r),EZ.encode.bytes=EX.encode.bytes,t},decode:function(e,t){let r=EX.decode(e,t);return EZ.decode.bytes=EX.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r}};EZ.encode.bytes=0,EZ.decode.bytes=0;let E0=EX.encode,E1=EX.decode,E2=EX.encodingLength;function E3(e,t){let r=0;for(let n=0;n<e.length;n++)r+=t.encodingLength(e[n]);return r}function E4(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 E6(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 E8(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}E8("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);let E5=E8("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2),E9="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;E9||(E9=class extends Error{constructor(e="Request aborted."){super(e)}}),E9.prototype.name="AbortError",E9.prototype.code="ABORT_ERR";let E7="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class ve 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}}}ve.prototype.name="HTTPStatusError",ve.prototype.code="HTTP_STATUS";class vt 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)}}}vt.prototype.name="ResponseError",vt.prototype.code="RESPONSE_ERR";class vr extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}vr.prototype.name="TimeoutError",vr.prototype.code="ETIMEOUT";let vn=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,vi=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i,vs=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,vo=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/ig,va=/\[(((pk|name)=([^\]]+)))\]/ig;function vl(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 vc extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${vu.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}vc.prototype.name="InvalidProtocolError",vc.prototype.code="EPROTOCOL";let vu=["http:","https:","udp4:","udp6:"];class vh{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 vd extends vh{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 vp extends vd{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 vf extends vd{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 vg(e){return vi.test(e)&&!vn.test(e)?`[${e}]`:e}class vm extends vh{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=vi.exec(this.host);e&&(this.ipv6=e[1])}!this.ipv4&&vn.test(this.host)&&(this.ipv4=this.host);let t=`${this.protocol}//${vg(this.host)}:${this.port}${this.path}`;try{this.url=new E7(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}${vg(this.host)}${t}${n}${r}${s}${o}${i}`}}function vy(e){let t;if("string"==typeof e)t=function(e){let t=vs.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=vl(o,vo);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=vl(o,va),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 vf({protocol:"udp6:",ipv6:s[1],port:i,pk:t.pk,name:t.name}):new vp({protocol:"udp4:",ipv4:n,port:i,pk:t.pk,name:t.name})}throw new vc(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 vh)return e;t=e}(null===t.protocol||void 0===t.protocol)&&(t.protocol="https:");let r=t.protocol;if("udp4:"===r)return new vp(t);if("udp6:"===r)return new vf(t);if("https:"===r||"http:"===r)return new vm(t);throw new vc(r,JSON.stringify(t))}let vb="application/dns-message";function vw(){}async function vE(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 vv(e,"GET",null,r,n),o={time:Date.now(),data:JSON.parse(Eh(s))};if(i)try{localStorage.setItem(i,JSON.stringify(o))}catch(e){o.time=null}return o}function vv(e,t,r,n,i){return new Promise((s,o)=>{let a=new E7(e);"GET"===t&&r&&(a.search="?dns="+E5.decode(r));let l=a.toString(),c=new XMLHttpRequest;c.open(t,l,!0),c.setRequestHeader("Accept",vb),"POST"===t&&c.setRequestHeader("Content-Type",vb),c.responseType="arraybuffer",c.timeout=n,c.ontimeout=function(){u(new vr(n));try{c.abort()}catch(e){}},c.onreadystatechange=function(){if(c.readyState>1&&200!==c.status&&0!==c.status){u(new ve(l,c.status,t));try{c.abort()}catch(e){}}},c.onerror=function(){u(200===c.status?Error("Inexplicable XHR Error"):new ve(l,c.status,t))},c.onload=function(){if(200!==c.status)u(new ve(l,c.status,t));else{let e;if("string"==typeof c.response)e=Eu(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=vw,i&&i.removeEventListener("abort",h),e?s({error:e,response:c}):s({data:t,response:c})};function h(){u(new E9);try{c.abort()}catch(e){}}})}function vS(e){let t=null===e.time||void 0===e.time?Date.now():e.time,r=e.data.map(e=>(e.endpoint=vy(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 vA=vS({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}),vI=new E7("https://martinheidegger.github.io/dns-query/resolvers.json");function vT(e){return/^@/.test(e)}class vR{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:vI,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?vE(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=>vS({data:e.data.resolvers,time:e.time})).catch(()=>t||vA):Promise.resolve(vA),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=vk),"dns"===e&&(e=vC),"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(vT))try{return Promise.resolve(e.map(vy))}catch(e){return Promise.reject(e)}return this.data().then(t=>e.map(e=>{if(vT(e)){let r=t.endpointByName[e.substring(1)];if(!r)throw Error(`Endpoint ${e} is not known.`);return r}return vy(e)}))}}let v_=new vR;function vk(e){return"https:"===e.protocol||"http:"===e.protocol}function vC(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}let vB=new a_("dns-over-https");class vD{endpoints;retries;static async create(e,t){let r=e??await v_.endpoints("doh");return new vD(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 E9):"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=E0(Object.assign({flags:256},r)),vv(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 vt("Empty.");else try{let e=E1(t);return e.response=r,e}catch(e){n=new vt("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(vy),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 vB.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,af.Md)(e))}):a.push((0,af.Md)(e))}),a}}var vP=r(7935);class vN{static RECORD_PREFIX=wM.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=vN.parseRootValues(e),n=vP.decode.asBytes(t),i=e.split(" sig")[0],s=(0,af.iY)(i),o=(0,hr.m)(r.signature,"base64url").slice(0,64),a=wR(o,wT(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 vL=new a_("discovery:fetch_nodes");async function vx(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(;!vM(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&&vF(e.waku2,n,s)&&(vU(e.waku2,s),a.push(e)),vL.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}return a}async function*vO(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(;!vM(n,s)&&o<i+t;){let e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&vF(e.waku2,n,s)&&(vU(e.waku2,s),yield e),vL.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}}function vM(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function vU(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function vF(e,t,r){if(vM(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 vV=new a_("discovery:dns");class vK{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await vD.create()),new vK(e)}async getPeers(e,t){let r=Math.floor(Math.random()*e.length),{publicKey:n,domain:i}=vN.parseTree(e[r]),s={domain:i,publicKey:n,visits:{}},o=await vx(t,this._errorTolerance,()=>this._search(i,s));return vV.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}=vN.parseTree(e[r]),s={domain:i,publicKey:n,visits:{}};for await(let e of vO(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(vN.ROOT_PREFIX)?vN.ROOT_PREFIX:i.startsWith(vN.BRANCH_PREFIX)?vN.BRANCH_PREFIX:i.startsWith(vN.RECORD_PREFIX)?vN.RECORD_PREFIX:"";try{switch(s){case vN.ROOT_PREFIX:return r=vN.parseAndVerifyRoot(i,t.publicKey),await this._search(r,t);case vN.BRANCH_PREFIX:return n=vN.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 vN.RECORD_PREFIX:return w5.fromString(i);default:return null}}catch(t){return vV.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return vV.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 vH=new a_("peer-discovery-dns");class vq extends lM{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;let{enrUrls:r}=t;vH.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(vH.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 vK.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={[wv]:{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(wv);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:aI(r)}}});i&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[dI](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}(nG=oT||(oT={})).Relay="relay",nG.Store="store",nG.LightPush="lightpush",nG.Filter="filter",(nj=oR||(oR={})).GENERIC_FAIL="Generic error",nj.ENCODE_FAILED="Failed to encode",nj.DECODE_FAILED="Failed to decode",nj.EMPTY_PAYLOAD="Payload is empty",nj.SIZE_TOO_BIG="Size is too big",nj.TOPIC_NOT_CONFIGURED="Topic not configured",nj.NO_PEER_AVAILABLE="No peer available",nj.REMOTE_PEER_FAULT="Remote peer fault",nj.REMOTE_PEER_REJECTED="Remote peer rejected",nj.REQUEST_TIMEOUT="Request timeout",(nW=o_||(o_={})).BACKWARD="backward",nW.FORWARD="forward",(nY=ok||(ok={})).BOOTSTRAP="bootstrap",nY.PEER_EXCHANGE="peer-exchange",nY.LOCAL="local-peer-cache",(nX=oC||(oC={})).PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",nX.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",nX.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",nX.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange",(oB||(oB={})).CONNECTION_STATUS="waku:connection";class v${multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new a_(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool.bind(this)),this.getStream=this.getStream.bind(this),this.streamPool=new Map}async getStream(e){let t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.newStream(e);this.streamPool.delete(t),this.prepareNewStream(e);let n=await r;return n&&"closed"!==n.status?n:this.newStream(e)}async newStream(e){let t=this.getConnections(e.id),r=a7(t);if(!r)throw Error("Failed to get a connection to the peer");return r.newStream(this.multicodec)}prepareNewStream(e){let t=this.newStream(e).catch(()=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()}`)});this.streamPool.set(e.id.toString(),t)}handlePeerUpdateStreamPool=e=>{let t=e.detail.peer;t.protocols.includes(this.multicodec)&&(this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareNewStream(t))}}class vz{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 v$(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 a5(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 a9(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?aS(this.options.shardInfo).shardInfo:void 0),n=function(e,t,r){let n=e.filter(e=>e.tags.has(ok.BOOTSTRAP)).slice(0,r);t>0&&t<n.length&&(n=n.slice(0,t));let i=e.filter(e=>!e.tags.has(ok.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 a8(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}}(nJ=oD||(oD={})).codec=()=>(null==eQ&&(eQ=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),eQ),nJ.encode=e=>(0,ao.LE)(e,nJ.codec()),nJ.decode=(e,t)=>(0,ao.C6)(e,nJ.codec(),t),(nQ=oP||(oP={})).codec=()=>(null==eZ&&(eZ=(0,ao.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),oD.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,aa.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=oD.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),eZ),nQ.encode=e=>(0,ao.LE)(e,nQ.codec()),nQ.decode=(e,t)=>(0,ao.C6)(e,nQ.codec(),t),(n0=(nZ=oN||(oN={})).ContentFilter||(nZ.ContentFilter={})).codec=()=>(null==e1&&(e1=(0,ao.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})),e1),n0.encode=e=>(0,ao.LE)(e,n0.codec()),n0.decode=(e,t)=>(0,ao.C6)(e,n0.codec(),t),nZ.codec=()=>(null==e0&&(e0=(0,ao.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),nZ.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(nZ.ContentFilter.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;default:e.skipType(7&t)}}return n})),e0),nZ.encode=e=>(0,ao.LE)(e,nZ.codec()),nZ.decode=(e,t)=>(0,ao.C6)(e,nZ.codec(),t),(n1=oL||(oL={})).codec=()=>(null==e2&&(e2=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(10),oM.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(oM.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),e2),n1.encode=e=>(0,ao.LE)(e,n1.codec()),n1.decode=(e,t)=>(0,ao.C6)(e,n1.codec(),t),(n2=ox||(ox={})).codec=()=>(null==e3&&(e3=(0,ao.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),oN.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),oL.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=oN.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=oL.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),e3),n2.encode=e=>(0,ao.LE)(e,n2.codec()),n2.decode=(e,t)=>(0,ao.C6)(e,n2.codec(),t),(n3=oO||(oO={})).codec=()=>(null==e4&&(e4=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),e4),n3.encode=e=>(0,ao.LE)(e,n3.codec()),n3.decode=(e,t)=>(0,ao.C6)(e,n3.codec(),t),(n4=oM||(oM={})).codec=()=>(null==e6&&(e6=(0,ao.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),oO.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,aa.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=oO.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),e6),n4.encode=e=>(0,ao.LE)(e,n4.codec()),n4.decode=(e,t)=>(0,ao.C6)(e,n4.codec(),t),(n6=oU||(oU={})).codec=()=>(null==e8&&(e8=(0,ao.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})),e8),n6.encode=e=>(0,ao.LE)(e,n6.codec()),n6.decode=(e,t)=>(0,ao.C6)(e,n6.codec(),t),(n5=e5=(n8=oF||(oF={})).FilterSubscribeType||(n8.FilterSubscribeType={})).SUBSCRIBER_PING="SUBSCRIBER_PING",n5.SUBSCRIBE="SUBSCRIBE",n5.UNSUBSCRIBE="UNSUBSCRIBE",n5.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL",(n9=e9||(e9={}))[n9.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",n9[n9.SUBSCRIBE=1]="SUBSCRIBE",n9[n9.UNSUBSCRIBE=2]="UNSUBSCRIBE",n9[n9.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL",(e5=n8.FilterSubscribeType||(n8.FilterSubscribeType={})).codec=()=>(0,ao.Ji)(e9),n8.codec=()=>(null==e7&&(e7=(0,ao.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!==e9[e.filterSubscribeType]&&(t.uint32(16),n8.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:e5.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=n8.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 ao.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})),e7),n8.encode=e=>(0,ao.LE)(e,n8.codec()),n8.decode=(e,t)=>(0,ao.C6)(e,n8.codec(),t),(n7=oV||(oV={})).codec=()=>(null==te&&(te=(0,ao.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})),te),n7.encode=e=>(0,ao.LE)(e,n7.codec()),n7.decode=(e,t)=>(0,ao.C6)(e,n7.codec(),t),(ie=oK||(oK={})).codec=()=>(null==tt&&(tt=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),oq.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=oq.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),tt),ie.encode=e=>(0,ao.LE)(e,ie.codec()),ie.decode=(e,t)=>(0,ao.C6)(e,ie.codec(),t),(it=oH||(oH={})).codec=()=>(null==tr&&(tr=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),tr),it.encode=e=>(0,ao.LE)(e,it.codec()),it.decode=(e,t)=>(0,ao.C6)(e,it.codec(),t),(ir=oq||(oq={})).codec=()=>(null==tn&&(tn=(0,ao.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),oH.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,aa.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=oH.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),tn),ir.encode=e=>(0,ao.LE)(e,ir.codec()),ir.decode=(e,t)=>(0,ao.C6)(e,ir.codec(),t),(ii=o$||(o$={})).codec=()=>(null==ti&&(ti=(0,ao.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),oW.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=oW.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),ti),ii.encode=e=>(0,ao.LE)(e,ii.codec()),ii.decode=(e,t)=>(0,ao.C6)(e,ii.codec(),t),(is=oz||(oz={})).codec=()=>(null==ts&&(ts=(0,ao.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})),ts),is.encode=e=>(0,ao.LE)(e,is.codec()),is.decode=(e,t)=>(0,ao.C6)(e,is.codec(),t),(io=oG||(oG={})).codec=()=>(null==to&&(to=(0,ao.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),o$.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),oz.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=o$.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=oz.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),to),io.encode=e=>(0,ao.LE)(e,io.codec()),io.decode=(e,t)=>(0,ao.C6)(e,io.codec(),t),(ia=oj||(oj={})).codec=()=>(null==ta&&(ta=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),ta),ia.encode=e=>(0,ao.LE)(e,ia.codec()),ia.decode=(e,t)=>(0,ao.C6)(e,ia.codec(),t),(il=oW||(oW={})).codec=()=>(null==tl&&(tl=(0,ao.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),oj.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,aa.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=oj.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),tl),il.encode=e=>(0,ao.LE)(e,il.codec()),il.decode=(e,t)=>(0,ao.C6)(e,il.codec(),t),(ic=oY||(oY={})).codec=()=>(null==tc&&(tc=(0,ao.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,aa.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})),tc),ic.encode=e=>(0,ao.LE)(e,ic.codec()),ic.decode=(e,t)=>(0,ao.C6)(e,ic.codec(),t),(ih=(iu=oX||(oX={})).Direction||(iu.Direction={})).BACKWARD="BACKWARD",ih.FORWARD="FORWARD",(id=tu||(tu={}))[id.BACKWARD=0]="BACKWARD",id[id.FORWARD=1]="FORWARD",(iu.Direction||(iu.Direction={})).codec=()=>(0,ao.Ji)(tu),iu.codec=()=>(null==th&&(th=(0,ao.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),oY.codec().encode(e.cursor,t)),null!=e.direction&&(t.uint32(24),iu.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=oY.codec().decode(e,e.uint32(),{limits:r.limits?.cursor});break;case 3:n.direction=iu.Direction.codec().decode(e);break;default:e.skipType(7&t)}}return n})),th),iu.encode=e=>(0,ao.LE)(e,iu.codec()),iu.decode=(e,t)=>(0,ao.C6)(e,iu.codec(),t),(ip=oJ||(oJ={})).codec=()=>(null==td&&(td=(0,ao.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})),td),ip.encode=e=>(0,ao.LE)(e,ip.codec()),ip.decode=(e,t)=>(0,ao.C6)(e,ip.codec(),t),(ig=oQ||(oQ={})).codec=()=>(null==tp&&(tp=(0,ao.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),oJ.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),oX.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 ao.sv('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(oJ.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=oX.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})),tp),ig.encode=e=>(0,ao.LE)(e,ig.codec()),ig.decode=(e,t)=>(0,ao.C6)(e,ig.codec(),t),(iy=tf=(im=oZ||(oZ={})).HistoryError||(im.HistoryError={})).NONE="NONE",iy.INVALID_CURSOR="INVALID_CURSOR",iy.TOO_MANY_RESULTS="TOO_MANY_RESULTS",iy.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",(ib=tg||(tg={}))[ib.NONE=0]="NONE",ib[ib.INVALID_CURSOR=1]="INVALID_CURSOR",ib[ib.TOO_MANY_RESULTS=429]="TOO_MANY_RESULTS",ib[ib.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",(tf=im.HistoryError||(im.HistoryError={})).codec=()=>(0,ao.Ji)(tg),im.codec=()=>(null==tm&&(tm=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(let r of e.messages)t.uint32(18),o2.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(26),oX.codec().encode(e.pagingInfo,t)),null!=e.error&&0!==tg[e.error]&&(t.uint32(32),im.HistoryError.codec().encode(e.error,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{let n={messages:[],error:tf.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 ao.sv('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(o2.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 3:n.pagingInfo=oX.codec().decode(e,e.uint32(),{limits:r.limits?.pagingInfo});break;case 4:n.error=im.HistoryError.codec().decode(e);break;default:e.skipType(7&t)}}return n})),tm),im.encode=e=>(0,ao.LE)(e,im.codec()),im.decode=(e,t)=>(0,ao.C6)(e,im.codec(),t),(iw=o0||(o0={})).codec=()=>(null==ty&&(ty=(0,ao.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),oQ.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),oZ.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=oQ.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=oZ.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),ty),iw.encode=e=>(0,ao.LE)(e,iw.codec()),iw.decode=(e,t)=>(0,ao.C6)(e,iw.codec(),t),(iE=o1||(o1={})).codec=()=>(null==tb&&(tb=(0,ao.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,aa.u)(0),merkleRoot:(0,aa.u)(0),epoch:(0,aa.u)(0),shareX:(0,aa.u)(0),shareY:(0,aa.u)(0),nullifier:(0,aa.u)(0),rlnIdentifier:(0,aa.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})),tb),iE.encode=e=>(0,ao.LE)(e,iE.codec()),iE.decode=(e,t)=>(0,ao.C6)(e,iE.codec(),t),(iv=o2||(o2={})).codec=()=>(null==tw&&(tw=(0,ao.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),o1.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,aa.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=o1.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),tw),iv.encode=e=>(0,ao.LE)(e,iv.codec()),iv.decode=(e,t)=>(0,ao.C6)(e,iv.codec(),t),(iS=o3||(o3={})).codec=()=>(null==tE&&(tE=(0,ao.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})),tE),iS.encode=e=>(0,ao.LE)(e,iS.codec()),iS.decode=(e,t)=>(0,ao.C6)(e,iS.codec(),t),(iA=o4||(o4={})).codec=()=>(null==tv&&(tv=(0,ao.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})),tv),iA.encode=e=>(0,ao.LE)(e,iA.codec()),iA.decode=(e,t)=>(0,ao.C6)(e,iA.codec(),t),(iI=o6||(o6={})).codec=()=>(null==tS&&(tS=(0,ao.yw)((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(let r of e.peerInfos)t.uint32(10),o3.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 ao.sv('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(o3.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),tS),iI.encode=e=>(0,ao.LE)(e,iI.codec()),iI.decode=(e,t)=>(0,ao.C6)(e,iI.codec(),t),(iT=o8||(o8={})).codec=()=>(null==tA&&(tA=(0,ao.yw)((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),o4.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),o6.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=o4.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=o6.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),tA),iT.encode=e=>(0,ao.LE)(e,iT.codec()),iT.decode=(e,t)=>(0,ao.C6)(e,iT.codec(),t),(iR=o5||(o5={})).codec=()=>(null==tI&&(tI=(0,ao.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 ao.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})),tI),iR.encode=e=>(0,ao.LE)(e,iR.codec()),iR.decode=(e,t)=>(0,ao.C6)(e,iR.codec(),t),(i_=o9||(o9={})).codec=()=>(null==tT&&(tT=(0,ao.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 ao.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})),tT),i_.encode=e=>(0,ao.LE)(e,i_.codec()),i_.decode=(e,t)=>(0,ao.C6)(e,i_.codec(),t);class vG{proto;constructor(e){this.proto=e}static createRequest(e){let{numPeers:t}=e;return new vG({query:{numPeers:t},response:void 0})}encode(){return o8.encode(this.proto)}static decode(e){let t=o8.decode(e);return new vG(t)}get query(){return this.proto.query}get response(){return this.proto.response}}let vj="/vac/waku/peer-exchange/2.0.0-alpha1",vW=new a_("peer-exchange");class vY extends vz{constructor(e,t){super(vj,e,vW,t)}async query(e){let{numPeers:t}=e,r=vG.createRequest({numPeers:BigInt(t)}),n=await this.peerStore.get(e.peerId);if(!n)return{peerInfos:null,error:oR.NO_PEER_AVAILABLE};let i=await this.getStream(n),s=await a0([r.encode()],a$,i,aj,async e=>await aL(e));try{let e=new aK;s.forEach(t=>{e.append(t)});let{response:t}=vG.decode(e);if(!t)return vW.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:oR.EMPTY_PAYLOAD};let r=await Promise.all(t.peerInfos.map(e=>e.enr).filter(al).map(async e=>({ENR:await w5.fromRLP(e)})));return{peerInfos:r,error:null}}catch(e){return vW.error("Failed to decode push reply",e),{peerInfos:null,error:oR.DECODE_FAILED}}}}let vX=new a_("peer-exchange-discovery"),vJ=ok.PEER_EXCHANGE;class vQ extends lM{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{let{protocols:t,peerId:r}=e.detail;!t.includes(vj)||this.queryingPeers.has(r.toString())||(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch(e=>vX.error(`Error querying peer ${e}`)))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new vY(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(vX.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(vX.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[dI](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{let t=e.toString(),{queryInterval:r=1e4,maxRetries:n=3}=this.options;vX.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=>{vX.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 vX.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(let e of r){let{ENR:t}=e;if(!t){vX.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:{[vJ]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...i&&{metadata:{shardInfo:aI(i)}}}),vX.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){vX.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}let vZ=new a_("peer-exchange-discovery"),v0=ok.LOCAL;class v1 extends lM{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(vZ.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers),this.peers)){let r=await yD({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[dQ(t)],tags:{[this.options?.tagName??v0]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:[dQ(t)]}})))}vZ.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(vZ.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=function(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}(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(v2)}catch(e){return vZ.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){vZ.error("Error saving peers to local storage:",e)}}}function v2(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}let v3={lightPush:1,filter:1,store:1};async function v4(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 lz(e,t)}:{};return wu({connectionManager:{minConnections:1},transports:[function(e={}){return t=>new m$(t,e)}({filter:mq})],streamMuxers:[function(e={}){return t=>new mI(t,e)}()],connectionEncryption:[function(e={}){return t=>new dA(t,e)}()],...r,services:{identify:function(e={}){return t=>new mi(t,e)}({agentVersion:n??"js-waku"}),ping:function(e={}){return t=>new m_(t,e)}(),...i,...t?{pubsub:t}:{},...r?.services}})}async function v6(e){let t=e.shardInfo?aS(e.shardInfo):void 0;e.pubsubTopics=t?.pubsubTopics??e.pubsubTopics??[aN];let r=e?.libp2p??{},n=r.peerDiscovery??[];if(e?.defaultBootstrap&&n.push(...function(e){let t=[function(e,t=wS){return r=>new vq(r,{enrUrls:e,wantedNodeCapabilityCount:t})}(["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im"],v3),(e,t)=>new v1(e,t),t=>new vQ(t,e)];return t}(e.pubsubTopics)),e?.bootstrapPeers){var i;n.push((i={list:e.bootstrapPeers},e=>new pv(e,i)))}r.peerDiscovery=n;let s=await v4(t?.shardInfo,function(e={}){return t=>{e={...e,msgIdFn:({data:e})=>(0,ap.J)(e),globalSignaturePolicy:s_.StrictNoSign,fallbackToFloodsub:!1};let r=new yf(t,e);return r.multicodecs=ym,r}}(e),r,e?.userAgent);return s}},9710:function(e,t,r){"use strict";r.d(t,{Md:function(){return a},ci:function(){return o},iY:function(){return l},nr:function(){return s},zo:function(){return c}});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}let o=e=>(0,i.B)(e,"base16"),a=e=>(0,i.B)(e,"utf8"),l=e=>(0,n.m)(e,"utf8");function c(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}},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 K}});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 m}});var o={};r.r(o),r.d(o,{base256emoji:function(){return E}});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 R}});var c={};r.r(c),r.d(c,{identity:function(){return k}});var u={};r.r(u),r.d(u,{code:function(){return P},decode:function(){return L},encode:function(){return N},name:function(){return D}});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}),m=(0,d.ET)({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),y=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=y.reduce((e,t,r)=>(e[r]=t,e),[]),w=y.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]),E=(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 v=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 R=(0,d.ET)({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _=r(495);let k=(0,d.Dp)({prefix:"\x00",name:"identity",encode:e=>(0,_.BB)(e),decode:e=>(0,_.mL)(e)}),C=new TextEncoder,B=new TextDecoder,D="json",P=512;function N(e){return C.encode(JSON.stringify(e))}function L(e){return JSON.parse(B.decode(e))}let x="raw",O=85;function M(e){return(0,_.oQ)(e)}function U(e){return(0,_.oQ)(e)}var F=r(9137),V=r(1818);r(8590),r(50),r(4511),r(9716);let K={...c,...s,...l,...n,...i,...v,...a,...I,...T,...o};({...V,...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 K},C6:function(){return v},LE:function(){return M},Ji:function(){return F},yw:function(){return V}});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>m&&(n=0n,++r>m&&(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 m=4294967296n;function y(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 E{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 v(e,t,r){let n=new E(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 R{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}let _=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 k{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 D((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(P,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(P,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(P,t.length(),t)}sint64Number(e){let t=f.fromNumber(e).zzEncode();return this._push(P,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(C,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(C,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(y,t,e):this._push(C,1,0)}fork(){return this.states=new R(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):_(e)),n=0;for(;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function C(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 D extends I{next;constructor(e,t){super(B,e,t),this.next=void 0}}function P(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?y(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set((0,A.m)(e),r)}function M(e,t){let r=new k;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 V(e,t){return U("message",i.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(k.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(x,t,e),this},k.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 K 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}}]); |