From 0a505c7b427004171a402ed521e9a246c3ff0331 Mon Sep 17 00:00:00 2001 From: status-im-auto Date: Thu, 25 Jul 2024 22:55:25 +0000 Subject: [PATCH] Updates --- dogfooding/index.js | 3 ++- dogfooding/index.js.map | 1 + flush-notes/404.html | 2 +- .../_buildManifest.js | 0 .../_ssgManifest.js | 0 flush-notes/index.html | 2 +- flush-notes/index.txt | 2 +- flush-notes/view.html | 2 +- flush-notes/view.txt | 2 +- 9 files changed, 8 insertions(+), 6 deletions(-) create mode 100644 dogfooding/index.js.map rename flush-notes/_next/static/{VJD631qiVEcQNWfhl6_Ve => QOeKfE5AVixhzCg9mihTc}/_buildManifest.js (100%) rename flush-notes/_next/static/{VJD631qiVEcQNWfhl6_Ve => QOeKfE5AVixhzCg9mihTc}/_ssgManifest.js (100%) diff --git a/dogfooding/index.js b/dogfooding/index.js index 33cbcc7..440bcea 100644 --- a/dogfooding/index.js +++ b/dogfooding/index.js @@ -1,2 +1,3 @@ /*! For license information please see index.js.LICENSE.txt */ -(()=>{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,s=2,i=!0;s{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),s=new Array(123),i=0;i<64;)s[n[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;r.encode=function(e,t,r){for(var s,i=null,o=[],a=0,c=0;t>2],s=(3&l)<<4,c=1;break;case 1:o[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:o[a++]=n[s|l>>6],o[a++]=n[63&l],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[s],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,i=r,a=0,c=0;c1)break;if(void 0===(l=s[l]))throw Error(o);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(o);return r-i},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function s(e){if("string"!=typeof e){var r=i();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";e.exports=i;var n=r(8045),s=r(4153)("fs");function i(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&s&&s.readFile?s.readFile(e,(function(n,s){return n&&"undefined"!=typeof XMLHttpRequest?i.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))})):i.xhr(e,t,r):n(i,this,e,t)}i.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var s=0;s{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3]}function i(e,n,s){t[0]=e,n[s]=r[3],n[s+1]=r[2],n[s+2]=r[1],n[s+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?s:i,e.writeFloatBE=n?i:s,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var s=t<0?1:0;if(s&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var i=Math.floor(Math.log(t)/Math.LN2);e((s<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),s=2*(n>>31)+1,i=n>>>23&255,o=8388607&n;return 255===i?o?NaN:s*(1/0):0===i?1401298464324817e-60*s*o:s*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,i)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3],n[s+4]=r[4],n[s+5]=r[5],n[s+6]=r[6],n[s+7]=r[7]}function i(e,n,s){t[0]=e,n[s]=r[7],n[s+1]=r[6],n[s+2]=r[5],n[s+3]=r[4],n[s+4]=r[3],n[s+5]=r[2],n[s+6]=r[1],n[s+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?s:i,e.writeDoubleBE=n?i:s,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,s,i){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,i+t),e(1/n>0?0:2147483648,s,i+r);else if(isNaN(n))e(0,s,i+t),e(2146959360,s,i+r);else if(n>17976931348623157e292)e(0,s,i+t),e((o<<31|2146435072)>>>0,s,i+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,i+t),e((o<<31|a/4294967296)>>>0,s,i+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,s,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,s,i+r)}}}function o(e,t,r,n,s){var i=e(n,s+t),o=e(n,s+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+i;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,i,4,0)}(),e}function r(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 n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},s=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),s="";r&&(s=t.shift()+"/");for(var i=0;i0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return s+t.join("/")};r.resolve=function(e,t,r){return r||(t=s(t)),n(t)?t:(r||(e=s(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?s(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,s=n>>>1,i=null,o=n;return function(r){if(r<1||r>s)return e(r);o+r>n&&(i=e(n),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?i[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[o++]=55296+(n>>10),i[o++]=56320+(1023&n)):i[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))},r.write=function(e,t,r){for(var n,s,i=r,o=0;o>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-i}},7833:(e,t,r)=>{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;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,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&&"undefined"!=typeof process&&"env"in process&&(e=process.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=(()=>{let e=!1;return()=>{e||(e=!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(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,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:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(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(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{},this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}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._headthis._capacity&&this.pop(),this._head1e4&&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._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var s,i=this._list[t];if(e0;s--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}},t.prototype.remove=function(e,t){var r,n=e,s=t;if(n===(0|n)&&this._head!==this._tail){var i=this.size(),o=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=i)return r=this.toArray(),this.clear(),r;var a;for(n+t>i&&(t=i-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;s>0;)this._list[n=n-1+o&this._capacityMask]=void 0,s--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+o&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>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){var s,i,o,a=arguments.length,c=this._list.length,l=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(s=r;s>0;s--)this.unshift(i[s-1])}else{var u=(i=new Array(n-(r+t))).length;for(s=0;sthis._tail){for(i=this._head;i>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){var t=1<{"use strict";function t(e,t){for(const 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 new 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(r){n.message=e.message,n.stack=e.stack;const s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(e)),t(new s,n)}}},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},9939:(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;const t={value:e,done:!1};if(this.pullQueue.length){const 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){this.isStopped=!0,this.remove();for(const e of 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(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const 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}={}){const s=new r;s.highWaterMark=t,s.lowWaterMark=n,s.removeCallback=e({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on:(e,t)=>{s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=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,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},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 s=0,i=n.length,o=new Array(i);s{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 s(s,i){r[s]=i,++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])?(s(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=r.g);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,i=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},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new 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){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,s,i,o,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],o=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,i=0,o=0;i191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):l(i,n);for(var a=0;a191)&&l(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(i,n),r>1114111&&l(i,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,s,i,o,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,y=f>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var m=f-y;return 2===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e[l],a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,i,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],s=c[3],i=c[4],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i]):1===l?h+=o[t>>>3]+o[t<<2&31]+"======":2===l?(r=c[1],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,i&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4866:e=>{e.exports=function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6368:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},1176:(e,t,r)=>{var n;!function(){"use strict";var s="input is invalid type",i="object"==typeof window,o=i?window:{};o.JS_SHA3_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[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],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(s);return[e,!1]},S=function(e){return 0===E(e)[0].length},_=function(e){for(var t=[],r=0;r>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 F(e,t,r){K.call(this,e,t,r)}K.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(i[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[l]<=o){for(this.start=r-o,this.block=i[c],r=0;r>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},K.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},K.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t==0&&(r=_(r),V(r),i=0)}return s&&(e=r[i],a+=h[e>>4&15]+h[15&e],s>1&&(a+=h[e>>12&15]+h[e>>8&15]),s>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},K.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=_(n),V(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},F.prototype=new K,F.prototype.finalize=function(){return this.encode(this.outputBits,!0),K.prototype.finalize.call(this)};var V=function(e){var t,r,n,s,i,o,a,c,l,u,h,d,p,g,y,m,b,w,v,E,S,_,A,I,k,R,T,C,P,B,D,N,x,L,O,M,U,K,F,V,q,H,j,$,z,G,W,Y,X,J,Q,Z,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=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],c=e[4]^e[14]^e[24]^e[34]^e[44],l=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],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(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=s^(c<<1|l>>>31),r=i^(l<<1|c>>>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=c^(d<<1|p>>>31),r=l^(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^(s<<1|i>>>31),r=h^(i<<1|s>>>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,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,H=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,L=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,B=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,x=e[44]<<29|e[45]>>>3,I=e[6]<<28|e[7]>>>4,k=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,K=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,$=e[8]<<27|e[9]>>>5,z=e[9]<<27|e[8]>>>5,R=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,V=e[38]<<8|e[39]>>>24,q=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,A=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~b&v,e[10]=I^~R&C,e[11]=k^~T&P,e[20]=L^~M&K,e[21]=O^~U&F,e[30]=$^~G&Y,e[31]=z^~W&X,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~C&B,e[13]=T^~P&D,e[22]=M^~K&V,e[23]=U^~F&q,e[32]=G^~Y&J,e[33]=W^~X&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&_,e[5]=v^~S&A,e[14]=C^~B&N,e[15]=P^~D&x,e[24]=K^~V&H,e[25]=F^~q&j,e[34]=Y^~J&Z,e[35]=X^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~_&g,e[7]=S^~A&y,e[16]=B^~N&I,e[17]=D^~x&k,e[26]=V^~H&L,e[27]=q^~j&O,e[36]=J^~Z&$,e[37]=Q^~ee&z,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=A^~y&b,e[18]=N^~I&R,e[19]=x^~k&T,e[28]=H^~L&M,e[29]=j^~O&U,e[38]=Z^~$&G,e[39]=ee^~z&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=B;else{for(N=0;NObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)s.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)i.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):e}const 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),i=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!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,l(t),r):u(t)}e.exports=function(...e){const t=p(u(c),this!==a&&this||{},c);let r={_:{}};for(const s of e)if(void 0!==s){if(!n(s))throw new TypeError("`"+s+"` is not an Option Object");r=p(r,{_:s},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,i=7*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\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(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=s?o(c,l,s,"day"):l>=n?o(c,l,n,"hour"):l>=r?o(c,l,r,"minute"):l>=t?o(c,l,t,"second"):c+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8437:(e,t,r)=>{e.exports=r(4327)},4327:function(e,t){!function(r,n){"use strict";var s={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function i(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t255)return!1;return!0}function o(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<>>32-t}function c(e){return e=o(e^=e>>>16,2246822507),(e=o(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<>>32-t,e[1]<>>32-t]:(t-=32,[e[1]<>>32-t,e[0]<>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<>>32-t,e[1]<>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}s.x86.hash32=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%4,l=e.length-r,u=t,h=0,d=3432918353,p=461845907,f=0;f>>0},s.x86.hash128=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%16,l=e.length-r,u=t,h=t,d=t,p=t,f=0,g=0,y=0,m=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},s.x64.hash128=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%16,o=e.length-r,a=[0,t],c=[0,t],g=[0,0],y=[0,0],m=[2277735313,289559509],b=[1291169091,658871167],w=0;w>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)+("00000000"+(c[0]>>>0).toString(16)).slice(-8)+("00000000"+(c[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=s),t.murmurHash3=s}()},5507:function(e,t){(function(){var e,r,n,s,i,o,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,s,i,o,a;for(t=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw new 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 new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new 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 new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},s=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),i=n("A"),r=function(e){var t,r,a,c,l;for(c=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")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-i)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new 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)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(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(c(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(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},9504:(e,t,r)=>{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!1,mode:n});return s.start(t),s},n.aes.createEncryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!0,mode:n});return s.start(t),s},n.aes.createDecryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.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){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var s=0;s>>=2,s=0;s>8^255&h^99,i[g]=h,o[h]=g,p=(d=e[h])<<24^h<<16^h<<8^h^d,f=((r=e[g])^(n=e[r])^(s=e[n]))<<24^(g^s)<<16^(g^n^s)<<8^g^r^s;for(var m=0;m<4;++m)c[m][g]=p,l[m][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=y=1:(g=r^e[e[e[r^s]]],y^=e[e[y]])}}function p(e,t){for(var r,n=e.slice(0),s=1,o=n.length,c=h*(o+6+1),u=o;u>>16&255]<<24^i[r>>>8&255]<<16^i[255&r]<<8^i[r>>>24]^a[s]<<24,s++):o>6&&u%o==4&&(r=i[r>>>24]<<24^i[r>>>16&255]<<16^i[r>>>8&255]<<8^i[255&r]),n[u]=n[u-o]^r;if(t){for(var d,p=l[0],f=l[1],g=l[2],y=l[3],m=n.slice(0),b=(u=0,(c=n.length)-h);u>>24]]^f[i[d>>>16&255]]^g[i[d>>>8&255]]^y[i[255&d]];n=m}return n}function f(e,t,r,n){var s,a,u,h,d,p,f,g,y,m,b,w,v=e.length/4-1;n?(s=l[0],a=l[1],u=l[2],h=l[3],d=o):(s=c[0],a=c[1],u=c[2],h=c[3],d=i),p=t[0]^e[0],f=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S>>24]^a[f>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],b=s[f>>>24]^a[g>>>16&255]^u[y>>>8&255]^h[255&p]^e[++E],w=s[g>>>24]^a[y>>>16&255]^u[p>>>8&255]^h[255&f]^e[++E],y=s[y>>>24]^a[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++E],p=m,f=b,g=w;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[n?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&p]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++E],r[n?1:3]=d[y>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++E]}function g(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},2746:(e,t,r)=>{var n=r(276);r(7619),r(6418);var s=e.exports=n.asn1=n.asn1||{};function i(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}function o(e,t,r,n){var a;i(e,t,2);var c=e.getByte();t--;var l=192&c,u=31&c;a=e.length();var h,d,p=function(e,t){var r=e.getByte();if(t--,128!==r){var n;if(128&r){var s=127&r;i(e,t,s),n=e.getInt(s<<3)}else n=r;if(n<0)throw new Error("Negative length: "+n);return n}}(e,t);if(t-=a-e.length(),void 0!==p&&p>t){if(n.strict){var f=new Error("Too few bytes to read ASN.1 value.");throw f.available=e.length(),f.remaining=t,f.requested=p,f}p=t}var g=!(32&~c);if(g)if(h=[],void 0===p)for(;;){if(i(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;p>0;)a=e.length(),h.push(o(e,p,r+1,n)),t-=a-e.length(),p-=a-e.length();if(void 0===h&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&(d=e.bytes(p)),void 0===h&&n.decodeBitStrings&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&p>1){var y=e.read,m=t,b=0;if(u===s.Type.BITSTRING&&(i(e,t,1),b=e.getByte(),t--),0===b)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),v=a-e.length();t-=v,u==s.Type.BITSTRING&&v++;var E=w.tagClass;v!==p||E!==s.Class.UNIVERSAL&&E!==s.Class.CONTEXT_SPECIFIC||(h=[w])}catch(e){}void 0===h&&(e.read=y,t=m)}if(void 0===h){if(void 0===p){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");p=t}if(u===s.Type.BMPSTRING)for(h="";p>0;p-=2)i(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(p),t-=p}var S=void 0===d?null:{bitStringContents:d};return s.create(l,u,g,h,S)}s.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},s.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},s.create=function(e,t,r,i,o){if(n.util.isArray(i)){for(var a=[],c=0;c1)||(0!==e.value.charCodeAt(0)||128&e.value.charCodeAt(1))&&(255!==e.value.charCodeAt(0)||128&~e.value.charCodeAt(1))?i.putBytes(e.value):i.putBytes(e.value.substr(1));if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);for(t.putByte(128|l.length),a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(i),t},s.oidToDer=function(e){var t,r,s,i,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c>>=7,t||(i|=128),r.push(i),t=!1}while(s>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},s.derToOid=function(e){var t;"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var s=0;e.length()>0;)s<<=7,128&(r=e.getByte())?s+=127&r:(t+="."+(s+r),s=0);return t},s.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,s=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},s.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,s=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);return"+"!==d&&"-"!==d||(l=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),l*=6e4,"+"===d&&(l*=-1),u=!0),"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,s),t.setHours(i,o,a,c)),t},s.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=-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=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},s.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},s.validate=function(e,t,r,i){var o=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)i&&(e.tagClass!==t.tagClass&&i.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&i.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c0&&(i+="\n");for(var o="",c=0;c1?i+="0x"+n.util.bytesToHex(e.value.slice(1)):i+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?i+=" (1 unused bit shown)":d>1&&(i+=" ("+d+" unused bits shown)")}}else if(e.type===s.Type.OCTETSTRING)a.test(e.value)||(i+="("+e.value+") "),i+="0x"+n.util.bytesToHex(e.value);else if(e.type===s.Type.UTF8)try{i+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;i+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===s.Type.PRINTABLESTRING||e.type===s.Type.IA5String?i+=e.value:a.test(e.value)?i+="0x"+n.util.bytesToHex(e.value):0===e.value.length?i+="[null]":i+=e.value}return i}},4058:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var s=0,i=t.length,o=t.charAt(0),a=[0];for(s=0;s0;)a.push(l%i),l=l/i|0}for(s=0;0===e[s]&&s=0;--s)n+=t[a[s]]}else n=function(e,t){var r=0,n=t.length,s=t.charAt(0),i=[0];for(r=0;r0;)i.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var s=0;s>=8;for(;u>0;)a.push(255&u),u>>=8}for(var h=0;e[h]===o&&h{var n=r(276);r(7619),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 new 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 new 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 s=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)};s.prototype.start=function(e){e=e||{};var t={};for(var r in 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)},s.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()},s.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)))}},6370:(e,t,r)=>{var n=r(276);r(7619),n.cipher=n.cipher||{};var s=e.exports=n.cipher.modes=n.cipher.modes||{};function i(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 s=0;s0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},s.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},s.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.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=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.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=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.ofb.prototype.decrypt=s.ofb.prototype.encrypt,s.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=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},s.ctr.prototype.decrypt=s.ctr.prototype.encrypt,s.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},s.gcm.prototype.start=function(e){if(!("iv"in e))throw new 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(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var s=r.length();if(12===s)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*s)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),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()])},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!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)},s.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))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 s=0;s0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},s.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,s=this._m[r][n];t[0]^=s[0],t[1]^=s[1],t[2]^=s[2],t[3]^=s[3]}return t},s.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)},s.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,s=16*r,i=new Array(s),o=0;o>>1,s=new Array(r);s[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(s[2*i],s[i]=[]),i>>=1;for(i=2;i{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var s=f({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},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 s=f({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},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 new 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],s=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[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],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,v=0;v>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27);var A=r[(E&=-15)>>>28]|n[E>>>24&15]|s[E>>>20&15]|i[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],I=l[(S&=-15)>>>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=65535&(I>>>16^A),m[w++]=A^t,m[w++]=I^t<<16}}return m}(t),this._init=!0}},s("DES-ECB",n.cipher.modes.ecb),s("DES-CBC",n.cipher.modes.cbc),s("DES-CFB",n.cipher.modes.cfb),s("DES-OFB",n.cipher.modes.ofb),s("DES-CTR",n.cipher.modes.ctr),s("3DES-ECB",n.cipher.modes.ecb),s("3DES-CBC",n.cipher.modes.cbc),s("3DES-CFB",n.cipher.modes.cfb),s("3DES-OFB",n.cipher.modes.ofb),s("3DES-CTR",n.cipher.modes.ctr);var i=[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],c=[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],l=[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 s,p,f=32===e.length?3:9;s=3===f?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(p=252645135&(g>>>4^y))<<4,g^=(p=65535&(g>>>16^(y^=p)))<<16,g^=p=858993459&((y^=p)>>>2^g),g^=p=16711935&((y^=p<<2)>>>8^g),g=(g^=(p=1431655765&(g>>>1^(y^=p<<8)))<<1)<<1|g>>>31,y=(y^=p)<<1|y>>>31;for(var m=0;m>>4|y<<28)^e[v+1];p=g,g=y,y=p^(o[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|d[63&E]|i[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|h[63&S])}p=g,g=y,y=p}y=y>>>1|y<<31,y^=p=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(p=16711935&(y>>>8^(g^=p<<1)))<<8,y^=(p=858993459&(y>>>2^(g^=p)))<<2,y^=p=65535&((g^=p)>>>16^y),y^=p=252645135&((g^=p<<16)>>>4^y),g^=p<<4,r[0]=g,r[1]=y}function f(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},276:e=>{e.exports={options:{usePureJavaScript:!1}}},1696:(e,t,r)=>{var n=r(276);r(8106),r(7619),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,s=null,i={start:function(i,o){if(null!==i)if("string"==typeof i){if(!((i=i.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+i+'"');t=n.md.algorithms[i].create()}else t=i;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 c=0;ct.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),s=n.util.createBuffer(),l=o.length(),c=0;c{var n,s=r(276);function i(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 o(){return new i(null)}function a(e,t,r,n,s,i){for(var o=16383&t,a=t>>14;--i>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*o;s=((c=o*c+((16383&u)<<14)+r.data[n]+s)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return s}e.exports=s.jsbn=s.jsbn||{},s.jsbn.BigInteger=i,"undefined"==typeof navigator?(i.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(var o=32767&t,a=t>>15;--i>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*o;s=((c=o*c+((32767&u)<<15)+r.data[n]+(1073741823&s))>>>30)+(u>>>15)+a*l+(s>>>30),r.data[n++]=1073741823&c}return s},n=30):"Netscape"!=navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(;--i>=0;){var o=t*this.data[e++]+r.data[n]+s;s=Math.floor(o/67108864),r.data[n++]=67108863&o}return s},n=26):(i.prototype.am=a,n=28),i.prototype.DB=n,i.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function A(e){return e}function I(e){this.r2=o(),this.q3=o(),i.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(i.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},i.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},i.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},i.prototype.fromString=function(e,t){var r;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)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==r?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-o):this.data[this.t-1]|=a<=this.DB&&(o-=this.DB))}8==r&&128&e[0]&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},i.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},i.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>s|a,a=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},i.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,s=this.DB-n,i=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=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()},i.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),s=r.t;for(t.t=s+n.t;--s>=0;)t.data[s]=0;for(s=0;s=0;)e.data[r]=0;for(r=0;r=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()},i.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var s=this.abs();if(s.t0?(n.lShiftTo(u,a),s.lShiftTo(u,r)):(n.copyTo(a),s.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var p=d*(1<1?a.data[h-2]>>this.F2:0),g=this.FV/p,y=(1<=0&&(r.data[r.t++]=1,r.subTo(v,r)),i.ONE.dlShiftTo(h,v),v.subTo(a,a);a.t=0;){var E=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+m)*y);if((r.data[b]+=a.am(0,E,r,w,0,h))0&&r.rShiftTo(u,r),c<0&&i.ZERO.subTo(r,r)}}},i.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(!(1&e))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},i.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},i.prototype.exp=function(e,t){if(e>4294967295||e<1)return i.ONE;var r=o(),n=o(),s=t.convert(this),a=f(e)-1;for(s.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,s,r);else{var c=r;r=n,n=c}return t.revert(r)},i.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;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 r,n=(1<0)for(a>a)>0&&(s=!0,i=h(r));o>=0;)a>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(s=!0),s&&(i+=h(r));return s?i:"0"},i.prototype.negate=function(){var e=o();return i.ZERO.subTo(this,e),e},i.prototype.abs=function(){return this.s<0?this.negate():this},i.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},i.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+f(this.data[this.t-1]^this.s&this.DM)},i.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t},i.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},i.ZERO=p(0),i.ONE=p(1),_.prototype.convert=A,_.prototype.revert=A,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},I.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},I.prototype.revert=function(e){return e},I.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);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},I.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},I.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var k=[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],R=(1<<26)/k[k.length-1];i.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},i.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),s=o(),i=o(),a="";for(this.divRemTo(n,s,i);s.signum()>0;)a=(r+i.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,i);return i.intValue().toString(e)+a},i.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),s=!1,o=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),s&&i.ZERO.subTo(this,this)},i.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(i.ONE.shiftLeft(e-1),b,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),t.nextBytes(n),s>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=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()},i.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},i.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]}},i.prototype.multiplyLowerTo=function(e,t,r){var n,s=Math.min(this.t+e.t,t);for(r.s=0,r.t=s;s>0;)r.data[--s]=0;for(n=r.t-this.t;s=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)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},i.prototype.millerRabin=function(e){var t=this.subtract(i.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,s=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(s,this);if(0!=c.compareTo(i.ONE)&&0!=c.compareTo(t)){for(var l=1;l++>24},i.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},i.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},i.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,s=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[s++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(t[s++]=r);return t},i.prototype.equals=function(e){return 0==this.compareTo(e)},i.prototype.min=function(e){return this.compareTo(e)<0?this:e},i.prototype.max=function(e){return this.compareTo(e)>0?this:e},i.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},i.prototype.or=function(e){var t=o();return this.bitwiseTo(e,b,t),t},i.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,w,t),t},i.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,v,t),t},i.prototype.not=function(){for(var e=o(),t=0;t=this.t?0!=this.s:!!(this.data[t]&1<1){var h=o();for(n.sqrTo(a[1],h);c<=u;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,m,b=e.t-1,w=!0,v=o();for(s=f(e.data[b])-1;b>=0;){for(s>=l?d=e.data[b]>>s-l&u:(d=(e.data[b]&(1<0&&(d|=e.data[b-1]>>this.DB+s-l)),c=r;!(1&d);)d>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),w)a[d].copyTo(i),w=!1;else{for(;c>1;)n.sqrTo(i,v),n.sqrTo(v,i),c-=2;c>0?n.sqrTo(i,v):(m=i,i=v,v=m),n.mulTo(v,a[d],i)}for(;b>=0&&!(e.data[b]&1<=0?(r.subTo(n,r),t&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(i.ONE)?i.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},i.prototype.pow=function(e){return this.exp(e,new _)},i.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var s=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(s0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(s=t.getLowestSetBit())>0&&t.rShiftTo(s,t),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r},i.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=k[k.length-1]){for(t=0;t{var n=r(276);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},6418:(e,t,r)=>{var n=r(276);n.pki=n.pki||{};var s=e.exports=n.pki.oids=n.oids=n.oids||{};function i(e,t){s[e]=t,s[t]=e}function o(e,t){s[e]=t}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")},2698:(e,t,r)=>{var n=r(276);if(r(9504),r(2746),r(9095),r(8106),r(6418),r(3254),r(2385),r(9356),r(5124),r(5805),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:i.Class.UNIVERSAL,type:i.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[i.derToOid(e)])){var r=new 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=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new 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 s,c,l,u=n.random.getBytesSync(r.saltSize),h=r.count,d=i.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var f,g,y;switch(r.algorithm){case"aes128":s=16,f=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":s=24,f=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":s=32,f=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":s=8,f=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),b=p(m),w=n.pkcs5.pbkdf2(t,u,h,s,b),v=n.random.getBytesSync(f);(_=y(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,s){var a=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,e),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,t.getBytes())]);return"hmacWithSHA1"!==s&&a.value.push(i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(o.oids[s]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.NULL,!1,"")])),a}(u,d,s,m);c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBES2).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(g).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,v)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;s=24;var _,A=new n.util.ByteBuffer(u);w=o.pbe.generatePkcs12Key(t,A,1,h,s),v=o.pbe.generatePkcs12Key(t,A,2,h,s),(_=n.des.createEncryptionCipher(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes(),c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,u),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,d.getBytes())])])}return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[c,i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,l)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,s={},a=[];if(!i.validate(e,c,s,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=i.derToOid(s.encryptionOid),h=o.pbe.getCipher(u,s.encryptionParams,t),d=n.util.createBuffer(s.encryptedData);return h.update(d),h.finish()&&(r=i.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:i.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=new 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 new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return i.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var s=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return s=o.encryptPrivateKeyInfo(s,t,r),o.encryptedPrivateKeyToPem(s)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));d.start(c),d.update(i.toDer(o.privateKeyToAsn1(e))),d.finish();var p={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(p)},o.decryptRsaPrivateKey=function(e,t){var r=null,s=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==s.type&&"PRIVATE KEY"!==s.type&&"RSA PRIVATE KEY"!==s.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(s.procType&&"ENCRYPTED"===s.procType.type){var a,c;switch(s.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+s.dekInfo.algorithm+'".')).algorithm=s.dekInfo.algorithm,l}var u=n.util.hexToBytes(s.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(h.start(u),h.update(n.util.createBuffer(s.body)),!h.finish())return r;r=h.output.getBytes()}else r=s.body;return null!==(r="ENCRYPTED PRIVATE KEY"===s.type?o.decryptPrivateKeyInfo(i.fromDer(r),t):i.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,s,i,o){var a,c;if(null==o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var l=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!=e){for(c=0;c=0;c--)C>>=8,C+=I.at(c)+T.at(c),T.setAt(c,255&C);R.putBuffer(T)}v=R,h.putBuffer(_)}return h.truncate(h.length()-i),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=new 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 s,a={},c=[];if(!i.validate(t,l,a,c))throw(s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,s;if((e=i.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,s.supportedOids=["pkcs5PBKDF2"],s;if((e=i.derToOid(a.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)throw(s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s;var u,h,p=a.kdfSalt,f=n.util.createBuffer(a.kdfIterationCount);switch(f=f.getInt(f.length()<<3),o.oids[e]){case"aes128-CBC":u=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,h=n.des.createDecryptionCipher;break;case"desCBC":u=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),y=n.pkcs5.pbkdf2(r,p,f,u,g),m=a.encIv,b=h(y);return b.start(m),b},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var s={},a=[];if(!i.validate(t,u,s,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,h,p=n.util.createBuffer(s.salt),f=n.util.createBuffer(s.iterations);switch(f=f.getInt(f.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=d(s.prfOid),m=o.pbe.generatePkcs12Key(r,p,1,f,c,y);return y.start(),h(m,o.pbe.generatePkcs12Key(r,p,2,f,l,y))},o.pbe.opensslDeriveBytes=function(e,t,r,s){if(null==s){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');s=n.md.md5.create()}null===t&&(t="");for(var i=[h(s,e+t)],o=16,a=1;o{var n=r(276);r(1696),r(8106),r(7619);var s,i=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(s=r(310)),e.exports=n.pbkdf2=i.pbkdf2=function(e,t,r,i,o,a){if("function"==typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&s.pbkdf2&&(null===o||"object"!=typeof o)&&(s.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!=typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===s.pbkdf2Sync.length?s.pbkdf2(e,t,r,i,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):s.pbkdf2(e,t,r,i,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===s.pbkdf2Sync.length?s.pbkdf2Sync(e,t,r,i).toString("binary"):s.pbkdf2Sync(e,t,r,i,o).toString("binary");if(null==o&&(o="sha1"),"string"==typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(i>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(i/c),h=i-(u-1)*c,d=n.hmac.create();d.start(o,e);var p,f,g,y="";if(!a){for(var m=1;m<=u;++m){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes();for(var b=2;b<=r;++b)d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f;y+=mu)return a(null,y);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes(),b=2,v()}function v(){if(b<=r)return d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f,++b,n.util.setImmediate(v);y+=m{var n=r(276);r(7619);var s=e.exports=n.pem=n.pem||{};function i(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},s=0;s65&&-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),i=s-o-1,o=-1,++s}else" "!==t[s]&&"\t"!==t[s]&&","!==t[s]||(o=s);return t}function o(e){return e.replace(/^\s+/,"")}s.encode=function(e,t){t=t||{};var r,s="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(s+=i(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(s+=i(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),s+=i(r)),e.headers)for(var o=0;o{var n=r(276);r(7619),r(9356),r(1598);var s=e.exports=n.pkcs1=n.pkcs1||{};function i(e,t,r){r||(r=n.md.sha1.create());for(var s="",i=Math.ceil(t/r.digestLength),o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),s+=r.digest().getBytes()}return s.substring(0,t)}s.encode_rsa_oaep=function(e,t,r){var s,o,a,c;"string"==typeof r?(s=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(s=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;s||(s=""),a.update(s,"raw");for(var h=a.digest(),d="",p=u-t.length,f=0;f{var n=r(276);r(7619),r(3736),r(9356),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,s=[6,4,2,4,2,4,6,2],i=new r(null);i.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,s){"function"==typeof t&&(s=t,t={});var i=(t=t||{}).algorithm||"PRIMEINC";"string"==typeof i&&(i={name:i}),i.options=i.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;re&&(o=l(e,t));var p=o.toString(16);s.target.postMessage({hex:p,workLoad:u}),o.dAddOffset(h,0)}}}p()}(e,t,s,i):a(e,t,s,i)}(e,c,i.options,s);throw new Error("Invalid prime generation algorithm: "+i.name)}}function a(e,t,r,n){var s=l(e,t),i=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(s.bitLength());"millerRabinTests"in r&&(i=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(s,e,t,0,i,o,n)}function c(e,t,r,i,o,a,u){var h=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(s[i++%8],0)}while(a<0||+new Date-h{var n=r(276);r(7619);var s=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(s=r(310)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,i=new Array(32),o=0;o<32;++o)i[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){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 s=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(s),t.generated=0}function l(e){var t=null,r=n.util.globalScope,s=r.crypto||r.msCrypto;s&&s.getRandomValues&&(t=function(e){return s.getRandomValues(e)});var i=n.util.createBuffer();if(t)for(;i.length()>16)))<<16,d=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31)),c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),i.putByte(255&h);return i.getBytes(e)}return t.pools=i,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var s=t.plugin.cipher,i=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(l.length()>=e)return r(null,l.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var d=s(t.key,t.seed);t.generated+=d.length,l.putBytes(d),t.key=o(s(t.key,i(t.seed))),t.seed=a(s(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,s=t.plugin.increment,i=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=i(r(t.key,s(t.seed))),t.seed=o(r(t.key,t.seed))}return c.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>s&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}},9356:(e,t,r)=>{var n=r(276);r(9504),r(172),r(3878),r(7619),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},s=new Array(4),i=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=new Array(4))[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=new Array(4))[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,s,!1),i.putInt32(s[0]),i.putInt32(s[1]),i.putInt32(s[2]),i.putInt32(s[3]),i.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){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)},5124:(e,t,r)=>{var n=r(276);r(7619);var s=[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],i=[1,2,3,5],o=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};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,i=e,o=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=o;r<128;r++)i.putByte(s[i.at(r-1)+i.at(r-o)&255]);for(i.setAt(128-c,s[i.at(128-c)&l]),r=127-c;r>=0;r--)i.setAt(r,s[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var s,c,l,u,h=!1,d=null,p=null,f=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(s=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=o(e[l],i[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(s=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],i[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=d.getInt16Le();null!==f&&(r?n^=f.getInt16Le():f.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var s=0;s=8;)y([[5,s],[1,c],[6,s],[1,c],[5,s]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,m.update()),!r&&(t=0===d.length()))if(e)t=e(8,p,!r);else{var s=p.length(),i=p.at(s-1);i>s?t=!1:p.truncate(i)}return t}}};n.rc2.startEncrypting=function(e,t,r){var s=n.rc2.createEncryptionCipher(e,128);return s.start(t,r),s},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var s=n.rc2.createDecryptionCipher(e,128);return s.start(t,r),s},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5805:(e,t,r)=>{var n=r(276);if(r(2746),r(3736),r(6418),r(7501),r(268),r(9356),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.util.isNodejs?r(310):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[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){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);i.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),i.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 s.value.push(i),s.value.push(a),o.toDer(s).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var i;t.dP||(t.dP=t.d.mod(t.p.subtract(s.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(s.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{i=new s(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(i.compareTo(t.n)>=0||!i.gcd(t.n).equals(s.ONE));for(var o=(e=e.multiply(i.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);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c.multiply(i.modInverse(t.n)).mod(t.n)};function m(e,t,r){var s=n.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}s.putByte(0),s.putByte(r);var a,c=i-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l0;){var u=0,h=n.random.getBytes(c);for(l=0;l1;){if(255!==o.getByte()){--o.read;break}++l}else if(2===c)for(l=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++l}if(0!==o.getByte()||l!==i-3-o.length())throw new 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))&&(255!==r.charCodeAt(0)||128&~r.charCodeAt(1))?r:r.substr(1)}function v(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function E(e){return n.util.isNodejs&&"function"==typeof i[e]}function S(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 _(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),s=0;s0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,i){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new s(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),!1!==i?b(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var i,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(i.eInt),i},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new s(null);r.fromInt(30);for(var n,i=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||uh?e.pqState=0:e.num.isProbablePrime(v(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[i++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(s.ONE).gcd(e.e).compareTo(s.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)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(s.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 p=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,l){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(l=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(l=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,l=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(l=r,r=void 0):(l=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(l){if(E("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return l(e);l(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(S("generateKey")&&S("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){l(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));l(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(_("generateKey")&&_("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"]);return 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=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));l(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){l(e)}},void(u.onerror=function(e){l(e)})}}else if(E("generateKeyPairSync")){var h=i.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(h.privateKey),publicKey:c.publicKeyFromPem(h.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!l)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;!function(e,t,r){"function"==typeof t&&(r=t,t={});var i={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?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,i,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var i=e.p;e.p=e.q,e.q=i}if(0!==e.p.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.p=null,void o();if(0!==e.q.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(s.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.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:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(i.prng=t.prng),o()}(d,r,l)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,s){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,s)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return c.rsa.encrypt(i,r,!0)},verify:function(e,t,s,i){"string"==typeof s?s=s.toUpperCase():void 0===s&&(s="RSASSA-PKCS1-V1_5"),void 0===i&&(i={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in i||(i._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===s?s={verify:function(e,t){t=b(t,r,!0);var s=o.fromDer(t,{parseAllBytes:i._parseAllDigestBytes}),a={},c=[];if(!o.validate(s,f,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,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"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new 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"!==s&&"NULL"!==s&&null!==s||(s={verify:function(e,t){return e===b(t,r,!0)}});var a=c.rsa.decrypt(t,r,!0,!1);return s.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,s,i,o,a,l){var u={n:e,e:t,d:r,p:s,q:i,dP:o,dQ:a,qInv:l,decrypt:function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var s=c.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))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(s,u,!1)},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 c.rsa.encrypt(n,u,r)}};return u},c.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(c.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())])},c.privateKeyFromAsn1=function(e){var t,r,i,a,l,d,p,f,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),i=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=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(),c.setRsaPrivateKey(new s(t,16),new s(r,16),new s(i,16),new s(a,16),new s(l,16),new s(d,16),new s(p,16),new s(f,16))},c.privateKeyToAsn1=c.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))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,p,t,r)){var i,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(i=new Error("Cannot read public key. Unknown OID.")).oid=a,i;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,i;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new s(l,16),new s(u,16))},c.publicKeyToAsn1=c.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(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.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))])}},1598:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),s={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i>>0,c>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=c[1],c[1]=c[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(i),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=c>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);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},s};var i=null,o=!1;function a(e,t,r){for(var n,s,i,o,a,c,l,u=r.length();u>=64;){for(s=e.h0,i=e.h1,o=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i&o|a&(i^o))+c+2400959708+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+3395469782+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;e.h0=e.h0+s|0,e.h1=e.h1+i|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},172:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),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=new Array(64),s={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i>>0,a>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=a[1],a[1]=a[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(i),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=a>>>0;o.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};c(d,r,o);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},s};var i=null,o=!1,a=null;function c(e,t,r){for(var n,s,i,o,c,l,u,h,d,p,f,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,s=((s=t[c-15])>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,t[c]=n+t[c-7]+s+t[c-16]|0;for(l=e.h0,u=e.h1,h=e.h2,d=e.h3,p=e.h4,f=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)i=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),o=l&u|h&(l^u),n=y+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(g^p&(f^g))+a[c]+t[c],y=g,g=f,f=p,p=d+n>>>0,d=h,h=u,u=l,l=n+(s=i+o)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+p|0,e.h5=e.h5+f|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},2313:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=s;var i=n.sha384=n.sha512.sha384=n.sha512.sha384||{};i.create=function(){return s.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=i,n.sha512.sha256=n.sha512.sha256||{create:function(){return s.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 s.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,s.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[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]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["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 l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,s=n.util.createBuffer(),i=new Array(80),h=0;h<80;++h)i[h]=new Array(2);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,start:function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,i=0;i>>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 s.putBytes(e),u(r,i,s),(s.read>2048||0===s.length())&&s.compact(),p},p.digest=function(){var t=n.util.createBuffer();t.putBytes(s.bytes());var a,c=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;t.putBytes(o.substr(0,p.blockLength-c));for(var l=8*p.fullMessageLength[0],h=0;h>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var d=new Array(r.length);for(h=0;h=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((B=(N=t[P-2])[0])>>>19|(D=N[1])<<13)^(D>>>29|B<<3)^B>>>6)>>>0,s=((B<<13|D>>>19)^(D<<3|B>>>29)^(B<<26|D>>>6))>>>0,i=(((B=(L=t[P-15])[0])>>>1|(D=L[1])<<31)^(B>>>8|D<<24)^B>>>7)>>>0,o=((B<<31|D>>>1)^(B<<24|D>>>8)^(B<<25|D>>>7))>>>0,x=t[P-7],O=t[P-16],D=s+x[1]+o+O[1],t[P][0]=n+x[0]+i+O[0]+(D/4294967296>>>0)>>>0,t[P][1]=D>>>0;for(f=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],b=e[2][0],w=e[2][1],v=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],A=e[5][0],I=e[5][1],k=e[6][0],R=e[6][1],T=e[7][0],C=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,h=(k^S&(A^k))>>>0,a=((f>>>28|g<<4)^(g>>>2|f<<30)^(g>>>7|f<<25))>>>0,l=((f<<4|g>>>28)^(g<<30|f>>>2)^(g<<25|f>>>7))>>>0,d=(f&y|b&(f^y))>>>0,p=(g&m|w&(g^m))>>>0,D=C+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((R^_&(I^R))>>>0)+c[P][1]+t[P][1],n=T+u+h+c[P][0]+t[P][0]+(D/4294967296>>>0)>>>0,s=D>>>0,i=a+d+((D=l+p)/4294967296>>>0)>>>0,o=D>>>0,T=k,C=R,k=A,R=I,A=S,I=_,S=v+n+((D=E+s)/4294967296>>>0)>>>0,_=D>>>0,v=b,E=w,b=y,w=m,y=f,m=g,f=n+i+((D=s+o)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+f+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+m,e[1][0]=e[1][0]+y+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+w,e[2][0]=e[2][0]+b+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+E,e[3][0]=e[3][0]+v+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+_,e[4][0]=e[4][0]+S+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+I,e[5][0]=e[5][0]+A+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+R,e[6][0]=e[6][0]+k+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+C,e[7][0]=e[7][0]+T+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},7619:(e,t,r)=>{var n=r(276),s=r(4058),i=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)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;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&s.setAttribute("a",n=!n))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?r.g:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=a,i.ByteStringBuffer=a,i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.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},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.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))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.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))},i.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.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},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.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},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.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},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=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},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.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},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.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},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.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},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var n="",s="",i="",o=0,a=0;r>0;--r,++o)s=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=i,i="",a=0),i+=String.fromCharCode(s),++a;return n+i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[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],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,n,s,i="",o="",a=0;a>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,s,i="",o=0;o>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==s&&(i+=String.fromCharCode((3&n)<<6|s)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:s.encode,decode:s.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,i=0;i>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.binary.base64.decode=function(e,t,r){var n,s,i,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c>4,64!==i&&(a[u++]=(15&s)<<4|i>>2,64!==o&&(a[u++]=(3&i)<<6|o));return t?u-r:a.subarray(0,u)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,u,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,u,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,o=0;o0&&i.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":s");break;case"%":i.push("%");break;default:i.push("<%"+a+"?>")}}return i.push(e.substring(o)),i.join("")},i.formatNumber=function(e,t,r,n){var s=e,i=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=s<0?"-":"",l=parseInt(s=Math.abs(+s||0).toFixed(i),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(i?o+Math.abs(s-l).toFixed(i).slice(2):"")},i.formatSize=function(e){return e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&s.sts.st&&a.st{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,s=r(5643),i=r(3262);function o(e,t,r,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof s?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":i=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=i.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=i.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===s.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==s.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==s.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=i.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(i.compareFieldsById),c=0;c>>0,8|s.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==s.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?o(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?o(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),s=r(361),i=r(3262);function o(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var s=r(8923),i=r(3262);function o(e,t,r,s,i,o){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=s,this.comments=i||{},this.valuesOptions=o,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var s,i=r(5643),o=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,i,l,u){if(a.isObject(s)?(u=i,l=s,s=i=void 0):a.isObject(i)&&(u=l,l=i,i=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==s&&!c.test(s=s.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==i&&!a.isString(i))throw TypeError("extend must be a string");"proto3_optional"===s&&(s="optional"),this.rule=s&&"optional"!==s?s:void 0,this.type=r,this.id=t,this.extend=i||void 0,this.required="required"===s,this.optional=!this.required,this.repeated="repeated"===s,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof s?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof i&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof i)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof s&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(s,i){a.decorateType(s.constructor).add(new l(i,e,t,r,{default:n}))}},l._configure=function(e){s=e}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4394:(e,t,r)=>{"use strict";var n=t;function s(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=s,s()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=o;var n=r(1344);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var s=r(361),i=r(3262);function o(e,t,r,s,o,a){if(n.call(this,e,t,s,void 0,void 0,o,a),!i.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===s.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},o.d=function(e,t,r){return"function"==typeof r?r=i.decorateType(r).name:r&&"object"==typeof r&&(r=i.decorateEnum(r).name),function(n,s){i.decorateType(n.constructor).add(new o(s,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Method";var s=r(3262);function i(e,t,r,i,o,a,c,l,u){if(s.isObject(o)?(c=o,o=a=void 0):s.isObject(a)&&(c=a,a=void 0),void 0!==t&&!s.isString(t))throw TypeError("type must be a string");if(!s.isString(r))throw TypeError("requestType must be a string");if(!s.isString(i))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}i.fromJSON=function(e,t){return new i(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},i.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var s,i,o,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var s=0;s{"use strict";e.exports=i,i.className="ReflectionObject";var n,s=r(3262);function i(e,t){if(!s.isString(e))throw TypeError("name must be a string");if(t&&!s.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(i.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),i.prototype.toJSON=function(){throw Error()},i.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},i.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},i.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},i.prototype.getOption=function(e){if(this.options)return this.options[e]},i.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},i.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var i=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(i){var o=i[e];s.setProperty(o,r,t)}else(i={})[e]=s.setProperty({},r,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},i.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var s=r(1344),i=r(3262);function o(e,t,r,s){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=s}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},o.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=A,A.filename=null,A.defaults={keepCase:!1};var n=r(527),s=r(5330),i=r(7882),o=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,_=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function A(e,t,r){t instanceof s||(r=t,t=new s),r||(r=A.defaults);var I,k,R,T,C,P=r.preferTrailingComment||!1,B=n(e,r.alternateCommentMode||!1),D=B.next,N=B.push,x=B.peek,L=B.skip,O=B.cmnt,M=!0,U=!1,K=t,F=r.keepCase?function(e){return e}:p.camelCase;function V(e,t,r){var n=A.filename;return r||(A.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+B.line+")")}function q(){var e,t=[];do{if('"'!==(e=D())&&"'"!==e)throw V(e);t.push(D()),L(e),e=x()}while('"'===e||"'"===e);return t.join("")}function H(e){var t=D();switch(t){case"'":case'"':return N(t),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;switch("-"===e.charAt(0)&&(r=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(b.test(e))return r*parseInt(e,8);if(v.test(e))return r*parseFloat(e);throw V(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw V(t,"value")}}function j(e,t){var r,n;do{!t||'"'!==(r=x())&&"'"!==r?e.push([n=$(D()),L("to",!0)?$(D()):n]):e.push(q())}while(L(",",!0));var s={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)}))}function $(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw V(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw V(e,"id")}function z(){if(void 0!==I)throw V("package");if(I=D(),!S.test(I))throw V(I,"name");K=K.define(I),L(";")}function G(){var e,t=x();switch(t){case"weak":e=R||(R=[]),D();break;case"public":D();default:e=k||(k=[])}t=q(),L(";"),e.push(t)}function W(){if(L("="),T=q(),!(U="proto3"===T)&&"proto2"!==T)throw V(T,"syntax");L(";")}function Y(e,t){switch(t){case"option":return ee(e,t),L(";"),!0;case"message":return J(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=D()))throw V(t,"service name");var r=new u(t);X(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw V(e);!function(e,t){var r=O(),n=t;if(!E.test(t=D()))throw V(t,"name");var s,i,o,a,c=t;if(L("("),L("stream",!0)&&(i=!0),!S.test(t=D()))throw V(t);if(s=t,L(")"),L("returns"),L("("),L("stream",!0)&&(a=!0),!S.test(t=D()))throw V(t);o=t,L(")");var l=new h(c,n,s,o,i,a);l.comment=r,X(l,(function(e){if("option"!==e)throw V(e);ee(l,e),L(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=D()))throw V(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":Q(e,t,r);break;case"optional":Q(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw V(t);N(t),Q(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=B.line;if(e&&("string"!=typeof e.comment&&(e.comment=O()),e.filename=A.filename),L("{",!0)){for(var s;"}"!==(s=D());)t(s);L(";",!0)}else r&&r(),L(";"),e&&("string"!=typeof e.comment||P)&&(e.comment=O(n)||e.comment)}function J(e,t){if(!E.test(t=D()))throw V(t,"type name");var r=new i(t);X(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){L("<");var t=D();if(void 0===d.mapKey[t])throw V(t,"type");L(",");var r=D();if(!S.test(r))throw V(r,"type");L(">");var n=D();if(!E.test(n))throw V(n,"name");L("=");var s=new a(F(n),$(D()),t,r);X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)})),e.add(s)}(r);break;case"required":case"repeated":Q(r,e);break;case"optional":Q(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new c(F(t));X(r,(function(e){"option"===e?(ee(r,e),L(";")):(N(e),Q(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":j(r.extensions||(r.extensions=[]));break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:if(!U||!S.test(e))throw V(e);N(e),Q(r,"optional")}})),e.add(r)}function Q(e,t,r){var n=D();if("group"!==n){for(;n.endsWith(".")||x().startsWith(".");)n+=D();if(!S.test(n))throw V(n,"type");var s=D();if(!E.test(s))throw V(s,"name");s=F(s),L("=");var a=new o(s,$(D()),n,t,r);if(X(a,(function(e){if("option"!==e)throw V(e);ee(a,e),L(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+s);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);U||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=D();if(!E.test(r))throw V(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),L("=");var s=$(D()),a=new i(r);a.group=!0;var c=new o(n,s,r,t);c.filename=A.filename,X(a,(function(e){switch(e){case"option":ee(a,e),L(";");break;case"required":case"repeated":Q(a,e);break;case"optional":Q(a,U?"proto3_optional":"optional");break;case"message":J(a,e);break;case"enum":Z(a,e);break;default:throw V(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),L(";");break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw V(t,"name");L("=");var r=$(D(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(n,(function(e){if("option"!==e)throw V(e);ee(n,e),L(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=L("(",!0);if(!S.test(t=D()))throw V(t,"name");var n,s=t,i=s;r&&(L(")"),i=s="("+s+")",t=x(),_.test(t)&&(n=t.slice(1),s+=t,D())),L("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,i,te(e,s),n)}function te(e,t){if(L("{",!0)){for(var r={};!L("}",!0);){if(!E.test(C=D()))throw V(C,"name");if(null===C)throw V(C,"end of input");var n,s=C;if(L(":",!0),"{"===x())n=te(e,t+"."+C);else if("["===x()){var i;if(n=[],L("[",!0)){do{i=H(!0),n.push(i)}while(L(",",!0));L("]"),void 0!==i&&re(e,t+"."+C,i)}}else n=H(!0),re(e,t+"."+C,n);var o=r[s];o&&(n=[].concat(o).concat(n)),r[s]=n,L(",",!0),L(";",!0)}return r}var a=H(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(L("[",!0)){do{ee(e,"option")}while(L(",",!0));L("]")}return e}for(;null!==(C=D());)switch(C){case"package":if(!M)throw V(C);z();break;case"import":if(!M)throw V(C);G();break;case"syntax":if(!M)throw V(C);W();break;case"option":ee(K,C),L(";");break;default:if(Y(K,C)){M=!1;continue}throw V(C)}return A.filename=null,{package:I,imports:k,weakImports:R,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),i=s.LongBits,o=s.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return s.Buffer?function(e){return(c.create=function(e){return s.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(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}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;if(t=0,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 a(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")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new i(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=s.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(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},c._configure=function(e){n=e,c.create=h(),n._configure();var t=s.Long?"toLong":"toNumber";s.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3158:(e,t,r)=>{"use strict";e.exports=i;var n=r(6237);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(e){n.call(this,e)}i._configure=function(){s.Buffer&&(i.prototype._slice=s.Buffer.prototype.slice)},i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},i._configure()},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var s,i,o,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var s=this;if(!n)return u.asPromise(e,s,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){i.filename=e;var n,o=i(t,s,r),h=0;if(o.imports)for(;h-1))if(s.files.push(e),e in o)a?h(e,o[e]):(++f,setTimeout((function(){--f,h(e,o[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,s.fetch(e,(function(r,i){--f,n&&(r?t?f||c(null,s):c(r):h(e,i))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-1&&this.deferred.splice(t,1)}}else if(e instanceof c)p.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(s.prototype=Object.create(n.EventEmitter.prototype)).constructor=s,s.prototype.rpcCall=function e(t,r,s,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,s,i);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){o(e)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},s.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var s=r(8811),i=r(3262),o=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),i=0;i{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,s=/^ *[*/]+ */,i=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(o),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var s=t.exec(e);if(!s)throw m("string");return l=t.lastIndex,_(y),y=null,u(s[1])}();var s,i,o,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(o=b(l));)if("\n"===o&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw m("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,s=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,s=!0}else{if("*"!==(o=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===o&&++d,++l===h)throw m("comment");i=o,o=b(l)}while("*"!==i||"/"!==o);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var A=l;if(t.lastIndex=0,!t.test(b(A++)))for(;A{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var s=r(5643),i=r(1457),o=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),y=r(744),m=r(6434);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,s=r(3262),i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,s,i=e.exports=r(3610),o=r(4529);i.codegen=r(8561),i.fetch=r(5212),i.path=r(9207),i.fs=i.inquire("fs"),i.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[s]=e(t[s]||{},r,n);else{var i=t[s];i&&(n=[].concat(i).concat(n)),t[s]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=s.zero=new s(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var o=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var 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 s(r,n)},s.from=function(e){if("number"==typeof e)return s.fromNumber(e);if(n.isString(e)){if(!n.Long)return s.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new s(e.low>>>0,e.high>>>0):i},s.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},s.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;s.fromHash=function(e){return e===o?i:new s((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},s.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},s.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},s.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},s.prototype.length=function(){var 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}},3610:function(e,t,r){"use strict";var n=t;function s(e,t,r){for(var n=Object.keys(t),s=0;s0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=s,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=i,n.ProtocolError=i("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=function(e){var t=s.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n{"use strict";var n=t,s=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var i=this.lookup(n);i&&(e=i.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var o=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),o["@type"]=n,o}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),i=s.LongBits,o=s.base64,a=s.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return s.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;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 y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,i.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=i.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=i.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var m=s.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(p,1,0);if(s.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return 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 c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},818:(e,t,r)=>{"use strict";e.exports=i;var n=r(3449);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(){n.call(this)}function o(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}i._configure=function(){i.alloc=s._Buffer_allocUnsafe,i.writeBytesBuffer=s.Buffer&&s.Buffer.prototype instanceof Uint8Array&&"set"===s.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},i._configure()},152:(e,t)=>{"use strict";class r{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 new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let e=0;e{},310:()=>{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>Ee});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>Se,base16upper:()=>_e});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>Ae});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>Te});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>Ce,base32hex:()=>Ne,base32hexpad:()=>Le,base32hexpadupper:()=>Oe,base32hexupper:()=>xe,base32pad:()=>Be,base32padupper:()=>De,base32upper:()=>Pe,base32z:()=>Me});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base36:()=>Ue,base36upper:()=>Ke});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base58btc:()=>Fe,base58flickr:()=>Ve});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>qe,base64pad:()=>He,base64url:()=>je,base64urlpad:()=>$e});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>ze});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Ge});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Je,decode:()=>Ze,encode:()=>Qe,name:()=>Xe});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>tt,decode:()=>nt,encode:()=>rt,name:()=>et});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>kt});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>Pt,sha512:()=>Bt});var f={};__webpack_require__.r(f),__webpack_require__.d(f,{DO:()=>Co,OG:()=>qo,My:()=>Bo,Ph:()=>Oo,lX:()=>Mo,Id:()=>Vo,fg:()=>$o,qj:()=>Fo,aT:()=>Lo,aY:()=>To,lq:()=>Uo,z:()=>Ko,Q5:()=>Go});var g={};__webpack_require__.r(g),__webpack_require__.d(g,{Ed25519PrivateKey:()=>dc,Ed25519PublicKey:()=>hc,generateKeyPair:()=>gc,generateKeyPairFromSeed:()=>yc,unmarshalEd25519PrivateKey:()=>pc,unmarshalEd25519PublicKey:()=>fc});var y={};__webpack_require__.r(y),__webpack_require__.d(y,{MAX_KEY_SIZE:()=>Ac,RsaPrivateKey:()=>kc,RsaPublicKey:()=>Ic,fromJwk:()=>Cc,generateKeyPair:()=>Pc,unmarshalRsaPrivateKey:()=>Rc,unmarshalRsaPublicKey:()=>Tc});var m={};__webpack_require__.r(m),__webpack_require__.d(m,{Secp256k1PrivateKey:()=>Wc,Secp256k1PublicKey:()=>Gc,generateKeyPair:()=>Jc,unmarshalSecp256k1PrivateKey:()=>Yc,unmarshalSecp256k1PublicKey:()=>Xc});var b={};__webpack_require__.r(b),__webpack_require__.d(b,{Ed25519PrivateKey:()=>ah,Ed25519PublicKey:()=>oh,generateKeyPair:()=>uh,generateKeyPairFromSeed:()=>hh,unmarshalEd25519PrivateKey:()=>ch,unmarshalEd25519PublicKey:()=>lh});var w={};__webpack_require__.r(w),__webpack_require__.d(w,{MAX_RSA_KEY_SIZE:()=>Rp,RsaPrivateKey:()=>Cp,RsaPublicKey:()=>Tp,fromJwk:()=>Dp,generateKeyPair:()=>Np,unmarshalRsaPrivateKey:()=>Pp,unmarshalRsaPublicKey:()=>Bp});var v={};__webpack_require__.r(v),__webpack_require__.d(v,{Secp256k1PrivateKey:()=>Op,Secp256k1PublicKey:()=>Lp,generateKeyPair:()=>Kp,unmarshalSecp256k1PrivateKey:()=>Mp,unmarshalSecp256k1PublicKey:()=>Up});var E={};__webpack_require__.r(E),__webpack_require__.d(E,{Ed25519PrivateKey:()=>Py,Ed25519PublicKey:()=>Cy,generateKeyPair:()=>Ny,generateKeyPairFromSeed:()=>xy,unmarshalEd25519PrivateKey:()=>By,unmarshalEd25519PublicKey:()=>Dy});var S={};__webpack_require__.r(S),__webpack_require__.d(S,{MAX_RSA_KEY_SIZE:()=>qy,RsaPrivateKey:()=>jy,RsaPublicKey:()=>Hy,fromJwk:()=>Gy,generateKeyPair:()=>Wy,unmarshalRsaPrivateKey:()=>$y,unmarshalRsaPublicKey:()=>zy});var _={};__webpack_require__.r(_),__webpack_require__.d(_,{Secp256k1PrivateKey:()=>Jy,Secp256k1PublicKey:()=>Xy,generateKeyPair:()=>em,unmarshalSecp256k1PrivateKey:()=>Qy,unmarshalSecp256k1PublicKey:()=>Zy});var A={};__webpack_require__.r(A),__webpack_require__.d(A,{Ed25519PrivateKey:()=>Pm,Ed25519PublicKey:()=>Cm,generateKeyPair:()=>Nm,generateKeyPairFromSeed:()=>xm,unmarshalEd25519PrivateKey:()=>Bm,unmarshalEd25519PublicKey:()=>Dm});var I={};__webpack_require__.r(I),__webpack_require__.d(I,{MAX_RSA_KEY_SIZE:()=>Hm,RsaPrivateKey:()=>$m,RsaPublicKey:()=>jm,fromJwk:()=>Wm,generateKeyPair:()=>Ym,unmarshalRsaPrivateKey:()=>zm,unmarshalRsaPublicKey:()=>Gm});var k={};__webpack_require__.r(k),__webpack_require__.d(k,{Secp256k1PrivateKey:()=>Qm,Secp256k1PublicKey:()=>Jm,generateKeyPair:()=>tb,unmarshalSecp256k1PrivateKey:()=>Zm,unmarshalSecp256k1PublicKey:()=>eb});var R={};__webpack_require__.r(R),__webpack_require__.d(R,{Ed25519PrivateKey:()=>Sb,Ed25519PublicKey:()=>Eb,generateKeyPair:()=>Ib,generateKeyPairFromSeed:()=>kb,unmarshalEd25519PrivateKey:()=>_b,unmarshalEd25519PublicKey:()=>Ab});var T={};__webpack_require__.r(T),__webpack_require__.d(T,{MAX_RSA_KEY_SIZE:()=>Lb,RsaPrivateKey:()=>Mb,RsaPublicKey:()=>Ob,fromJwk:()=>Fb,generateKeyPair:()=>Vb,unmarshalRsaPrivateKey:()=>Ub,unmarshalRsaPublicKey:()=>Kb});var C={};__webpack_require__.r(C),__webpack_require__.d(C,{Secp256k1PrivateKey:()=>jb,Secp256k1PublicKey:()=>Hb,generateKeyPair:()=>Gb,unmarshalSecp256k1PrivateKey:()=>$b,unmarshalSecp256k1PublicKey:()=>zb});var P={};__webpack_require__.r(P),__webpack_require__.d(P,{Ed25519PrivateKey:()=>y_,Ed25519PublicKey:()=>g_,generateKeyPair:()=>w_,generateKeyPairFromSeed:()=>v_,unmarshalEd25519PrivateKey:()=>m_,unmarshalEd25519PublicKey:()=>b_});var B={};__webpack_require__.r(B),__webpack_require__.d(B,{MAX_RSA_KEY_SIZE:()=>C_,RsaPrivateKey:()=>B_,RsaPublicKey:()=>P_,fromJwk:()=>x_,generateKeyPair:()=>L_,unmarshalRsaPrivateKey:()=>D_,unmarshalRsaPublicKey:()=>N_});var D={};function N(e=0){return new Uint8Array(e)}function x(e=0){return new Uint8Array(e)}__webpack_require__.r(D),__webpack_require__.d(D,{Secp256k1PrivateKey:()=>U_,Secp256k1PublicKey:()=>M_,generateKeyPair:()=>V_,unmarshalSecp256k1PrivateKey:()=>K_,unmarshalSecp256k1PublicKey:()=>F_});const L=Math.pow(2,7),O=Math.pow(2,14),M=Math.pow(2,21),U=Math.pow(2,28),K=Math.pow(2,35),F=Math.pow(2,42),V=Math.pow(2,49),q=128,H=127;function j(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $(e,t,r=0){switch(j(e)){case 8:t[r++]=255&e|q,e/=128;case 7:t[r++]=255&e|q,e/=128;case 6:t[r++]=255&e|q,e/=128;case 5:t[r++]=255&e|q,e/=128;case 4:t[r++]=255&e|q,e>>>=7;case 3:t[r++]=255&e|q,e>>>=7;case 2:t[r++]=255&e|q,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function z(e,t){let r=e[t],n=0;if(n+=r&H,r>>=7;case 3:t.set(r++,255&e|q),e>>>=7;case 2:t.set(r++,255&e|q),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function W(e,t=0){return e instanceof Uint8Array?z(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&H,r>>31>0){const e=1+~this.lo>>>0;let 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){const e=1+~this.lo>>>0;let 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(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const 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 se;if(ere)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>ie&&(n=0n,++r>ie&&(r=0n))),new ne(Number(n),Number(r))}static fromNumber(e){if(0===e)return se;const 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 ne(r,n)}static from(e){return"number"==typeof e?ne.fromNumber(e):"bigint"==typeof e?ne.fromBigInt(e):"string"==typeof e?ne.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ne(e.low>>>0,e.high>>>0):se}}const se=new ne(0,0);se.toBigInt=function(){return 0n},se.zzEncode=se.zzDecode=function(){return this},se.length=function(){return 1};const ie=4294967296n;function oe(e,t,r){const n=r;let s,i;for(let n=0;n>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function ae(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ce(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class le{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)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(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,ae(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw ae(this,4);return ce(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ae(this,4);return 0|ce(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,X[0]=t[r],X[1]=t[r+1],X[2]=t[r+2],X[3]=t[r+3],Y[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,Z[0]=t[r],Z[1]=t[r+1],Z[2]=t[r+2],Z[3]=t[r+3],Z[4]=t[r+4],Z[5]=t[r+5],Z[6]=t[r+6],Z[7]=t[r+7],Q[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw ae(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t191&&i<224?s[o++]=(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,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw ae(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw ae(this)}while(128&this.buf[this.pos++]);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(){const e=new ne(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw ae(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}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;if(t=0,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 ae(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 ae(this,8);const e=ce(this.buf,this.pos+=4),t=ce(this.buf,this.pos+=4);return new ne(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=z(this.buf,this.pos);return this.pos+=j(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 ue(e,t,r){const n=function(e){return new le(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function he(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 new Error("Unknown type, must be binary type")}new Uint8Array(0);const de=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)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 new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);fhe(s(e))})}function ve({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return be({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<function(e,t,r,n){const s={};for(let e=0;e=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}(t,n,r,e)})}const Ee=we({prefix:"9",name:"base10",alphabet:"0123456789"}),Se=ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_e=ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ae=ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Ie=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ke=Ie.reduce(((e,t,r)=>(e[r]=t,e)),[]),Re=Ie.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),Te=be({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+ke[t]),"")},decode:function(e){const t=[];for(const r of e){const e=Re[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}}),Ce=ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pe=ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Be=ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),De=ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ne=ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xe=ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Le=ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Oe=ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Me=ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ue=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ke=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Fe=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ve=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),qe=ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),He=ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),je=ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$e=ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),ze=ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Ge=be({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),We=new TextEncoder,Ye=new TextDecoder,Xe="json",Je=512;function Qe(e){return We.encode(JSON.stringify(e))}function Ze(e){return JSON.parse(Ye.decode(e))}const et="raw",tt=85;function rt(e){return he(e)}function nt(e){return he(e)}var st=128,it=-128,ot=Math.pow(2,31),at=128,ct=127,lt=Math.pow(2,7),ut=Math.pow(2,14),ht=Math.pow(2,21),dt=Math.pow(2,28),pt=Math.pow(2,35),ft=Math.pow(2,42),gt=Math.pow(2,49),yt=Math.pow(2,56),mt=Math.pow(2,63);const bt={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=ot;)r[n++]=255&t|st,t/=128;for(;t⁢)r[n++]=255&t|st,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&ct)<=at);return e.bytes=o-r,s},encodingLength:function(e){return eSt(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ct(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const Pt=Rt({name:"sha2-256",code:18,encode:Ct("SHA-256")}),Bt=Rt({name:"sha2-512",code:19,encode:Ct("SHA-512")});function Dt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,xt(e),t??Fe.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,xt(e),t??Ce.encoder)}const Nt=new WeakMap;function xt(e){const t=Nt.get(e);if(null==t){const t=new Map;return Nt.set(e,t),t}return t}class Lt{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:{const{code:e,multihash:t}=this;if(e!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Lt.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:{const{code:e,digest:t}=this.multihash,r=St(e,t);return Lt.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 Lt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{const[r,n]=wt(e.subarray(t));return t+=n,r};let n=r(),s=Ot;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Fe;return[Fe.prefix,r.decode(`${Fe.prefix}${e}`)]}case Fe.prefix:{const r=t??Fe;return[Fe.prefix,r.decode(e)]}case Ce.prefix:{const r=t??Ce;return[Ce.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),s=Lt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return xt(s).set(r,e),s}}const Ot=112,Mt=18;function Ut(e,t,r){const n=Et(e),s=n+Et(t),i=new Uint8Array(s+r.byteLength);return vt(e,i,0),vt(t,i,n),i.set(r,s),i}const Kt=Symbol.for("@ipld/js-cid/CID"),Ft={...l,...r,...c,...e,...t,...s,...i,...o,...a,...n};function Vt(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const qt=Vt("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ht=Vt("ascii","a",(e=>{let t="a";for(let r=0;r{const t=x((e=e.substring(1)).length);for(let r=0;r4096)return x(e);n+e>t&&(r=x(t),n=0);const s=r.subarray(n,n+=e);return 7&n&&(n=1+(7|n)),s}}();class Xt{len;head;tail;states;constructor(){this.len=0,this.head=new zt(Gt,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new zt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Zt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(er,10,ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ne.fromBigInt(e);return this._push(er,t.length(),t)}uint64Number(e){return this._push($,j(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){const t=ne.fromBigInt(e).zzEncode();return this._push(er,t.length(),t)}sint64Number(e){const t=ne.fromNumber(e).zzEncode();return this._push(er,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jt,1,e?1:0)}fixed32(e){return this._push(tr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ne.fromBigInt(e);return this._push(tr,4,t.lo)._push(tr,4,t.hi)}fixed64Number(e){const t=ne.fromNumber(e);return this._push(tr,4,t.lo)._push(tr,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(J,4,e)}double(e){return this._push(ee,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Jt,1,0):this.uint32(t)._push(rr,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Zt extends zt{next;constructor(e,t){super(Qt,e,t),this.next=void 0}}function er(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 tr(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 rr(e,t,r){t.set(e,r)}function nr(e,t,r){t.set(e,r)}function sr(e,t,r){e.length<40?oe(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set($t(e),r)}function ir(e,t){const r=new Xt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var or,ar,cr,lr,ur,hr,dr,pr,fr,gr,yr,mr,br,wr,vr,Er,Sr,_r,Ar,Ir,kr,Rr,Tr,Cr,Pr,Br,Dr,Nr,xr,Lr,Or,Mr,Ur;function Kr(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Fr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Kr("enum",or.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Vr(e,t){return Kr("message",or.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Xt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(nr,t,e),this},Xt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(sr,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(or||(or={}));class qr extends Error{code;constructor(e,t,r){super(e,r),this.code=t}}function Hr(e){return Boolean(e)}function jr(e){const 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}function $r(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),ar.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=ar.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(cr||(cr={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),r),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),pr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(pr.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),lr.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),ur.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=lr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=ur.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),dr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=dr.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(fr||(fr={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new qr('decode error - map field "contentTopics" had too many elements',"ERR_MAX_LENGTH");i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),wr.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.wakuMessage=wr.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),br.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=br.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Ar.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Ar.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(vr||(vr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={isSuccess:!1},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Er||(Er={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),vr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Er.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=vr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=Er.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Sr||(Sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(_r||(_r={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),_r.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=_r.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ar||(Ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={digest:N(0),receiverTime:0n,senderTime:0n,pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ir||(Ir={})),function(e){let t,r,n;!function(e){e.BACKWARD="BACKWARD",e.FORWARD="FORWARD"}(t=e.Direction||(e.Direction={})),function(e){e[e.BACKWARD=0]="BACKWARD",e[e.FORWARD=1]="FORWARD"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.Direction||(e.Direction={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{!1!==n.lengthDelimited&&r.fork(),null!=t.pageSize&&(r.uint32(8),r.uint64(t.pageSize)),null!=t.cursor&&(r.uint32(18),Ir.codec().encode(t.cursor,r)),null!=t.direction&&(r.uint32(24),e.Direction.codec().encode(t.direction,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.pageSize=t.uint64();break;case 2:s.cursor=Ir.codec().decode(t,t.uint32(),{limits:n.limits?.cursor});break;case 3:s.direction=e.Direction.codec().decode(t);break;default:t.skipType(7&r)}}return s}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(kr||(kr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Rr||(Rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),null!=e.contentFilters)for(const r of e.contentFilters)t.uint32(26),Rr.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),kr.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={})=>{const n={contentFilters:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 2:n.pubsubTopic=e.string();break;case 3:if(null!=r.limits?.contentFilters&&n.contentFilters.length===r.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(Rr.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=kr.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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Tr||(Tr={})),function(e){let t,r,n;!function(e){e.NONE="NONE",e.INVALID_CURSOR="INVALID_CURSOR",e.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",e.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE"}(t=e.HistoryError||(e.HistoryError={})),function(e){e[e.NONE=0]="NONE",e[e.INVALID_CURSOR=1]="INVALID_CURSOR",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.HistoryError||(e.HistoryError={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.messages)for(const e of t.messages)n.uint32(18),Dr.codec().encode(e,n);null!=t.pagingInfo&&(n.uint32(26),kr.codec().encode(t.pagingInfo,n)),null!=t.error&&0!==r[t.error]&&(n.uint32(32),e.HistoryError.codec().encode(t.error,n)),!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={messages:[],error:t.NONE},o=null==n?r.len:r.pos+n;for(;r.pos>>3){case 2:if(null!=s.limits?.messages&&i.messages.length===s.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");i.messages.push(Dr.codec().decode(r,r.uint32(),{limits:s.limits?.messages$}));break;case 3:i.pagingInfo=kr.codec().decode(r,r.uint32(),{limits:s.limits?.pagingInfo});break;case 4:i.error=e.HistoryError.codec().decode(r);break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Cr||(Cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Tr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),Cr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.query=Tr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=Cr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Pr||(Pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Br||(Br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Br.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=Br.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Dr||(Dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Nr||(Nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(xr||(xr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Nr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new qr('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(Nr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Lr||(Lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),xr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Lr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.query=xr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=Lr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Or||(Or={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Mr||(Mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ur||(Ur={}));function zr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Gr(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Wr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(e.outputLen),zr(e.blockLen)}function Yr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Xr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Jr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Qr=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Zr=async()=>{};async function en(e,t,r){let n=Date.now();for(let s=0;s=0&&ee().update(rn(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function cn(e=32){if(Xr&&"function"==typeof Xr.getRandomValues)return Xr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}const ln=(e,t,r)=>e&t^e&r^t&r;class un extends sn{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=Jr(this.buffer)}update(e){Yr(this);const{view:t,buffer:r,blockLen:n}=this,s=(e=rn(e)).length;for(let i=0;in-i&&(this.process(r,0),i=0);for(let e=i;e>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=Jr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,s=Qr(r,17)^Qr(r,19)^r>>>10;pn[e]=s+pn[e-7]+n+pn[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Qr(o,6)^Qr(o,11)^Qr(o,25))+((u=o)&a^~u&c)+hn[e]+pn[e]|0,h=(Qr(r,2)^Qr(r,13)^Qr(r,22))+ln(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){pn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const gn=an((()=>new fn));var yn,mn,bn,wn,vn,En;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(yn||(yn={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.REMOTE_PEER_FAULT="Remote peer fault",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout"}(mn||(mn={})),function(e){e.BACKWARD="backward",e.FORWARD="forward"}(bn||(bn={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(wn||(wn={})),function(e){e.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",e.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",e.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",e.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"}(vn||(vn={})),function(e){e.CONNECTION_STATUS="waku:connection"}(En||(En={}));const Sn="/waku/2/default-waku/proto",_n=1;function An(e,t="utf8"){const r=jt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function In(e){return"string"==typeof e?$t(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}const kn=e=>An(e,"base16"),Rn=e=>An(e,"utf8"),Tn=e=>$t(e,"utf8");function Cn(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}const Pn=e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??_n}/${e.shard}`},Bn=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>Ln(t,e.clusterId)))));if("shards"in e){if(void 0===e.shards)throw new Error("Invalid shard");return Array.from(new Set(e.shards.map((t=>`/waku/2/rs/${e.clusterId??_n}/${t}`))))}if("application"in e&&"version"in e)return[Ln(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},Dn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function Nn(e,t){if(!t.includes(e))throw new 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 xn(e,t=8){const{application:r,version:n}=function(e){const 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(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),s=gn(Cn([Tn(r),Tn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}function Ln(e,t=_n,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${xn(e,r)}`}function On(e,t){return"string"==typeof t?t:void 0!==t?.shard?Pn(t):Ln(e,t?.clusterId??_n)}const Mn=e=>{const t=e.clusterId??_n,r="shards"in e?e.shards:[],n="contentTopics"in e?e.contentTopics:[],[s,i]="application"in e&&"version"in e?[e.application,e.version]:[void 0,void 0],o=r&&r.length>0,a=n&&n.length>0,c=s&&i;if(o)return{shardingParams:{clusterId:t,shards:r},shardInfo:{clusterId:t,shards:r},pubsubTopics:Bn({clusterId:t,shards:r})};if(a){const e=Array.from(new Set(n.map((e=>Ln(e,t))))),r=Array.from(new Set(n.map((e=>xn(e)))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(c){const e=Ln(`/${s}/${i}/default/default`,t);return{shardingParams:{clusterId:t,application:s,version:i},shardInfo:{clusterId:t,shards:[Dn(e).shard]},pubsubTopics:[e]}}throw new Error("Missing minimum required configuration options for static sharding or autosharding.")},Un=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},Kn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function Jn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=x(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Qn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!ts(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!ts(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=es(this.bufs,e);return t.buf[t.index]}set(e,t){const r=es(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Jn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Jn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new rs;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s=a)continue;const c=e>=o&&eo&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(ts(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=x(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=x(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof rs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;te+t.byteLength),0)),r.length=t,r}}function ns(e){return null!=e[Symbol.asyncIterator]}const ss=e=>{const t=j(e),r=x(t);return G(e,r),ss.bytes=t,r};function is(e,t){const r=(t=t??{}).lengthEncoder??ss;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return ns(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}ss.bytes=0,is.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??ss;return new rs(r(e.byteLength),e)};var os,as=__webpack_require__(6310);!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(os||(os={}));const cs=e=>{const t=W(e);return cs.bytes=j(t),t};function ls(e,t){const r=new rs;let n=os.LENGTH,s=-1;const i=t?.lengthDecoder??cs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===os.LENGTH)try{if(s=i(r),s<0)throw as(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw as(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=os.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw as(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===os.DATA){if(r.byteLength0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}function us(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}cs.bytes=0,ls.fromReader=(e,t)=>{let r=1;return ls(async function*(){for(;;)try{const{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}}(),{...t??{},onLength:e=>{r=e}})};class hs{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const 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 ds{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new hs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class ps extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function fs(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new ds,a=us();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new ds,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=us()}))}},return:()=>(o=new ds,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new ps)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const 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)}const gs=function(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(){for(const e of t)yield*e}():async function*(){const t=fs({objectMode:!0});Promise.resolve().then((async()=>{try{await Promise.all(e.map((async e=>{for await(const r of e)t.push(r)}))),t.end()}catch(e){t.end(e)}})),yield*t}()};function ys(e,...t){if(null==e)throw new Error("Empty pipeline");if(vs(e)){const t=e;e=()=>t.source}else if(ws(e)||bs(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&vs(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e{let t;for(;e.length>0;)t=e.shift()(t);return t},bs=e=>null!=e?.[Symbol.asyncIterator],ws=e=>null!=e?.[Symbol.iterator],vs=e=>null!=e&&null!=e.sink&&null!=e.source,Es=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=fs({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(bs(s))n=async function*(){yield*s,t.end()};else{if(!ws(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return gs(t,n())}return e.source};class Ss{multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new qn(`stream-manager:${e}`),this.streamPool=new Map,this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.createStream(e);this.streamPool.delete(t),this.prepareStream(e);try{const e=await r;if(e&&"closed"!==e.status)return e}catch(e){this.log.warn(`Failed to get stream for ${t} -- `,e),this.log.warn("Attempting to create a new stream for the peer")}return this.createStream(e)}async createStream(e,t=0){const r=function(e){if(!e.length)return;if(1===e.length)return e[0];let t;return e.forEach((e=>{"open"===e.status&&(t?e.timeline.open>t.timeline.open&&(t=e):t=e)})),t}(this.getConnections(e.id));if(!r)throw new Error("Failed to get a connection to the peer");try{return await r.newStream(this.multicodec)}catch(r){if(t<3){const r=1e3*Math.pow(2,t);return await new Promise((e=>setTimeout(e,r))),this.createStream(e,t+1)}throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+r)}}prepareStream(e){const t=new Promise((e=>setTimeout(e,5e3))),r=Promise.race([this.createStream(e),t.then((()=>{throw new Error("Connection timeout")}))]).catch((t=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()} -- `,t)}));this.streamPool.set(e.id.toString(),r)}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;if(t.protocols.includes(this.multicodec))if(this.isConnectedTo(t.id))this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareStream(t);else{const e=t.id.toString();this.streamPool.delete(e),this.log.info(`Removed pending stream for disconnected peer ${e}`)}};isConnectedTo(e){return this.getConnections(e).some((e=>"open"===e.status))}}class _s{multicodec;components;log;pubsubTopics;options;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n,s){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.options=s,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new Ss(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 async function(e,t){const r=[];return await e.forEach((e=>{for(let n=0;nthis.components.connectionManager.getConnections(e.id).length>0))}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:1,numPeers:0}){const r=function(e,t,r){let n=e.filter((e=>e.tags.has(wn.BOOTSTRAP))).slice(0,r);t>0&&t!e.tags.has(wn.BOOTSTRAP)));if(0===t)return[...n,...s];const i=[...n];for(;i.length0;){const e=Math.floor(Math.random()*s.length),t=s.splice(e,1)[0];i.push(t)}return i}(await async function(e,t,r,n){const s=e.filter((e=>"open"===e.status)).map((async e=>{const s=await t.get(e.remotePeer);if(r.some((e=>s.protocols.includes(e)))){if(!n)return s;{const e=s.metadata.get("shardInfo"),t=e&&Un(e);if(t&&n.clusterId===t.clusterId)return s}}return null}));return(await Promise.all(s)).filter((e=>null!==e))}(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?Mn(this.options.shardInfo).shardInfo:void 0),e,t),n=await async function(e,t){return 0===t.length?[]:(await Promise.all(t.map((async t=>{try{const r=(await e.get(t.id)).metadata.get("ping");return r?{peer:t,ping:Number(Rn(r))}:{peer:t,ping:1/0}}catch(e){return{peer:t,ping:1/0}}})))).filter((e=>null!==e)).sort(((e,t)=>e.ping-t.ping)).map((e=>e.peer))}(this.peerStore,r);return 0===n.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),n.length{Ns.error("Failed to register ",xs,e)}))}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Ns.info(`Received message from ${n.toString()}`);try{ys(r,ls,(async e=>{for await(const t of e){const e=Ps.decode(t.slice()),{pubsubTopic:r,wakuMessage:n}=e;if(!n)return void Ns.error("Received empty message");if(!r)return void Ns.error("Pubsub topic missing from push message");await this.handleIncomingMessage(r,n)}})).then((()=>{Ns.info("Receiving pipe closed.")}),(e=>{Ns.error("Error with receiving pipe",e)}))}catch(e){Ns.error("Error decoding message",e)}}async subscribe(e,t,r){const n=await this.getStream(t),s=Bs.createSubscribeRequest(e,r);let i;try{i=await ys([s.encode()],is,n,ls,(async e=>await Xn(e)))}catch(e){return Ns.error("Failed to send subscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}const{statusCode:o,requestId:a,statusDesc:c}=Ds.decode(i[0].slice());return o<200||o>=300?(Ns.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:mn.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return Ns.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id}}}const s=Bs.createUnsubscribeRequest(e,r);try{await ys([s.encode()],is,n.sink)}catch(e){return Ns.error("Failed to send unsubscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=Bs.createUnsubscribeAllRequest(e),s=await ys([n.encode()],is,r,ls,(async e=>await Xn(e)));if(!s||!s.length)return{failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ds.decode(s[0].slice());return i<200||i>=300?(Ns.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:mn.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t;try{t=await this.getStream(e)}catch(t){return Ns.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}}}const r=Bs.createSubscriberPingRequest();let n;try{n=await ys([r.encode()],is,t,ls,(async e=>await Xn(e)))}catch(t){return Ns.error("Failed to send ping request",t),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}};const{statusCode:s,requestId:i,statusDesc:o}=Ds.decode(n[0].slice());return s<200||s>=300?(Ns.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}}class Os{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Os({requestId:Cs(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=Sr.decode(e);return new Os(t)}encode(){return Sr.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Ms=new qn("light-push");class Us extends _s{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,Ms,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Ms.error("Failed to send waku light push: payload is empty"),{query:null,error:mn.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Ms.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:mn.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:Os.createRequest(r,e.pubsubTopic),error:null}:(Ms.error("Failed to encode to protoMessage, aborting push"),{query:null,error:mn.ENCODE_FAILED})}catch(e){return Ms.error("Failed to prepare push message",e),{query:null,error:mn.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:s}=await this.preparePushMessage(e,t);if(s||!n)return{success:null,failure:{error:s,peerId:r.id}};let i,o;try{i=await this.getStream(r)}catch(e){return Ms.error("Failed to get stream",e),{success:null,failure:{error:mn.NO_STREAM_AVAILABLE,peerId:r.id}}}try{o=await ys([n.encode()],is,i,ls,(async e=>await Xn(e)))}catch(e){return Ms.error("Failed to send waku light push request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:r.id}}}const a=new rs;let c;o.forEach((e=>{a.append(e)}));try{c=Os.decode(a).response}catch(e){return Ms.error("Failed to decode push reply",e),{success:null,failure:{error:mn.DECODE_FAILED,peerId:r.id}}}return c?c.isSuccess?{success:r.id,failure:null}:(Ms.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:r.id}}):(Ms.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:r.id}})}}const Ks={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Fs=BigInt(1e6);var Vs;!function(e){e.BACKWARD="backward",e.FORWARD="forward"}(Vs||(Vs={}));class qs{proto;constructor(e){this.proto=e}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){const t=e.contentTopics.map((e=>({contentTopic:e}))),r=function(e){switch(e){case Vs.BACKWARD:return kr.Direction.BACKWARD;case Vs.FORWARD:return kr.Direction.FORWARD;default:return kr.Direction.BACKWARD}}(e.pageDirection),n={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:r};let s,i;return e.startTime&&(s=BigInt(e.startTime.valueOf())*Fs),e.endTime&&(i=BigInt(e.endTime.valueOf())*Fs),new qs({requestId:Cs(),query:{pubsubTopic:e.pubsubTopic,contentFilters:t,pagingInfo:n,startTime:s,endTime:i},response:void 0})}decode(e){const t=Pr.decode(e);return new qs(t)}encode(){return Pr.encode(this.proto)}}var Hs=Cr.HistoryError;const js=new qn("store");class $s extends _s{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,js,t.pubsubTopics,t)}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.cursor;for(;;){e.cursor=n;const s=qs.createQuery(e);let i;try{i=await this.getStream(r)}catch(e){js.error("Failed to get stream",e);break}const o=await ys([s.encode()],is,i,ls,(async e=>await Xn(e))),a=new rs;o.forEach((e=>{a.append(e)}));const c=s.decode(a);if(!c.response){js.warn("Stopping pagination due to store `response` field missing");break}const l=c.response;if(l.error&&l.error!==Hs.NONE)throw"History response contains an Error: "+l.error;if(!l.messages||!l.messages.length){js.warn("Stopping pagination due to store `response.messages` field missing or empty");break}js.error(`${l.messages.length} messages retrieved from store`),yield l.messages.map((r=>{const n=r.contentTopic;if(void 0!==n){const i=t.get(n);if(i)return i.fromProtoObj(e.pubsubTopic,(s=r,{...Ks,...s}))}var s;return Promise.resolve(void 0)}));const u=l.pagingInfo?.cursor;if(void 0===u){js.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;const h=l.pagingInfo?.pageSize,d=s.query?.pagingInfo?.pageSize;if(h&&d&&hvoid 0===globalThis.DOMException?new Gs(e):new DOMException(e),Ys=e=>{const t=void 0===e.reason?Ws("This operation was aborted."):e.reason;return t instanceof Error?t:Ws(t)};function Xs(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=t;let o;const a=new Promise(((a,c)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&c(Ys(e)),e.addEventListener("abort",(()=>{c(Ys(e))}))}if(r===Number.POSITIVE_INFINITY)return void e.then(a,c);const l=new zs;o=i.setTimeout.call(void 0,(()=>{if(n)try{a(n())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?c(s):(l.message=s??`Promise timed out after ${r} milliseconds`,c(l))}),r),(async()=>{try{a(await e)}catch(e){c(e)}})()})).finally((()=>{a.clear()}));return a.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},a}const Js=e=>{const t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Qs(e,t,r){"function"==typeof r&&(r={filter:r});const n=function(e,t,r){let n;const s=new Promise(((s,i)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r}).count>=0)||r.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(r.count))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const o=[t].flat(),a=[],{addListener:c,removeListener:l}=Js(e),u=(...e)=>{const t=r.multiArgs?e:e[0];r.filter&&!r.filter(t)||(a.push(t),r.count===a.length&&(n(),s(a)))},h=e=>{n(),i(e)};n=()=>{for(const e of o)l(e,u);for(const e of r.rejectionEvents)l(e,h)};for(const e of o)c(e,u);for(const e of r.rejectionEvents)c(e,h);r.signal&&r.signal.addEventListener("abort",(()=>{h(r.signal.reason)}),{once:!0}),r.resolveImmediately&&s(a)}));if(s.cancel=n,"number"==typeof r.timeout){const e=Xs(s,{milliseconds:r.timeout});return e.cancel=n,e}return s}(e,t,r={...r,count:1,resolveImmediately:!1}),s=n.then((e=>e[0]));return s.cancel=n.cancel,s}const Zs=new qn("wait-for-remote-peer");async function ei(e,t,r){if(t=t??function(e){const t=[];return e.relay&&t.push(yn.Relay),e.filter&&t.push(yn.Filter),e.store&&t.push(yn.Store),e.lightPush&&t.push(yn.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");const n=[];if(t.includes(yn.Relay)){if(!e.relay)throw new Error("Cannot wait for Relay peer: protocol not mounted");n.push(async function(e){let t=e.getMeshPeers();const r=e.pubsubTopics;for(const n of r)for(;0==t.length;)await Qs(e.gossipSub,"gossipsub:heartbeat"),t=e.getMeshPeers(n)}(e.relay))}if(t.includes(yn.Store)){if(!e.store)throw new Error("Cannot wait for Store peer: protocol not mounted");n.push(ti(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(yn.LightPush)){if(!e.lightPush)throw new Error("Cannot wait for LightPush peer: protocol not mounted");n.push(ti(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(yn.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");n.push(ti(e.filter.protocol,e.libp2p.services.metadata))}r?await async function(e,t,r){await Promise.race([e,ri(t,"Timed out waiting for a remote peer.")])}(Promise.all(n),r):await Promise.all(n)}async function ti(e,t){const r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t)return void Zs.info(`${r} peer found: `,n[0].id.toString());try{return void await Promise.any(n.map((e=>t.confirmOrAttemptHandshake(e.id))))}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)}}Zs.info(`Waiting for ${r} peer`),await new Promise((n=>{const s=i=>{i.detail?.protocols?.includes(r)&&(t?t.confirmOrAttemptHandshake(i.detail.peerId).then((()=>{e.removeLibp2pEventListener("peer:identify",s),n()})).catch((e=>{"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)})):(e.removeLibp2pEventListener("peer:identify",s),n()))};e.addLibp2pEventListener("peer:identify",s)}))}const ri=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(t)),e)));class ni extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const 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){const t=super.dispatchEvent(e);let 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 ii(e,t))}}class si extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}const ii=globalThis.CustomEvent??si,oi=new qn("keep-alive");class ai{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);const{pingKeepAlive:n,relayKeepAlive:s}=this.options,i=e.toString();if(0!==n){const s=setInterval((()=>{(async()=>{let s;try{try{s=await t.ping(e),oi.info(`Ping succeeded (${i})`,s)}catch(e){return void oi.error(`Ping failed for peer (${i}).\n Next ping will be attempted in ${n} seconds.\n `)}try{await r.merge(e,{metadata:{ping:Tn(s.toString())}})}catch(e){oi.error("Failed to update ping",e)}}catch(e){oi.error(`Ping failed (${i})`,e)}})()}),1e3*n);this.pingKeepAliveTimers.set(i,s)}const o=this.relay;if(o&&0!==s){const t=this.scheduleRelayPings(o,s,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const 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(const 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){const n=[];for(const s of e.pubsubTopics){if(!e.getMeshPeers(s).includes(r))continue;const i=Gn({pubsubTopicShardInfo:Dn(s),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),o=setInterval((()=>{oi.info("Sending Waku Relay ping message"),e.send(i,{payload:new Uint8Array([1])}).catch((e=>oi.error("Failed to send relay ping",e)))}),1e3*t);n.push(o)}return n}}const ci=new qn("connection-manager");class li extends ni{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 ii(En.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new ii(En.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,s,i){let o=li.instances.get(e);return o||(o=new li(t,r,n,s,i),li.instances.set(e,o)),o}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],s=[],i=[],o=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(wn.BOOTSTRAP)?r.push(t):e.includes(wn.PEER_EXCHANGE)?n.push(t):e.includes(wn.LOCAL)&&s.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(wn.BOOTSTRAP)?i.push(t):r.includes(wn.PEER_EXCHANGE)?o.push(t):r.includes(wn.LOCAL)&&a.push(t)}return{DISCOVERED:{[wn.BOOTSTRAP]:r,[wn.PEER_EXCHANGE]:n,[wn.LOCAL]:s},CONNECTED:{[wn.BOOTSTRAP]:i,[wn.PEER_EXCHANGE]:o,[wn.LOCAL]:a}}}constructor(e,t,r,n,s){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...s},this.keepAliveManager=new ai(t,n),this.run().then((()=>ci.info("Connection Manager is now running"))).catch((e=>ci.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>ci.error("Unexpected error while dialing peer store peers",e)))}async dialPeerStorePeers(){const e=await this.libp2p.peerStore.all(),t=[];for(const 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){ci.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{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1);break}catch(r){r instanceof AggregateError?ci.error(`Error dialing peer ${e.toString()} - ${r.errors}`):ci.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{const t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?ci.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):ci.warn("No errors array found for AggregateError"):r=t.message,ci.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 new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),ci.info(`Dropped connection with peer ${e.toString()}`)}catch(t){ci.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{ci.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){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):this.dialPeer(e).catch((t=>{ci.error(`Error dialing peer ${e.toString()} : ${t}`)})))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){ci.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{ci.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t,this.libp2p.services.ping,this.libp2p.peerStore),(await this.getTagNamesForPeer(t)).includes(wn.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(wn.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new ii(vn.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new ii(vn.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.toggleOnline()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.toggleOffline()})()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return ci.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return ci.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(ci.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(ci.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){return!(await this.getTagNamesForPeer(e)).some((e=>e===wn.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===wn.BOOTSTRAP)))).lengththis.configuredPubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return Un(r)}}const ui=new qn("metadata"),hi="/vac/waku/metadata/1.0.0";class di extends _s{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(hi,t.components,ui,Bn(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(hi,(e=>{this.onRequest(e)}))}async onRequest(e){try{const{stream:t,connection:r}=e,n=Ur.encode(this.shardInfo),s=await ys([n],is,t,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){ui.error("Error handling metadata request",e)}}async query(e){const t=Mr.encode(this.shardInfo),r=await this.peerStore.get(e);if(!r)return{shardInfo:null,error:mn.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(i){return ui.error("Failed to get stream",i),{shardInfo:null,error:mn.NO_STREAM_AVAILABLE}}const s=await ys([t],is,n,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);return i?{shardInfo:null,error:i}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){const t=new rs;e.forEach((e=>{t.append(e)}));const r=Ur.decode(t);return r?{shardInfo:r,error:null}:(ui.error("Error decoding metadata response"),{shardInfo:null,error:mn.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:Kn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function pi(e){return t=>new di(e,t)}class fi 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 gi(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new fi(r?.errorMessage,r?.errorCode));let n;const s=new fi(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class yi{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=us(),this.haveNext=us()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=us(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=us(),await gi(this.readNext.promise,t?.signal,t)}}class mi extends Error{code;constructor(e,t){super(e),this.code=t}}class bi extends mi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}class wi extends Error{code;constructor(e,t){super(e),this.code=t}}function vi(e,t={}){const r=function(e,t){const r=new yi;e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const 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]());const s=new rs,i={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const i=new Promise(((e,n)=>{r=()=>{n(new bi("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),i]);return!0===e?new rs:t}for(;s.byteLength{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}};return i}(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=j(t.maxDataLength));const n=t?.lengthDecoder??W,s=t?.lengthEncoder??G;return{read:async e=>{let s=-1;const i=new rs;for(;;){i.append(await r.read(1,e));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new wi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new wi("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(s,e)},write:async(e,t)=>{await r.write(new rs(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new rs(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Ei(){const e=us();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Si=65535,_i=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS),Ai=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function Ii(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function ki(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Ri(e){if("string"==typeof e)e=ki(e);else{if(!Ii(e))throw new Error("expected Uint8Array, got "+typeof e);e=e.slice()}return e}function Ti(e,t){if(!Ii(e))throw new Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}const Ci=(e,t)=>(Object.assign(t,e),t);function Pi(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function Bi(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`wrong positive integer: ${e}`)}function Di(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ni(e,...t){if(null==(r=e)||"object"!=typeof r||!(r instanceof Uint8Array||"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function xi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Li=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Oi{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,Ti(e=Ri(e),32);const t=Li(e,0),r=Li(e,2),n=Li(e,4),s=Li(e,6),i=Li(e,8),o=Li(e,10),a=Li(e,12),c=Li(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Li(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],y=Li(e,t+0),m=Li(e,t+2),b=Li(e,t+4),w=Li(e,t+6),v=Li(e,t+8),E=Li(e,t+10),S=Li(e,t+12),_=Li(e,t+14);let A=s[0]+(8191&y),I=s[1]+(8191&(y>>>13|m<<3)),k=s[2]+(8191&(m>>>10|b<<6)),R=s[3]+(8191&(b>>>7|w<<9)),T=s[4]+(8191&(w>>>4|v<<12)),C=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),B=s[7]+(8191&(E>>>11|S<<5)),D=s[8]+(8191&(S>>>8|_<<8)),N=s[9]+(_>>>5|n),x=0,L=x+A*o+I*(5*g)+k*(5*f)+R*(5*p)+T*(5*d);x=L>>>13,L&=8191,L+=C*(5*h)+P*(5*u)+B*(5*l)+D*(5*c)+N*(5*a),x+=L>>>13,L&=8191;let O=x+A*a+I*o+k*(5*g)+R*(5*f)+T*(5*p);x=O>>>13,O&=8191,O+=C*(5*d)+P*(5*h)+B*(5*u)+D*(5*l)+N*(5*c),x+=O>>>13,O&=8191;let M=x+A*c+I*a+k*o+R*(5*g)+T*(5*f);x=M>>>13,M&=8191,M+=C*(5*p)+P*(5*d)+B*(5*h)+D*(5*u)+N*(5*l),x+=M>>>13,M&=8191;let U=x+A*l+I*c+k*a+R*o+T*(5*g);x=U>>>13,U&=8191,U+=C*(5*f)+P*(5*p)+B*(5*d)+D*(5*h)+N*(5*u),x+=U>>>13,U&=8191;let K=x+A*u+I*l+k*c+R*a+T*o;x=K>>>13,K&=8191,K+=C*(5*g)+P*(5*f)+B*(5*p)+D*(5*d)+N*(5*h),x+=K>>>13,K&=8191;let F=x+A*h+I*u+k*l+R*c+T*a;x=F>>>13,F&=8191,F+=C*o+P*(5*g)+B*(5*f)+D*(5*p)+N*(5*d),x+=F>>>13,F&=8191;let V=x+A*d+I*h+k*u+R*l+T*c;x=V>>>13,V&=8191,V+=C*a+P*o+B*(5*g)+D*(5*f)+N*(5*p),x+=V>>>13,V&=8191;let q=x+A*p+I*d+k*h+R*u+T*l;x=q>>>13,q&=8191,q+=C*c+P*a+B*o+D*(5*g)+N*(5*f),x+=q>>>13,q&=8191;let H=x+A*f+I*p+k*d+R*h+T*u;x=H>>>13,H&=8191,H+=C*l+P*c+B*a+D*o+N*(5*g),x+=H>>>13,H&=8191;let j=x+A*g+I*f+k*p+R*d+T*h;x=j>>>13,j&=8191,j+=C*u+P*l+B*c+D*a+N*o,x+=j>>>13,j&=8191,x=(x<<2)+x|0,x=x+L|0,L=8191&x,x>>>=13,O+=x,s[0]=L,s[1]=O,s[2]=M,s[3]=U,s[4]=K,s[5]=F,s[6]=V,s[7]=q,s[8]=H,s[9]=j}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let 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 s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i}update(e){xi(this);const{buffer:t,blockLen:r}=this,n=(e=Ri(e)).length;for(let s=0;s>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const Mi=function(e){const t=(t,r)=>e(r).update(Ri(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new Oi(e))),Ui=ki("expand 16-byte k"),Ki=ki("expand 32-byte k"),Fi=Ai(Ui),Vi=Ai(Ki);function qi(e,t){return e<>>32-t}function Hi(e){return e.byteOffset%4==0}const ji=2**32-1,$i=new Uint32Array;function zi(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||(r=t,"[object Object]"!==Object.prototype.toString.call(r)||r.constructor!==Object)))throw new Error("options must be object or undefined");var r;return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Bi(s),Bi(o),Di(i),Di(r),(t,a,c,l,u=0)=>{Ni(t),Ni(a),Ni(c);const h=c.length;if(l||(l=new Uint8Array(h)),Ni(l),Bi(u),u<0||u>=ji)throw new Error("arx: counter overflow");if(l.length=ji)throw new Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t0;)d.pop().fill(0);return l}}function Gi(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,_=a,A=c,I=l,k=u,R=h,T=d,C=p,P=f,B=g,D=y,N=m,x=b,L=w,O=v,M=E;for(let e=0;e{e.update(t);const r=t.length%16;r&&e.update(Xi.subarray(r))},Qi=new Uint8Array(32);function Zi(e,t,r,n,s){const i=e(t,r,Qi),o=Mi.create(i);s&&Ji(o,s),Ji(o,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;Pi(c,0,BigInt(s?s.length:0),!0),Pi(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return i.fill(0),u}const eo=e=>(t,r,n)=>(Ti(t,32),Ti(r),{encrypt:(s,i)=>{const o=s.length,a=o+16;i?Ti(i,a):i=new Uint8Array(a),e(t,r,s,i,1);const c=Zi(e,t,r,i.subarray(0,-16),n);return i.set(c,o),i},decrypt:(s,i)=>{const o=s.length,a=o-16;if(o<16)throw new Error("encrypted data must be at least 16 bytes");i?Ti(i,a):i=new Uint8Array(a);const c=s.subarray(0,-16);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n>no&ro)}:{h:0|Number(e>>no&ro),l:0|Number(e&ro)}}const io=function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let s=0;se>>>r,ao=(e,t,r)=>e<<32-r|t>>>r,co=(e,t,r)=>e>>>r|t<<32-r,lo=(e,t,r)=>e<<32-r|t>>>r,uo=(e,t,r)=>e<<64-r|t>>>r-32,ho=(e,t,r)=>e>>>r-32|t<<64-r,po=function(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}},fo=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),go=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,yo=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),mo=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,bo=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,wo=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),[vo,Eo]=(()=>io(["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)))))(),So=new Uint32Array(80),_o=new Uint32Array(80);class Ao extends un{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(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,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|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,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)So[r]=e.getUint32(t),_o[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|So[e-15],r=0|_o[e-15],n=co(t,r,1)^co(t,r,8)^oo(t,r,7),s=lo(t,r,1)^lo(t,r,8)^ao(t,r,7),i=0|So[e-2],o=0|_o[e-2],a=co(i,o,19)^uo(i,o,61)^oo(i,o,6),c=lo(i,o,19)^ho(i,o,61)^ao(i,o,6),l=yo(s,c,_o[e-7],_o[e-16]),u=mo(l,n,a,So[e-7],So[e-16]);So[e]=0|u,_o[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){const t=co(u,h,14)^co(u,h,18)^uo(u,h,41),b=lo(u,h,14)^lo(u,h,18)^ho(u,h,41),w=u&d^~u&f,v=wo(m,b,h&p^~h&g,Eo[e],_o[e]),E=bo(v,y,t,w,vo[e],So[e]),S=0|v,_=co(r,n,28)^uo(r,n,34)^uo(r,n,39),A=lo(r,n,28)^ho(r,n,34)^ho(r,n,39),I=r&s^r&o^s&o,k=n&i^n&a^i&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=po(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const R=fo(S,A,k);r=go(R,E,_,I),n=0|R}({h:r,l:n}=po(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=po(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=po(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l}=po(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=po(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=po(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=po(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=po(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,y,m)}roundClean(){So.fill(0),_o.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)}}const Io=an((()=>new Ao)),ko=(BigInt(0),BigInt(1)),Ro=BigInt(2);function To(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Co(e){if(!To(e))throw new Error("Uint8Array expected")}const Po=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Bo(e){Co(e);let t="";for(let r=0;r=No._0&&e<=No._9?e-No._0:e>=No._A&&e<=No._F?e-(No._A-10):e>=No._a&&e<=No._f?e-(No._a-10):void 0}function Lo(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t(Ro<new Uint8Array(e),jo=e=>Uint8Array.from(e);function $o(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let n=Ho(e),s=Ho(e),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...e)=>r(s,n,...e),c=(e=Ho())=>{s=a(jo([0]),e),n=a(),0!==e.length&&(s=a(jo([1]),e),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(o(),c(e);!(r=t(l()));)c();return o(),r}}const zo={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||To(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 Go(e,t,r={}){const n=(t,r,n)=>{const s=zo[r];if("function"!=typeof s)throw new Error(`Invalid validator "${r}", expected function`);const i=e[t];if(!(n&&void 0===i||s(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}const Wo=BigInt(0),Yo=BigInt(1),Xo=BigInt(2),Jo=BigInt(3),Qo=BigInt(4),Zo=BigInt(5),ea=BigInt(8);function ta(e,t){const r=e%t;return r>=Wo?r:t+r}function ra(e,t,r){if(r<=Wo||t 0");if(r===Yo)return Wo;let n=Yo;for(;t>Wo;)t&Yo&&(n=n*e%r),e=e*e%r,t>>=Yo;return n}function na(e,t,r){let n=e;for(;t-- >Wo;)n*=n,n%=r;return n}function sa(e,t){if(e===Wo||t<=Wo)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ta(e,t),n=t,s=Wo,i=Yo,o=Yo,a=Wo;for(;r!==Wo;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==Yo)throw new Error("invert: does not exist");return ta(s,t)}BigInt(9),BigInt(16);const ia=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oa(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function aa(e,t,r=!1,n={}){if(e<=Wo)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=oa(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=function(e){if(e%Qo===Jo){const t=(e+Yo)/Qo;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}if(e%ea===Zo){const t=(e-Zo)/ea;return function(e,r){const n=e.mul(r,Xo),s=e.pow(n,t),i=e.mul(r,s),o=e.mul(e.mul(i,Xo),s),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Yo)/Xo;let r,n,s;for(r=e-Yo,n=0;r%Xo===Wo;r/=Xo,n++);for(s=Xo;sta(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return Wo<=t&&te===Wo,isOdd:e=>(e&Yo)===Yo,neg:t=>ta(-t,e),eql:(e,t)=>e===t,sqr:t=>ta(t*t,e),add:(t,r)=>ta(t+r,e),sub:(t,r)=>ta(t-r,e),mul:(t,r)=>ta(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===Wo)return e.ONE;if(r===Yo)return t;let n=e.ONE,s=t;for(;r>Wo;)r&Yo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Yo;return n}(a,e,t),div:(t,r)=>ta(t*sa(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>sa(t,e),sqrt:n.sqrt||(e=>o(a,e)),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n))),e.ONE),s=e.inv(n);return t.reduceRight(((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n))),s),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Ko(e,i):Uo(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return r?Mo(e):Oo(e)}});return Object.freeze(a)}function ca(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function la(e){const t=ca(e);return t+Math.ceil(t/2)}const ua=BigInt(0),ha=BigInt(1);function da(e,t){const r=(e,t)=>{const 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,s=t;for(;r>ua;)r&ha&&(n=n.add(s)),s=s.double(),r>>=ha;return n},precomputeWindow(e,t){const{windows:r,windowSize:s}=n(t),i=[];let o=e,a=o;for(let e=0;e>=d,n>a&&(n-=h,i+=ha);const o=t,p=t+Math.abs(n)-1,f=e%2!=0,g=n<0;0===n?l=l.add(r(f,s[o])):c=c.add(r(g,s[p]))}return{p:c,f:l}},wNAFCached(e,t,r,n){const s=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,s),1!==s&&t.set(e,n(i))),this.wNAF(s,i,r)}}}function pa(e){return function(e){const t=ia.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});Go(e,t)}(e.Fp),Go(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...oa(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const fa=BigInt(0),ga=BigInt(1),ya=BigInt(2),ma=BigInt(8),ba={zip215:!0};function wa(e){const t=function(e){const t=pa(e);return Go(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:s,hash:i,randomBytes:o,nByteLength:a,h:c}=t,l=ya<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:fa}}}),d=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,r)=>{if(t.length||r)throw new Error("Contexts/pre-hash are not supported");return e}),f=e=>"bigint"==typeof e&&faf(e)&&f(t)&&ee===fa||g(e,l);function m(e,t){if(g(e,t))return e;throw new Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function b(e){return e===fa?e:m(e,n)}const w=new Map;function v(e){if(!(e instanceof E))throw new Error("ExtendedPoint expected")}class E{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!y(e))throw new Error("x required");if(!y(t))throw new Error("y required");if(!y(r))throw new Error("z required");if(!y(n))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};if(!y(t)||!y(r))throw new Error("invalid affine point");return new E(t,r,ga,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(E.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,w.delete(this)}assertValidity(){const{a:e,d:r}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:n,ey:s,ez:i,et:o}=this,a=u(n*n),c=u(s*s),l=u(i*i),h=u(l*l),d=u(a*e);if(u(l*u(d+c))!==u(h+u(r*u(a*c))))throw new Error("bad point: equation left != right (1)");if(u(n*s)!==u(i*o))throw new Error("bad point: equation left != right (2)")}equals(e){v(e);const{ex:t,ey:r,ez:n}=this,{ex:s,ey:i,ez:o}=e,a=u(t*o),c=u(s*n),l=u(r*o),h=u(i*n);return a===c&&l===h}is0(){return this.equals(E.ZERO)}negate(){return new E(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:s}=this,i=u(r*r),o=u(n*n),a=u(ya*u(s*s)),c=u(e*i),l=r+n,h=u(u(l*l)-i-o),d=c+o,p=d-a,f=c-o,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new E(g,y,b,m)}add(e){v(e);const{a:r,d:n}=t,{ex:s,ey:i,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((i-s)*(l+c)),t=u((i+s)*(l-c)),r=u(t-e);if(r===fa)return this.double();const n=u(o*ya*d),p=u(a*ya*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),w=u(f*y),v=u(r*g);return new E(m,b,v,w)}const p=u(s*c),f=u(i*l),g=u(a*n*d),y=u(o*h),m=u((s+i)*(c+l)-p-f),b=y-g,w=y+g,S=u(f-r*p),_=u(m*b),A=u(w*S),I=u(m*S),k=u(b*w);return new E(_,A,k,I)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,w,e,E.normalizeZ)}multiply(e){const{p:t,f:r}=this.wNAF(m(e,n));return E.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=b(e);return t===fa?_:this.equals(_)||t===ga?this:this.equals(S)?this.wNAF(t).p:A.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(e){const{ex:t,ey:n,ez:s}=this,i=this.is0();null==e&&(e=i?ma:r.inv(s));const o=u(t*e),a=u(n*e),c=u(s*e);if(i)return{x:fa,y:ga};if(c!==ga)throw new Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){const{h:e}=t;return e===ga?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:s,a:i}=t,o=r.BYTES,a=(e=Fo("pointHex",e,o)).slice(),c=e[o-1];a[o-1]=-129&c;const d=Mo(a);d===fa||m(d,n?l:r.ORDER);const p=u(d*d),f=u(p-ga),g=u(s*p-i);let{isValid:y,value:b}=h(f,g);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const w=(b&ga)===ga,v=!!(128&c);if(!n&&b===fa&&v)throw new Error("Point.fromHex: x=0 and x_0=1");return v!==w&&(b=u(-b)),E.fromAffine({x:b,y:d})}static fromPrivateKey(e){return R(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ko(t,r.BYTES);return n[n.length-1]|=e&ga?128:0,n}toHex(){return Bo(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,ga,u(t.Gx*t.Gy)),E.ZERO=new E(fa,ga,ga,fa);const{BASE:S,ZERO:_}=E,A=da(E,8*a);function I(e){return ta(e,n)}function k(e){return I(Mo(e))}function R(e){const t=a;e=Fo("private key",e,t);const r=Fo("hashed private key",i(e),2*t),n=d(r.slice(0,t)),s=r.slice(t,2*t),o=k(n),c=S.multiply(o),l=c.toRawBytes();return{head:n,prefix:s,scalar:o,point:c,pointBytes:l}}function T(e=new Uint8Array,...t){const r=Vo(...t);return k(i(p(r,Fo("context",e),!!s)))}const C=ba;return S._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return R(e).pointBytes},sign:function(e,t,n={}){e=Fo("message",e),s&&(e=s(e));const{prefix:i,scalar:o,pointBytes:c}=R(t),l=T(n.context,i,e),u=S.multiply(l).toRawBytes(),h=I(l+T(n.context,u,c,e)*o);return b(h),Fo("result",Vo(u,Ko(h,r.BYTES)),2*a)},verify:function(e,t,n,i=C){const{context:o,zip215:a}=i,c=r.BYTES;e=Fo("signature",e,2*c),t=Fo("message",t),s&&(t=s(t));const l=Mo(e.slice(c,2*c));let u,h,d;try{u=E.fromHex(n,a),h=E.fromHex(e.slice(0,c),a),d=S.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=T(o,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:{getExtendedPublicKey:R,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=E.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}const va=BigInt(0),Ea=BigInt(1);const Sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Aa=(BigInt(0),BigInt(1)),Ia=BigInt(2),ka=BigInt(5),Ra=BigInt(10),Ta=BigInt(20),Ca=BigInt(40),Pa=BigInt(80);function Ba(e){const t=Sa,r=e*e%t*e%t,n=na(r,Ia,t)*r%t,s=na(n,Aa,t)*e%t,i=na(s,ka,t)*s%t,o=na(i,Ra,t)*i%t,a=na(o,Ta,t)*o%t,c=na(a,Ca,t)*a%t,l=na(c,Pa,t)*c%t,u=na(l,Pa,t)*c%t,h=na(u,Ra,t)*i%t;return{pow_p_5_8:na(h,Ia,t)*e%t,b2:r}}function Da(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Na=aa(Sa,void 0,!0),xa=wa({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Io,randomBytes:cn,adjustScalarBytes:Da,uvRatio:function(e,t){const r=Sa,n=ta(t*t*t,r),s=ta(n*n*t,r);let i=ta(e*n*Ba(e*s).pow_p_5_8,r);const o=ta(t*i*i,r),a=i,c=ta(i*_a,r),l=o===e,u=o===ta(-e,r),h=o===ta(-e*_a,r);return l&&(i=a),(u||h)&&(i=c),(ta(i,r)&Yo)===Yo&&(i=ta(-i,r)),{isValid:l||u,value:i}}});const La=(()=>function(e){const t=(Go(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,s=e=>ta(e,n),i=t.montgomeryBits,o=Math.ceil(i/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>ra(e,n-BigInt(2),n));function u(e,t,r){const n=s(e*(t-r));return[t=s(t-n),r=s(r+n)]}function h(e){if("bigint"==typeof e&&va<=e&&e=va;e--){const t=n>>e&Ea;y^=t,a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1],y=t;const r=c+p,i=s(r*r),l=c-p,h=s(l*l),m=i-h,b=f+g,w=s((f-g)*r),v=s(b*l),E=w+v,S=w-v;f=s(E*E),g=s(o*s(S*S)),c=s(i*h),p=s(m*(i+s(d*m)))}a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1];const m=l(p);return s(c*m)}(r,n);if(f===va)throw new Error("Invalid private or public key received");return p(f)}const g=p(t.Gu);function y(e){return f(e,g)}return{scalarMult:f,scalarMultBase:y,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>y(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}}({P:Sa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Sa,{pow_p_5_8:r,b2:n}=Ba(e);return ta(na(r,BigInt(3),t)*n,t)},adjustScalarBytes:Da,randomBytes:cn}))(),Oa=(Na.ORDER+BigInt(3))/BigInt(8);Na.pow(Ia,Oa),Na.sqrt(Na.neg(Na.ONE)),Na.ORDER,BigInt(5),BigInt(8),BigInt(486662),function(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");const r=e.sqrt(t);e.isOdd(r)&&e.neg(r)}(Na,Na.neg(BigInt(486664))),BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Ma extends sn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Wr(e);const r=rn(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew Ma(e,t).update(r).digest();Ua.create=(e,t)=>new Ma(e,t);const Ka=new Uint8Array([0]),Fa=new Uint8Array;const Va={hashSHA256:e=>gn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Ua(e,rn(r),rn(t))}(gn,t,e),n=function(e,t,r,n=32){if(Wr(e),zr(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/e.outputLen);void 0===r&&(r=Fa);const i=new Uint8Array(s*e.outputLen),o=Ua.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t({publicKey:La.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>La.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>to(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>to(n,t,r).decrypt(e.subarray(),s)},qa=e=>{const t=x(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};qa.bytes=2;const Ha=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)};Ha.bytes=2;class ja extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=ja.code}static code="ERR_UNEXPECTED_PEER"}class $a extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=$a.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}__webpack_require__(2746),__webpack_require__(2698);class za extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=za.code,this.type=za.type}static code="ABORT_ERR";static type="aborted"}class Ga extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class Wa extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}Error,Error,Error;const Ya="ERR_TIMEOUT";var Xa=__webpack_require__(276);function Ja(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 new Error("byte array longer than desired length");r=Jn([new Uint8Array(t-r.length),r])}return An(r,"base64url")}function Qa(e){const t=function(e,t){let r=$t(e,"base64urlpad");return r}(e);return new Xa.jsbn.BigInteger(An(t,"base16"),16)}function Za(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}__webpack_require__(7619),__webpack_require__(3736);const ec=32,tc=64,rc=32;function nc(e,t){const r=new Uint8Array(tc);for(let n=0;nFr(cc)}(ac||(ac={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(lc||(lc={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(uc||(uc={}));class hc{_key;constructor(e){this._key=mc(e,ec)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return lc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class dc{_key;_publicKey;constructor(e,t){this._key=mc(e,tc),this._publicKey=mc(t,ec)}sign(e){return function(e,t){const r=e.subarray(0,rc);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new hc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function pc(e){if(e.length>tc){const t=(e=mc(e,tc+ec)).subarray(0,tc),r=e.subarray(tc,e.length);return new dc(t,r)}const t=(e=mc(e,tc)).subarray(0,tc),r=e.subarray(ec);return new dc(t,r)}function fc(e){return e=mc(e,ec),new hc(e)}async function gc(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:nc(e,t),publicKey:t}}();return new dc(e,t)}async function yc(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==rc)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:nc(t,r),publicKey:r}}(e);return new dc(t,r)}function mc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function bc(e,t){return t.map((t=>Qa(e[t])))}async function wc(e){const t=[await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Ec(e)],r=await vc({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function vc(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([sc.get().subtle.exportKey("jwk",e.privateKey),sc.get().subtle.exportKey("jwk",e.publicKey)])}async function Ec(e){return sc.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 Sc(e,t,r,n){const s=t?function(e){return Xa.pki.setRsaPublicKey(...bc(e,["n","e"]))}(e):function(e){return Xa.pki.setRsaPrivateKey(...bc(e,["n","e","d","p","q","dp","dq","qi"]))}(e);return $t(n(An(r instanceof Uint8Array?r:r.subarray(),"ascii"),s),"ascii")}function _c(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}Object.keys({"P-256":256,"P-384":384,"P-521":521}).join(" / "),__webpack_require__(2313),__webpack_require__(5805);const Ac=8192;class Ic{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return sc.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.publicKeyToAsn1({n:Qa(e.n),e:Qa(e.e)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return lc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Sc(this._key,!0,e,((e,t)=>t.encrypt(e)))}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class kc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(16))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(16)}()}sign(e){return async function(e,t){const r=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await sc.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ic(this._publicKey)}decrypt(e){return Sc(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.privateKeyToAsn1({n:Qa(e.n),e:Qa(e.e),d:Qa(e.d),p:Qa(e.p),q:Qa(e.q),dP:Qa(e.dp),dQ:Qa(e.dq),qInv:Qa(e.qi)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return uc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){const t=new Xa.util.ByteBuffer(this.marshal()),r=Xa.asn1.fromDer(t),n=Xa.pki.privateKeyFromAsn1(r),s={algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"};return Xa.pki.encryptRsaPrivateKey(n,e,s)}if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Rc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e),d:Ja(r.d),p:Ja(r.p),q:Ja(r.q),dp:Ja(r.dP),dq:Ja(r.dQ),qi:Ja(r.qInv),alg:"RS256"}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await wc(t);return new kc(r.privateKey,r.publicKey)}function Tc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e)}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ic(t)}async function Cc(e){if(_c(e)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await wc(e);return new kc(t.privateKey,t.publicKey)}async function Pc(e){if(e>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await sc.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 vc(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new kc(t.privateKey,t.publicKey)}const{Ph:Bc,aT:Dc}=f,Nc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=Nc;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const 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:Bc(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=Nc,r="string"==typeof e?Dc(e):e;Co(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");const{d:s,l:i}=Nc._parseInt(r.subarray(2)),{d:o,l:a}=Nc._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,r=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},n=t(r(e.s)),s=t(r(e.r)),i=n.length/2,o=s.length/2,a=r(i),c=r(o);return`30${r(o+i+4)}02${c}${s}02${a}${n}`}},xc=BigInt(0),Lc=BigInt(1),Oc=(BigInt(2),BigInt(3));function Mc(e){const t=function(e){const t=pa(e);return Go(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,s=r.BYTES+1,i=2*r.BYTES+1;function o(e){return ta(e,n)}function a(e){return sa(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=pa(e);Go(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:s}=t;if(r){if(!n.eql(s,n.ZERO))throw new 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 new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=t.toBytes||((e,t,n)=>{const s=t.toAffine();return Vo(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:n,b:s}=t,i=r.sqr(e),o=r.mul(i,e);return r.add(r.add(o,r.mul(e,n)),s)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&xcr.eql(e,r.ZERO);return s(t)&&s(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(s(Fo("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:n}=this.toAffine();if(!r.isValid(e)||!r.isValid(n))throw new Error("bad point: x or y not FE");const s=r.sqr(n),o=i(e);if(!r.eql(s,o))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:n,pz:s}=this,{px:i,py:o,pz:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,s=r.mul(n,Oc),{px:i,py:o,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),p=r.mul(o,o),f=r.mul(a,a),g=r.mul(i,o);return g=r.add(g,g),u=r.mul(i,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(s,f),l=r.add(c,l),c=r.sub(p,l),l=r.add(p,l),l=r.mul(c,l),c=r.mul(g,c),u=r.mul(s,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),l=r.add(l,d),f=r.mul(o,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){u(e);const{px:n,py:s,pz:i}=this,{px:o,py:a,pz:c}=e;let l=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Oc);let y=r.mul(n,o),m=r.mul(s,a),b=r.mul(i,c),w=r.add(n,s),v=r.add(o,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,i);let E=r.add(o,c);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(s,i),l=r.add(a,c),E=r.mul(E,l),l=r.add(m,b),E=r.sub(E,l),p=r.mul(f,v),l=r.mul(g,b),p=r.add(l,p),l=r.sub(m,p),p=r.add(m,p),d=r.mul(l,p),m=r.add(y,y),m=r.add(m,y),b=r.mul(f,b),v=r.mul(g,v),m=r.add(m,b),b=r.sub(y,b),b=r.mul(f,b),v=r.add(v,b),y=r.mul(m,v),d=r.add(d,y),y=r.mul(E,v),l=r.mul(w,l),l=r.sub(l,y),y=r.mul(w,m),p=r.mul(E,p),p=r.add(p,y),new h(l,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,l,e,(e=>{const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}))}multiplyUnsafe(e){const n=h.ZERO;if(e===xc)return n;if(a(e),e===Lc)return this;const{endo:s}=t;if(!s)return p.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(e),u=n,d=n,f=this;for(;o>xc||l>xc;)o&Lc&&(u=u.add(f)),l&Lc&&(d=d.add(f)),f=f.double(),o>>=Lc,l>>=Lc;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(r.mul(d.px,s.beta),d.py,d.pz),u.add(d)}multiply(e){a(e);let n,s,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(e,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,o.beta),d.py,d.pz),n=l.add(d),s=u.add(f)}else{const{p:e,f:t}=this.wNAF(i);n=e,s=t}return h.normalizeZ([n,s])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,s=(e,t)=>t!==xc&&t!==Lc&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),i=s(this,t).add(s(e,r));return i.is0()?void 0:i}toAffine(e){const{px:t,py:n,pz:s}=this,i=this.is0();null==e&&(e=i?r.ONE:r.inv(s));const o=r.mul(t,e),a=r.mul(n,e),c=r.mul(s,e);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(c,r.ONE))throw new Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Lc)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===Lc?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),n(h,this,e)}toHex(e=!0){return Bo(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const d=t.nBitLength,p=da(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}({...t,toBytes(e,t,n){const s=t.toAffine(),i=r.toBytes(s.x),o=Vo;return n?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,r.toBytes(s.y))},fromBytes(e){const t=e.length,n=e[0],o=e.subarray(1);if(t!==s||2!==n&&3!==n){if(t===i&&4===n)return{x:r.fromBytes(o.subarray(0,r.BYTES)),y:r.fromBytes(o.subarray(r.BYTES,2*r.BYTES))};throw new Error(`Point of length ${t} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const e=Oo(o);if(!(xc<(a=e)&&aBo(Uo(e,t.nByteLength));function p(e){return e>n>>Lc}const f=(e,t,r)=>Oo(e.slice(t,r));class g{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Fo("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Nc.toSig(Fo("DER",e));return new g(t,r)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s,recovery:i}=this,l=w(Fo("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&i?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=o(-l*f),y=o(s*f),m=c.BASE.multiplyAndAddUnsafe(p,g,y);if(!m)throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Lo(this.toDERHex())}toDERHex(){return Nc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Lo(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const y={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=la(t.n);return function(e,t,r=!1){const n=e.length,s=ca(t),i=la(t);if(n<16||n1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);const o=ta(r?Oo(e):Mo(e),t-Yo)+Yo;return r?Ko(o,s):Uo(o,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){const t=To(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===s||n===i:r?n===2*s||n===2*i:e instanceof c}const b=t.bits2int||function(e){const r=Oo(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return o(b(e))},v=qo(t.nBitLength);function E(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(xc<=e&&ee in s)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:y}=s;null==d&&(d=!0),e=Fo("msgHash",e),f&&(e=Fo("prehashed msgHash",i(e)));const m=w(e),v=l(n),_=[E(v),E(m)];if(null!=y&&!1!==y){const e=!0===y?u(r.BYTES):y;_.push(Fo("extraEntropy",e))}const A=Vo(..._),I=m;return{seed:A,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),s=o(n.x);if(s===xc)return;const i=o(r*o(I+s*v));if(i===xc)return;let l=(n.x===s?0:2)|Number(n.y&Lc),u=i;return d&&p(i)&&(u=function(e){return p(e)?o(-e):e}(i),l^=1),new g(s,u,l)}}}(e,n,s),d=t;return $o(d.hash.outputLen,d.nByteLength,d.hmac)(i,u)},verify:function(e,r,n,s=_){const i=e;if(r=Fo("msgHash",r),n=Fo("publicKey",n),"strict"in s)throw new Error("options.strict was renamed to lowS");const{lowS:l,prehash:u}=s;let h,d;try{if("string"==typeof i||To(i))try{h=g.fromDER(i)}catch(e){if(!(e instanceof Nc.Err))throw e;h=g.fromCompact(i)}else{if("object"!=typeof i||"bigint"!=typeof i.r||"bigint"!=typeof i.s)throw new Error("PARSE");{const{r:e,s:t}=i;h=new g(e,t)}}d=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(l&&h.hasHighS())return!1;u&&(r=t.hash(r));const{r:p,s:f}=h,y=w(r),m=a(f),b=o(y*m),v=o(p*m),E=c.BASE.multiplyAndAddUnsafe(d,b,v)?.toAffine();return!!E&&o(E.x)===p},ProjectivePoint:c,Signature:g,utils:y}}function Uc(e){return{hash:e,hmac:(t,...r)=>Ua(e,t,nn(...r)),randomBytes:cn}}BigInt(4);const Kc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Vc=BigInt(1),qc=BigInt(2),Hc=(e,t)=>(e+t/qc)/t;const jc=aa(Kc,void 0,void 0,{sqrt:function(e){const t=Kc,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=na(u,r,t)*u%t,d=na(h,r,t)*u%t,p=na(d,qc,t)*l%t,f=na(p,s,t)*p%t,g=na(f,i,t)*f%t,y=na(g,a,t)*g%t,m=na(y,c,t)*y%t,b=na(m,a,t)*g%t,w=na(b,r,t)*u%t,v=na(w,o,t)*f%t,E=na(v,n,t)*l%t,S=na(E,qc,t);if(!jc.eql(jc.sqr(S),e))throw new Error("Cannot find square root");return S}}),$c=function(e,t){const r=t=>Mc({...e,...Uc(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:jc,n:Fc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Fc,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Vc*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Hc(i*e,t),c=Hc(-n*e,t);let l=ta(e-a*r-c*s,t),u=ta(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},gn);function zc(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),$c.ProjectivePoint;class Gc{_key;constructor(e){zc(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Za(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return lc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}}class Wc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),zc(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Za(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Gc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Yc(e){return new Wc(e)}function Xc(e){return new Gc(e)}async function Jc(){const e=$c.utils.randomPrivateKey();return new Wc(e)}const Qc={rsa:y,ed25519:g,secp256k1:m};function Zc(e){const t=Object.keys(Qc).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const el=Symbol.for("@libp2p/peer-id");function tl(e){return null!=e&&Boolean(e[el])}const rl=Symbol.for("nodejs.util.inspect.custom"),nl=Object.values(Ft).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)),Ft.identity.decoder),sl=114,il=36,ol=37;class al{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()})`}[el]=!0;toString(){return null==this.string&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Lt.createV1(sl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Qn(this.multihash.bytes,e);if("string"==typeof e)return hl(e).equals(this);if(null!=e?.multihash?.bytes)return Qn(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[rl](){return`PeerId(${this.toString()})`}}class cl extends al{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ll extends al{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class ul extends al{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function hl(e,t){if(t=t??nl,"1"===e.charAt(0)||"Q"===e.charAt(0)){const t=_t(Fe.decode(`z${e}`));return e.startsWith("12D")?new ll({multihash:t}):e.startsWith("16U")?new ul({multihash:t}):new cl({multihash:t})}return dl(nl.decode(e))}function dl(e){try{const t=_t(e);if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:t});if(t.digest.length===ol)return new ul({multihash:t})}if(t.code===Pt.code)return new cl({multihash:t})}catch{return function(e){if(null==e||null==e.multihash||null==e.version||1===e.version&&e.code!==sl)throw new Error("Supplied PeerID CID is invalid");const t=e.multihash;if(t.code===Pt.code)return new cl({multihash:e.multihash});if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:e.multihash});if(t.digest.length===ol)return new ul({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}(Lt.decode(e))}throw new Error("Supplied PeerID CID is invalid")}async function pl(e,t){return e.length===il?new ll({multihash:St(kt.code,e),privateKey:t}):e.length===ol?new ul({multihash:St(kt.code,e),privateKey:t}):new cl({multihash:await Pt.digest(e),publicKey:e,privateKey:t})}var fl,gl;async function yl(e,t,r){const n=await async function(e,t){if(null==e.privateKey)throw new Error("PrivateKey was missing from PeerId");return(await async function(e){const t=uc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPrivateKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PrivateKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Zc(t.Type??"RSA")}}(e.privateKey)).sign(t)}(e,wl(t));if(null==e.publicKey)throw new Error("PublicKey was missing from local PeerId");return function(e,t,r){return gl.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}(e.publicKey,n,r)}async function ml(e){return pl(e.identityKey)}function bl(e){return gl.decode(e)}function wl(e){const t=$t("noise-libp2p-static-key:");return e instanceof Uint8Array?Jn([t,e],t.length+e.length):(e.prepend(t),e)}async function vl(e,t,r){const n=await pl(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);const s=wl(e);if(null==n.publicKey)throw new Error("PublicKey was missing from PeerId");if(null==t.identitySig)throw new Error("Signature was missing from message");const i=function(e){const t=lc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPublicKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PublicKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Zc(t.Type??"unknown")}}(n.publicKey);if(!await i.verify(s,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function El(e){return!!(e instanceof Uint8Array||ts(e))&&32===e.byteLength}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(fl||(fl={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),fl.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:N(0),identitySig:N(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=fl.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(gl||(gl={}));class Sl{n;bytes;view;constructor(e=0){this.n=e,this.bytes=N(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 new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}class _l{crypto;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=t}encryptWithAd(e,t,r){const n=this.encrypt(e.k,e.n,t,r);return e.n.increment(),n}decryptWithAd(e,t,r,n){const{plaintext:s,valid:i}=this.decrypt(e.k,e.n,t,r,n);return i&&e.n.increment(),{plaintext:s,valid:i}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return N(32)}isEmptyKey(e){return Qn(this.createEmptyKey(),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,s){t.assertValue();const i=this.crypto.chaCha20Poly1305Decrypt(n,t.getBytes(),r,e,s);return i?{plaintext:i,valid:!0}:{plaintext:N(0),valid:!1}}decryptAndHash(e,t){let r,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{const r=this.crypto.generateX25519SharedKey(e,t);return 32===r.length?r:r.subarray(0,32)}catch(e){const t=e;return this.log.error("error deriving shared key",t),N(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(new rs(e,t))}mixKey(e,t){const[r,n]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(n),e.ck=r}initializeKey(e){return{k:e,n:new Sl}}initializeSymmetric(e){const t=$t(e,"utf-8"),r=this.hashProtocolName(t),n=r,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:n,h:r}}hashProtocolName(e){if(e.length<=32){const t=N(32);return t.set(e),t}return this.getHash(e,N(0))}split(e){const[t,r]=this.crypto.getHKDF(e.ck,N(0));return{cs1:this.initializeKey(t),cs2:this.initializeKey(r)}}writeMessageRegular(e,t){const r=this.encryptWithAd(e,N(0),t);return{ne:this.createEmptyKey(),ns:N(0),ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,N(0),t.ciphertext)}}class Al extends _l{initializeInitiator(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}initializeResponder(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}writeMessageA(e,t,r){const n=N(0);e.e=void 0!==r?r:this.crypto.generateX25519KeyPair();const s=e.e.publicKey;return this.mixHash(e.ss,s),{ne:s,ns:n,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const n=e.s.publicKey,s=this.encryptAndHash(e.ss,n);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.re)),{ne:r,ns:s,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageC(e,t){const r=e.s.publicKey,n=this.encryptAndHash(e.ss,r);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const s=this.encryptAndHash(e.ss,t),i={ne:this.createEmptyKey(),ns:n,ciphertext:s},{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,messageBuffer:i,cs1:o,cs2:a}}readMessageA(e,t){return El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);n&&El(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:n&&i}}readMessageC(e,t){const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);if(n&&El(r)&&(e.rs=r),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:n&&i,cs1:o,cs2:a}}initSession(e,t,r){const n=this.createEmptyKey(),s=N(32);let i;return i=e?this.initializeInitiator(t,r,s,n):this.initializeResponder(t,r,s,n),{hs:i,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){const{h:r,messageBuffer:s,cs1:i,cs2:o}=this.writeMessageC(e.hs,t);n=s,e.h=r,e.cs1=i,e.cs2=o}else{if(!(e.mc>2))throw new Error("Session invalid.");if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");n=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");n=this.writeMessageRegular(e.cs2,t)}}return e.mc++,n}recvMessage(e,t){let r=N(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){const{h:s,plaintext:i,valid:o,cs1:a,cs2:c}=this.readMessageC(e.hs,t);r=i,n=o,e.h=s,e.cs1=a,e.cs2=c}return e.mc++,{plaintext:r,valid:n}}}function Il(e,t){t.enabled&&_i&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${An(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function kl(e,t){t.enabled&&_i&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${An(e.subarray(),"hex")}`)}class Rl{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(e,t,r,n,s,i,o,a,c){this.log=e.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=i,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new Al(e,s),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&&_i&&(t(`LOCAL_STATIC_PUBLIC_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${An(e.privateKey,"hex")}`)),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");const e=this.xx.sendMessage(this.session,N(0));await this.connection.write(function(e){return new rs(e.ne,e.ciphertext)}(e)),this.log.trace("Stage 0 - Initiator finished sending first message."),Il(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");const e=function(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:N(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new $a("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),kl(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");const r=function(e){if(e.length<80)throw new 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:s}=this.xx.recvMessage(this.session,r);if(!s)throw new $a("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),kl(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&_i&&t(`REMOTE_STATIC_PUBLIC_KEY ${An(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{const e=bl(n);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`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.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ne,e.ns,e.ciphertext)}(e)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Il(this.session.hs.e,this.log)}var e,t}async finish(){if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ns,e.ciphertext)}(e)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");const e=function(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:N(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 $a("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{const e=bl(t);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`Error occurred while verifying signed payload: ${e.message}`)}}var e,t;e=this.session,(t=this.log).enabled&&_i&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${An(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${An(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){const r=this.getCS(t);return this.xx.encryptWithAd(r,N(0),e)}decrypt(e,t,r){const n=this.getCS(t,!1);return this.xx.decryptWithAd(n,N(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new $a("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 Tl{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:o}=e;this.components=e,this.crypto=s??Va,this.extensions=n,this.metrics=o?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(o):void 0,this.staticKeys=r?this.crypto.generateX25519KeyPairFromSeed(r):this.crypto.generateX25519KeyPair(),this.prologue=i??N(0)}async secureOutbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!0,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!1,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){const t=await yl(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){const{isInitiator:r,remotePeer:n,connection:s}=e,i=new Rl(this.components,r,t,this.prologue,this.crypto,this.staticKeys,s,n);try{await i.propose(),await i.exchange(),await i.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 i}async createSecureConnection(e,t){const[r,n]=function(){const e=Ei(),t=Ei();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await ys(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i),e.session):e.encrypt(n.sublist(r,i),e.session),t?.encryptedPackets.increment(),yield new rs(qa(s.byteLength),s)}}}(t,this.metrics),s,(e=>ls(e,{lengthDecoder:Ha})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(s=n.length),s-16new Tl(t,e)}const Pl=Symbol.for("@libp2p/peer-discovery"),Bl=45,Dl=15,Nl=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const 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((()=>{const 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 s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;tthis.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]}const 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((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function xl(e){return Boolean(function(e){if(!(e.length>Dl))return Nl.new(e).parseWith((()=>Nl.readIPv4Addr()))}(e))}function Ll(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPv6Addr()))}(e))}function Ol(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPAddr()))}(e))}parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);const Ml=xl,Ul=Ll,Kl=function(e){let t=0;if(e=e.toString().trim(),Ml(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Ul(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n>8&255,s[t++]=255&e}return s}throw new Error("invalid ip address")},Fl=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let s=0;s65536)throw new Error("Port number is not in range(1, 65536)");const s=Yl(n);return Jn([r,s],r.length+s.length)}(t);case 445:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=Ce.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=Yl(n);return Jn([r,s],r.length+s.length)}(t);case 466:return function(e){const t=Wl.decode(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}(t);case 481:return Jl(globalThis.decodeURIComponent(t));default:return $t(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Vl,"ip6zone"],[43,8,"ipcidr"],[53,Vl,"dns",!0],[54,Vl,"dns4",!0],[55,Vl,"dns6",!0],[56,Vl,"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,Vl,"unix",!1,!0],[421,Vl,"ipfs"],[421,Vl,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Vl,"garlic64"],[448,0,"tls"],[449,Vl,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Vl,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Vl,"http-path"],[777,Vl,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(s)}}(...e);Hl[t.code]=t,ql[t.name]=t})),jl("ip4"),jl("ip6"),jl("ipcidr");const Gl=Object.values(Ft).map((e=>e.decoder)),Wl=function(){let e=Gl[0].or(Gl[1]);return Gl.slice(2).forEach((t=>e=e.or(t))),e}();function Yl(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Xl(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Jl(e){const t=$t(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}function Ql(e){const t=W(e);if((e=e.slice(j(t))).length!==t)throw new Error("inconsistent lengths");return An(e)}function Zl(e){const t=[],r=[];let n=null,s=0;for(;se.length)throw su("Invalid address Uint8Array: "+An(e,"base16"));t.push([i,l]);const u=$l(i,l);if(r.push([i,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:eu(r),tuples:t,stringTuples:r,path:n}}function eu(e){const t=[];return e.map((e=>{const r=jl(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),nu(t.join("/"))}function tu(e){return Jn(e.map((e=>{const t=jl(e[0]);let r=Uint8Array.from(G(t.code));return e.length>1&&null!=e[1]&&(r=Jn([r,e[1]])),r})))}function ru(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=W(t instanceof Uint8Array?t:Uint8Array.from(t));return e+j(e)}}function nu(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function su(e){return new Error("Error parsing address: "+e)}const iu=Symbol.for("nodejs.util.inspect.custom"),ou=Symbol.for("@multiformats/js-multiaddr/multiaddr"),au=[jl("dns").code,jl("dns4").code,jl("dns6").code,jl("dnsaddr").code];class cu{bytes;#t;#r;#n;#s;[ou]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=Zl(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw new Error(`multiaddr "${e}" must start with a "/"`);t=function(e){const t=[],r=[];let n=null;const s=(e=nu(e)).split("/").slice(1);if(1===s.length&&""===s[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i=s.length)throw su("invalid address: "+e);if(!0===o.path){n=nu(s.slice(i).join("/")),t.push([o.code,zl(o.code,n)]),r.push([o.code,n]);break}const a=zl(o.code,s[i]);t.push([o.code,a]),r.push([o.code,$l(o.code,a)])}return{string:eu(r),bytes:tu(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!uu(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=Zl(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#s=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";const i=jl("tcp"),o=jl("udp"),a=jl("ip4"),c=jl("ip6"),l=jl("dns6"),u=jl("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(s=`%${d??""}`),au.includes(h)&&(t=i.name,n=443,r=`${d??""}${s}`,e=h===l.code?6:4),h!==i.code&&h!==o.code||(t=jl(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=jl(h).name,r=`${d??""}${s}`,e=h===c.code?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}protos(){return this.#r.map((([e])=>Object.assign({},jl(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>jl(e).name))}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new cu(e),new cu(this.toString()+e.toString())}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new cu(r.slice(0,n))}decapsulateCode(e){const t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new cu(tu(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===ql.p2p.code&&e.push([t,r]),t===ql["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?An(Fe.decode(`z${e}`),"base58btc"):An(Lt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#s}equals(e){return Qn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=lu.get(t.name);if(null==r)throw new Ga(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await r(this,e)).map((e=>hu(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){const t=(e??this).protos();return!(2!==t.length||4!==t[0].code&&41!==t[0].code||6!==t[1].code&&273!==t[1].code)}[iu](){return`Multiaddr(${this.#t})`}}const lu=new Map;function uu(e){return Boolean(e?.[ou])}function hu(e){return new cu(e)}const du=Hu("dns4"),pu=Hu("dns6"),fu=Hu("dnsaddr"),gu=qu(Hu("dns"),fu,du,pu),yu=qu(Hu("ip4"),Hu("ip6")),mu=qu(Vu(yu,Hu("tcp")),Vu(gu,Hu("tcp"))),bu=Vu(yu,Hu("udp")),wu=Vu(bu,Hu("utp")),vu=Vu(bu,Hu("quic")),Eu=Vu(bu,Hu("quic-v1")),Su=qu(Vu(mu,Hu("ws")),Vu(gu,Hu("ws"))),_u=qu(Vu(Su,Hu("p2p")),Su),Au=qu(Vu(mu,Hu("wss")),Vu(gu,Hu("wss")),Vu(mu,Hu("tls"),Hu("ws")),Vu(gu,Hu("tls"),Hu("ws"))),Iu=qu(Vu(Au,Hu("p2p")),Au),ku=qu(Vu(mu,Hu("http")),Vu(yu,Hu("http")),Vu(gu,Hu("http"))),Ru=qu(Vu(mu,Hu("https")),Vu(yu,Hu("https")),Vu(gu,Hu("https"))),Tu=Vu(bu,Hu("webrtc-direct"),Hu("certhash")),Cu=qu(Vu(Tu,Hu("p2p")),Tu),Pu=Vu(Eu,Hu("webtransport"),Hu("certhash"),Hu("certhash")),Bu=qu(Vu(Pu,Hu("p2p")),Pu),Du=qu(Vu(_u,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(Iu,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(_u,Hu("p2p-webrtc-star")),Vu(Iu,Hu("p2p-webrtc-star"))),Nu=(qu(Vu(_u,Hu("p2p-websocket-star"),Hu("p2p")),Vu(Iu,Hu("p2p-websocket-star"),Hu("p2p")),Vu(_u,Hu("p2p-websocket-star")),Vu(Iu,Hu("p2p-websocket-star"))),qu(Vu(ku,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(Ru,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(ku,Hu("p2p-webrtc-direct")),Vu(Ru,Hu("p2p-webrtc-direct")))),xu=qu(Su,Au,ku,Ru,Du,Nu,mu,wu,vu,gu,Cu,Bu),Lu=(qu(Vu(xu,Hu("p2p-stardust"),Hu("p2p")),Vu(xu,Hu("p2p-stardust"))),qu(Vu(xu,Hu("p2p")),Du,Nu,Cu,Bu,Hu("p2p"))),Ou=qu(Vu(Lu,Hu("p2p-circuit"),Lu),Vu(Lu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),Lu),Vu(xu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),xu),Hu("p2p-circuit")),Mu=()=>qu(Vu(Ou,Mu),Ou),Uu=Mu(),Ku=qu(Vu(Uu,Lu,Uu),Vu(Lu,Uu),Vu(Uu,Lu),Uu,Lu);function Fu(e){return function(t){let r;try{r=hu(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Vu(...e){function t(t){if(t.length(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Fu(t),partialMatch:t}}function qu(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Fu(t),partialMatch:t}}function Hu(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=hu(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}qu(Vu(Uu,Hu("webrtc"),Hu("p2p")),Vu(Uu,Hu("webrtc")),Vu(xu,Hu("webrtc"),Hu("p2p")),Vu(xu,Hu("webrtc")),Hu("webrtc"));class ju extends ni{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!Ku.matches(e)){this.log.error("Invalid multiaddr");continue}const t=hu(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:hl(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Pl]=this;[Symbol.toStringTag]="@libp2p/bootstrap";isStarted(){return Boolean(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(const 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}}const $u=Uint8Array.from([3,1]);var zu;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.peerId=t.bytes();break;case 2:n.seq=t.uint64();break;case 3:n.addresses.push(e.AddressInfo.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return n}))),r),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(zu||(zu={}));class Gu{static createFromProtobuf=e=>{const t=zu.decode(e),r=dl(t.peerId),n=(t.addresses??[]).map((e=>hu(e.multiaddr))),s=t.seq;return new Gu({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=$u;peerId;multiaddrs;seqNumber;domain=Gu.DOMAIN;codec=Gu.CODEC;marshaled;constructor(e){const{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=zu.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Gu&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const 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 Wu(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const Yu=32,Xu=64,Ju=32;function Qu(e,t){const r=new Uint8Array(Xu);for(let n=0;nFr(nh)}(rh||(rh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(sh||(sh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(ih||(ih={}));class oh{_key;constructor(e){this._key=dh(e,Yu)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return sh.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class ah{_key;_publicKey;constructor(e,t){this._key=dh(e,Xu),this._publicKey=dh(t,Yu)}sign(e){return function(e,t){const r=e.subarray(0,Ju);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new oh(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function ch(e){if(e.length>Xu){const t=(e=dh(e,Xu+Yu)).subarray(0,Xu),r=e.subarray(Xu,e.length);return new ah(t,r)}const t=(e=dh(e,Xu)).subarray(0,Xu),r=e.subarray(Yu);return new ah(t,r)}function lh(e){return e=dh(e,Yu),new oh(e)}async function uh(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Qu(e,t),publicKey:t}}();return new ah(e,t)}async function hh(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==Ju)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Qu(t,r),publicKey:r}}(e);return new ah(t,r)}function dh(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function ph(e){const t=[await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await gh(e)],r=await fh({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function fh(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Zu.get().subtle.exportKey("jwk",e.privateKey),Zu.get().subtle.exportKey("jwk",e.publicKey)])}async function gh(e){return Zu.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 yh(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}async function mh(e,t,r,n){const{c:s,dkLen:i,asyncTick:o,DK:a,PRF:c,PRFSalt:l}=function(e,t,r,n){Wr(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!==on.call(t))throw new Error("Options should be object or undefined");return Object.assign({dkLen:32,asyncTick:10},t)}(0,n),{c:i,dkLen:o,asyncTick:a}=s;if(zr(i),zr(o),zr(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=rn(t),l=rn(r),u=new Uint8Array(o),h=Ua.create(e,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n);let u;const h=new Uint8Array(4),d=Jr(h),p=new Uint8Array(c.outputLen);for(let e=1,t=0;t{c._cloneInto(u).update(p).digestInto(p);for(let e=0;e=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function vh(e,t,r=-1){const n=r;let s=e,i=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e=0;e--){const r=Math.pow(2,e*t);o[i-e-1]=Math.floor(s/r),s-=o[i-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function Eh(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),s=new Uint8Array(n);for(const t of e)s.set(t,r),r+=t.length;return s}function Sh(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e=s.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=n.subarray(o,o+i);return 0===a[i-1]&&this.warnings.push("Needlessly long encoded length"),this.length=wh(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const n=vh(this.length,8);if(n.byteLength>127)return this.error="Too big length",Bh;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const s=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e=37&&!1===s.idBlock.isHexOnly)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};a=Vh.EndOfContent;break;case 1:a=Vh.Boolean;break;case 2:a=Vh.Integer;break;case 3:a=Vh.BitString;break;case 4:a=Vh.OctetString;break;case 5:a=Vh.Null;break;case 6:a=Vh.ObjectIdentifier;break;case 10:a=Vh.Enumerated;break;case 12:a=Vh.Utf8String;break;case 13:a=Vh.RelativeObjectIdentifier;break;case 14:a=Vh.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:a=Vh.Sequence;break;case 17:a=Vh.Set;break;case 18:a=Vh.NumericString;break;case 19:a=Vh.PrintableString;break;case 20:a=Vh.TeletexString;break;case 21:a=Vh.VideotexString;break;case 22:a=Vh.IA5String;break;case 23:a=Vh.UTCTime;break;case 24:a=Vh.GeneralizedTime;break;case 25:a=Vh.GraphicString;break;case 26:a=Vh.VisibleString;break;case 27:a=Vh.GeneralString;break;case 28:a=Vh.UniversalString;break;case 29:a=Vh.CharacterString;break;case 30:a=Vh.BmpString;break;case 31:a=Vh.DATE;break;case 32:a=Vh.TimeOfDay;break;case 33:a=Vh.DateTime;break;case 34:a=Vh.Duration;break;default:{const e=s.idBlock.isConstructed?new Vh.Constructed:new Vh.Primitive;e.idBlock=s.idBlock,e.lenBlock=s.lenBlock,e.warnings=s.warnings,s=e}}}else a=s.idBlock.isConstructed?Vh.Constructed:Vh.Primitive;return s=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(s,a),o=s.fromBER(e,t,s.lenBlock.isIndefiniteForm?r:s.lenBlock.length),s.valueBeforeDecodeView=e.subarray(n,n+s.blockLength),{offset:o,result:s}}function Rd(e){if(!e.byteLength){const e=new qh({},Uh);return e.error="Input buffer has zero length",{offset:-1,result:e}}return kd(bh._H.toUint8Array(e).slice(),0,e.byteLength)}zh=Id,Vh.Primitive=zh,Id.NAME="PRIMITIVE";class Td extends Uh{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=bh._H.toUint8Array(e);if(!kh(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let s=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=kd(n,s,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Nh)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Nh?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){const r=t||new Rh;for(let t=0;t` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Gh=Cd,Vh.Constructed=Gh,Cd.NAME="CONSTRUCTED";class Pd extends Uh{fromBER(e,t,r){return t}toBER(e){return Bh}}Pd.override="EndOfContentValueBlock";class Bd extends qh{constructor(e={}){super(e,Pd),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Wh=Bd,Vh.EndOfContent=Wh,Bd.NAME=Nh;class Dd extends qh{constructor(e={}){super(e,Uh),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){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Yh=Dd,Vh.Null=Yh,Dd.NAME="NULL";class Nd extends(Oh(Uh)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=bh._H.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){const n=bh._H.toUint8Array(e);return kh(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,Sh.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Nd.NAME="BooleanValueBlock";class xd extends qh{constructor(e={}){super(e,Nd),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}`}}Xh=xd,Vh.Boolean=Xh,xd.NAME="BOOLEAN";class Ld extends(Oh(Td)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,n=Td.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e0&&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}const s=bh._H.toUint8Array(e);if(!kh(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=i.subarray(1);try{if(e.byteLength){const t=kd(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+r}toBER(e,t){if(this.isConstructed)return Td.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Bh;const 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}}}Md.NAME="BitStringValueBlock";class Ud extends qh{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,s;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(s=r.value)||void 0===s?void 0:s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Md),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 Cd.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function Kd(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),s=new Uint8Array(t);let i=n.slice(0);const o=i.length-1,a=s.slice(0),c=a.length-1;let l=0,u=0;for(let e=c=0;e--,u++)l=1==u=i.length?i=Eh(new Uint8Array([l%10]),i):i[o-u]=l%10;return r[0]>0&&(i=Eh(r,i)),i}function Fd(e){if(e>=Th.length)for(let t=Th.length;t<=e;t++){const e=new Uint8Array([0]);let r=Th[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=Eh(e,r)),Th.push(r)}return Th[e]}function Vd(e,t){let r=0;const n=new Uint8Array(e),s=new Uint8Array(t),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=i[o-u]-a[c-u]-r,1==l<0?(r=1,i[o-u]=l+10):(r=0,i[o-u]=l);if(r>0)for(let e=o-c+1;e>=0;e--,u++){if(l=i[o-u]-r,!(l<0)){r=0,i[o-u]=l;break}r=1,i[o-u]=l+10}return i.slice()}Qh=Ud,Vh.BitString=Qh,Ud.NAME=Lh;class qd extends(Oh(Uh)){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=Sh.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){const e=vh(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let s=vh(t,8,n),i=new Uint8Array(s);if(128&i[0]){const e=s.slice(0),t=new Uint8Array(e);s=new ArrayBuffer(s.byteLength+1),i=new Uint8Array(s);for(let r=0;r1&&(n=i.length+1),this.valueHexView=i.subarray(n-i.length)),s}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const 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]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const 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(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),n=0;const s=this.valueHexView;let i="",o=!1;for(let o=s.byteLength-1;o>=0;o--){t=s[o];for(let s=0;s<8;s++)1&~t||(n===e?(r=Vd(Fd(n),r),i="-"):r=Kd(r,Fd(n))),n++,t>>=1}for(let e=0;e0;){const t=new $d;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){const t=[];for(let r=0;rNumber.MAX_SAFE_INTEGER){Ah();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,s=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r0;){const t=new Wd;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){const r=[];for(let t=0;t4)continue;const i=4-s.length;for(let e=s.length-1;e>=0;e--)r[4*n+e+i]=s[e]}this.valueBlock.value=e}}op.NAME="UniversalStringValueBlock";class ap extends op{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}cd=ap,Vh.UniversalString=cd,ap.NAME="UniversalString";class cp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ld=cp,Vh.NumericString=ld,cp.NAME="NumericString";class lp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}ud=lp,Vh.PrintableString=ud,lp.NAME="PrintableString";class up extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}hd=up,Vh.TeletexString=hd,up.NAME="TeletexString";class hp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}dd=hp,Vh.VideotexString=dd,hp.NAME="VideotexString";class dp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}pd=dp,Vh.IA5String=pd,dp.NAME="IA5String";class pp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}fd=pp,Vh.GraphicString=fd,pp.NAME="GraphicString";class fp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}gd=fp,Vh.VisibleString=gd,fp.NAME="VisibleString";class gp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}yd=gp,Vh.GeneralString=yd,gp.NAME="GeneralString";class yp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}md=yp,Vh.CharacterString=md,yp.NAME="CharacterString";class mp extends fp{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=50?1900+r: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){const e=new Array(7);return e[0]=_h(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=_h(this.month,2),e[2]=_h(this.day,2),e[3]=_h(this.hour,2),e[4]=_h(this.minute,2),e[5]=_h(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}}}bd=mp,Vh.UTCTime=bd,mp.NAME="UTCTime";class bp extends mp{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="",s="",i=0,o=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new 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 new Error("Wrong input string for conversion");let s=parseInt(r.substring(0,2),10);if(isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*s,4===r.length){if(s=parseInt(r.substring(2,4),10),isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");a=e*s}}}let c=n.indexOf(".");if(-1===c&&(c=n.indexOf(",")),-1!==c){const e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");i=e.valueOf(),s=n.substring(0,c)}else s=n;switch(!0){case 8===s.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*i;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===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(s);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}Ad=_p,Vh.TIME=Ad,_p.NAME="TIME";const Rp=8192;class Tp{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Zu.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return sh.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class Cp{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Ap(16)}sign(e){return async function(e,t){const r=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Zu.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Tp(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url"))),Hd.fromBigInt(kp($t(e.d,"base64url"))),Hd.fromBigInt(kp($t(e.p,"base64url"))),Hd.fromBigInt(kp($t(e.q,"base64url"))),Hd.fromBigInt(kp($t(e.dp,"base64url"))),Hd.fromBigInt(kp($t(e.dq,"base64url"))),Hd.fromBigInt(kp($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return ih.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Zu.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Ap(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Ap(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Pp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Ip(r[1].toBigInt()),"base64url"),e:An(Ip(r[2].toBigInt()),"base64url"),d:An(Ip(r[3].toBigInt()),"base64url"),p:An(Ip(r[4].toBigInt()),"base64url"),q:An(Ip(r[5].toBigInt()),"base64url"),dp:An(Ip(r[6].toBigInt()),"base64url"),dq:An(Ip(r[7].toBigInt()),"base64url"),qi:An(Ip(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await ph(t);return new Cp(r.privateKey,r.publicKey)}function Bp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Ip(r[0].toBigInt()),"base64url"),e:An(Ip(r[1].toBigInt()),"base64url")}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Tp(t)}async function Dp(e){if(yh(e)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await ph(e);return new Cp(t.privateKey,t.publicKey)}async function Np(e){if(e>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Zu.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 fh(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Cp(t.privateKey,t.publicKey)}function xp(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Lp{_key;constructor(e){xp(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Wu(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return sh.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}}class Op{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),xp(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Wu(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Lp(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Mp(e){return new Op(e)}function Up(e){return new Lp(e)}async function Kp(){const e=$c.utils.randomPrivateKey();return new Op(e)}const Fp={rsa:w,ed25519:b,secp256k1:v};function Vp(e){const t=Object.keys(Fp).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}var qp;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const 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>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(qp||(qp={}));class Hp{static createFromProtobuf=async e=>{const t=qp.decode(e),r=await pl(t.publicKey);return new Hp({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw new Error("Missing private key");const r=e.domain,n=e.codec,s=e.marshal(),i=jp(r,n,s),o=await async function(e){const t=ih.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPrivateKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PrivateKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Vp(t.Type??"RSA")}}(t.privateKey),a=await o.sign(i.subarray());return new Hp({peerId:t,payloadType:n,payload:s,signature:a})};static openAndCertify=async(e,t)=>{const r=await Hp.createFromProtobuf(e);if(!await r.validate(t))throw new Ga("envelope signature is not valid for the given domain","ERR_SIGNATURE_NOT_VALID");return r};peerId;payloadType;payload;signature;marshaled;constructor(e){const{peerId:t,payloadType:r,payload:n,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=qp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Qn(this.marshal(),e.marshal())}async validate(e){const t=jp(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw new Error("Missing public key");return function(e){const t=sh.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPublicKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PublicKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Vp(t.Type??"unknown")}}(this.peerId.publicKey).verify(t.subarray(),this.signature)}}const jp=(e,t,r)=>{const n=$t(e),s=G(n.byteLength),i=G(t.length),o=G(r.length);return new rs(s,n,i,t,o,r)},$p=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),zp=e=>({match:t=>$p((t=>t===e)).match(t),pattern:e}),Gp=()=>({match:e=>$p((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Wp=()=>({match:e=>$p((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),Yp=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{Fe.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Xp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{je.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Jp=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Qp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.lengthe.pattern)).join(", ")})`}),Zp=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function ef(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const tf=Zp(zp("dns4"),Gp()),rf=Zp(zp("dns6"),Gp()),nf=Zp(zp("dnsaddr"),Gp()),sf=Zp(zp("dns"),Gp()),of=(ef(tf),ef(rf),ef(nf),ef(Qp(sf,nf,tf,rf)),Zp(zp("ip4"),$p(xl))),af=Zp(zp("ip6"),$p(Ll)),cf=Qp(of,af),lf=Qp(cf,sf,tf,rf,nf),uf=ef(lf),hf=(ef(of),ef(af),ef(cf),Zp(lf,zp("tcp"),Wp())),df=Zp(lf,zp("udp"),Wp()),pf=(ef(hf),ef(df),Zp(df,zp("quic"))),ff=Zp(df,zp("quic-v1")),gf=Qp(pf,ff),yf=(ef(pf),ef(ff),Qp(lf,hf,df,pf,ff)),mf=Qp(Zp(yf,zp("ws"),Jp(Yp()))),bf=(ef(mf),Qp(Zp(yf,zp("wss"),Jp(Yp())),Zp(yf,zp("tls"),zp("ws"),Jp(Yp())))),wf=(ef(bf),Zp(df,zp("webrtc-direct"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),vf=(ef(wf),Zp(ff,zp("webtransport"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),Ef=(ef(vf),Qp(mf,bf,Zp(hf,Jp(Yp())),Zp(gf,Jp(Yp())),Zp(lf,Jp(Yp())),wf,vf,Yp())),Sf=(ef(Ef),ef(Zp(Ef,zp("p2p-circuit"),Yp())));function _f(e,t){const r=vi(e,t),n={read:async(e,t)=>{const 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}ef(Qp(Zp(Ef,zp("p2p-circuit"),zp("webrtc"),Jp(Yp())),Zp(Ef,zp("webrtc"),Jp(Yp())),zp("webrtc"))),ef(Qp(Zp(lf,zp("tcp"),Wp(),zp("http"),Jp(Yp())),Zp(lf,zp("http"),Jp(Yp())))),ef(Qp(Zp(lf,zp("tcp"),Qp(Zp(zp("443"),zp("http")),Zp(Wp(),zp("https"))),Jp(Yp())),Zp(lf,zp("tls"),zp("http"),Jp(Yp())),Zp(lf,zp("https"),Jp(Yp()))));var Af=__webpack_require__(4866);const If="object"==typeof window&&"object"==typeof document&&9===document.nodeType,kf=Af(),Rf=If&&!kf,Tf=kf&&!If,Cf=kf&&If,Pf=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!kf,Bf="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Df=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product);var Nf;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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(const 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(const 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)=>{const r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Nf||(Nf={}));const xf=8192,Lf="ipfs";class Of{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??Lf}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Lf}/id/push/1.0.0`,this.timeout=t.timeout??6e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxPushIncomingStreams=t.maxPushIncomingStreams??1,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??1,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnTransientConnection=t.runOnTransientConnection??true,this.host={protocolVersion:`${t.protocolPrefix??Lf}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??true)&&e.events.addEventListener("connection:open",(e=>{const 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}`&&(Pf||Tf?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Rf||Bf||Cf||Df)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:$t(this.host.agentVersion),ProtocolVersion:$t(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){const t=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code))),r=new Gu({peerId:this.peerId,multiaddrs:t}),n=await Hp.seal(r,this.peerId),s=this.registrar.getProtocols(),i=await this.peerStore.get(this.peerId),o=An(i.metadata.get("AgentVersion")??$t(this.host.agentVersion)),a=An(i.metadata.get("ProtocolVersion")??$t(this.host.protocolVersion)),c=e.map((async e=>{let r;const i=AbortSignal.timeout(this.timeout);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:i,runOnTransientConnection:this.runOnTransientConnection});const c=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf);await c.write({listenAddrs:t.map((e=>e.bytes)),signedPeerRecord:n.marshal(),protocols:s,agentVersion:o,protocolVersion:a},{signal:i}),await r.close({signal:i})}catch(e){this.log.error("could not push identify update to peer",e),r?.abort(e)}}));await Promise.all(c)}async push(){if(!this.isStarted())return;const e=[];await Promise.all(this.connectionManager.getConnections().map((async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).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){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});const n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),s=await n.read(t);return await r.close(t),s}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Ga("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const o=await pl(n);if(!e.remotePeer.equals(o))throw new Ga("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new Ga("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return hu(e)}catch{}}(i);return this.log("identify completed for peer %p and protocols %o",o,s),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.#i(e,r)}async _handleIdentify(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=this.peerId.publicKey??new Uint8Array(0),s=await this.peerStore.get(this.peerId),i=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code)));let o=s.peerRecordEnvelope;if(i.length>0&&null==o){const e=new Gu({peerId:this.peerId,multiaddrs:i});o=(await Hp.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;uf.matches(t.remoteAddr)||(a=void 0);const c=_f(r).pb(Nf);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:o,observedAddr:a,protocols:s.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){const{connection:t,stream:r}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const e={signal:AbortSignal.timeout(this.timeout)},n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),s=await n.read(e);await r.close(e),await this.#i(t,s)}catch(e){return this.log.error("received invalid message",e),void r.abort(e)}this.log("handled push from %p",t.remotePeer)}async#i(e,t){if(this.log("received identify from %p",e.remotePeer),null==t)throw new Ga("message was null or undefined","ERR_INVALID_MESSAGE");const r={};if(t.listenAddrs.length>0&&(r.addresses=t.listenAddrs.map((e=>({isCertified:!1,multiaddr:hu(e)})))),t.protocols.length>0&&(r.protocols=t.protocols),null!=t.publicKey&&(r.publicKey=t.publicKey,!(await pl(t.publicKey)).equals(e.remotePeer)))throw new Ga("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let n;if(null!=t.signedPeerRecord){this.log("received signedPeerRecord from %p",e.remotePeer);let s=t.signedPeerRecord;const i=await Hp.openAndCertify(s,Gu.DOMAIN);let o,a=Gu.createFromProtobuf(i.payload);if(!a.peerId.equals(i.peerId))throw new Ga("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new Ga("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{o=await this.peerStore.get(a.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=o&&(r.metadata=o.metadata,null!=o.peerRecordEnvelope)){const e=await Hp.createFromProtobuf(o.peerRecordEnvelope),t=Gu.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=o.peerRecordEnvelope)}r.peerRecordEnvelope=s,r.addresses=a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),n={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,r),await this.peerStore.patch(e.remotePeer,r),null!=t.agentVersion||null!=t.protocolVersion){const r={};null!=t.agentVersion&&(r.AgentVersion=$t(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=$t(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,r),await this.peerStore.merge(e.remotePeer,{metadata:r})}const s={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map((e=>hu(e))),observedAddr:null==t.observedAddr?void 0:hu(t.observedAddr),protocols:t.protocols,signedPeerRecord:n,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:s}),s}}function Mf(e={}){return t=>new Of(t,e)}function Uf(e,t){const 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 new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Kf=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Ff=new WeakMap,Vf=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Kf());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Kf())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),Ff.set(u,(()=>{c(i),i=null,o()})),u}}();class qf{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 Hf}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Ga("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const 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 null!=e?.customDuration&&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 Hf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var jf;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(jf||(jf={}));const $f=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),zf=Object.freeze({NEW_STREAM:jf.NEW_STREAM,MESSAGE:jf.MESSAGE_INITIATOR,CLOSE:jf.CLOSE_INITIATOR,RESET:jf.RESET_INITIATOR}),Gf=Object.freeze({MESSAGE:jf.MESSAGE_RECEIVER,CLOSE:jf.CLOSE_RECEIVER,RESET:jf.RESET_RECEIVER}),Wf=1<<20;class Yf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Wf,t=4194304){this._buffer=new rs,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(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const 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}const{id:e,type:r,length:n,offset:s}=this._headerInfo;if(this._buffer.length-sthis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:i,offset:r+s,length:n}}}const Xf=128,Jf=127;function Qf(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&Jf)<=Xf);return{value:n,offset:t=i-t}}const Zf=10240,eg=new class{_pool;_poolOffset;constructor(){this._pool=x(Zf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;G(e.id<<3|e.type,r,n),n+=j(e.id<<3|e.type),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data?(G(0,r,n),n+=j(0)):(G(e.data.length,r,n),n+=j(e.data.length));const s=r.subarray(this._poolOffset,n);Zf-n<100?(this._pool=x(Zf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function tg(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class rg{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=us(),this.closed=us(),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=fs({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 Ga(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);tg(e)&&await e}const r=()=>{Uf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new rs(r):r;const e=this.sendData(r,t);tg(e)&&(this.sendingData=us(),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 gi(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);const 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 gi(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await gi(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await gi(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");const t=this.sendReset();tg(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;const e=new Ga("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(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class ng extends rg{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?zf:Gf,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:zf.NEW_STREAM,data:new rs($t(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const 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 sg(e){const t={...e,type:`${$f[e.type]} (${e.type})`};return e.type===jf.NEW_STREAM&&(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class ig{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=fs({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=ys(this._source,(e=>async function*(e){for await(const t of e){const e=new rs;eg.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new qf({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const 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){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Ga("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=Wf}=e;return new ng({id:"initiator"===i?`i${t}`:`r${t}`,streamId:t,name:`${null==r?t:r}`,direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,sg(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Uf(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Yf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const 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)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",sg(e)),e.type===jf.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:jf.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(new Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:An(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,$f[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case jf.MESSAGE_INITIATOR:case jf.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===jf.MESSAGE_INITIATOR?jf.RESET_RECEIVER:jf.RESET_INITIATOR}),new Ga("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case jf.CLOSE_INITIATOR:case jf.CLOSE_RECEIVER:n.remoteCloseWrite();break;case jf.RESET_INITIATOR:case jf.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class og{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new ig(this.components,{...e,...this._init})}}function ag(e={}){return t=>new og(t,e)}const cg="ERR_WRONG_PING_ACK";class lg{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);const{stream:t}=e,r=Date.now();ys(t,t).catch((t=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,t)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=function(e){if(isNaN(32))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(32)}(),s=await this.components.connectionManager.openConnection(e,t);let i,o=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),o=()=>{i?.abort(new Ga("ping timeout",Ya))},t.signal?.addEventListener("abort",o,{once:!0});const e=await ys([n],i,(async e=>function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e)return t})();for(const t of e)return t}(e))),a=Date.now()-r;if(null==e)throw new Ga(`Did not receive a ping ack after ${a}ms`,cg);if(!Qn(n,e.subarray()))throw new Ga(`Received wrong ping ack after ${a}ms`,cg);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),i?.abort(e),e}finally{t.signal?.removeEventListener("abort",o),null!=i&&await i.close()}}}function ug(e={}){return t=>new lg(t,e)}const hg=Symbol.for("@libp2p/transport");var dg;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(dg||(dg={}));const pg=[jl("tcp").code,jl("dns").code,jl("dnsaddr").code,jl("dns4").code,jl("dns6").code];function fg(e){let t;try{t=jl("sni").code}catch(e){return null}for(const[r,n]of e)if(r===t&&void 0!==n)return n;return null}function gg(e){return e.some((([e,t])=>e===jl("tls").code))}function yg(e,t,r){const n=mg[jl(e).name];if(void 0===n)throw new Error(`Can't interpret protocol ${jl(e).name}`);const s=n(t,r);return e===jl("ip6").code?`[${s}]`:s}const mg={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`tcp://${yg(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`udp://${yg(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)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`https://${n}`;const s=r?"https://":"http://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return yg(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return yg(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=yg(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`wss://${n}`;const s=r?"wss://":"ws://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=yg(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-webrtc-direct`}},bg=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",i)}))},wg=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await bg(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{const t=Object.assign(new Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))});var vg=__webpack_require__(544);function Eg(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Sg=WebSocket,_g={"http:":"ws:","https:":"wss:"};function Ag(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(_g))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new vg.PP((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=$t(e.data)),Eg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Eg(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:wg(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:s,socket:e}})(new Sg(r.toString(),t.websocket),t)}const Ig=421,kg=290;function Rg(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return Iu.matches(t)}))}class Tg{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[hg]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s={log:n,async sink(t){try{await e.sink(async function*(){for await(const 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={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const i=()=>{const{host:e,port:t}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Ga("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",i);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",i),s.timeline.close=Date.now()}},abort(t){const{host:r,port:i}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,i,t),e.destroy(),s.timeline.close=Date.now()}};return e.socket.addEventListener("close",(()=>{null==s.timeline.close&&(s.timeline.close=Date.now())}),{once:!0}),s}(await this._connect(e,t),e,{logger:this.logger});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){if(!0===t?.signal?.aborted)throw new za;const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=us(),s=Ag(function(e,t){const r=hu(e).stringTuples(),n=r.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");const s=jl(n[0]),i=mg[s.name];if(null==i)throw new Error(`No interpreter found for ${s.name}`);let o=i(n[1]??"",r);return pg.includes(n[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===n[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}(e),this.init);if(s.socket.addEventListener("error",(()=>{const t=new Ga(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),n.reject(t)})),null==t.signal)return await Promise.race([s.connected(),n.promise]),this.log("connected %s",e),s;let i;const o=new Promise(((e,r)=>{i=()=>{r(new za),s.close().catch((e=>{this.log.error("error closing raw socket",e)}))},!0!==t?.signal?.aborted?t?.signal?.addEventListener("abort",i):i()}));try{await Promise.race([o,n.promise,s.connected()])}finally{null!=i&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}(this.logger,this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Rf||Bf?Rg(e):function(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return _u.matches(t)||Iu.matches(t)}))}(e)}dialFilter(e){return this.listenFilter(e)}}function Cg(e={}){return t=>new Tg(t,e)}const Pg="StrictSign",Bg="StrictNoSign";var Dg;!function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"}(Dg||(Dg={}));const Ng="/floodsub/1.0.0",xg="/meshsub/1.0.0",Lg="/meshsub/1.1.0",Og=5e3,Mg={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var Ug,Kg,Fg,Vg,qg,Hg,jg,$g,zg,Gg,Wg,Yg;!function(e){let t,r,n,s,i,o,a,c,l;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.SubOpts||(e.SubOpts={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={topic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(r=e.Message||(e.Message={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.ihave)for(const n of t.ihave)r.uint32(10),e.ControlIHave.codec().encode(n,r);if(null!=t.iwant)for(const n of t.iwant)r.uint32(18),e.ControlIWant.codec().encode(n,r);if(null!=t.graft)for(const n of t.graft)r.uint32(26),e.ControlGraft.codec().encode(n,r);if(null!=t.prune)for(const n of t.prune)r.uint32(34),e.ControlPrune.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={ihave:[],iwant:[],graft:[],prune:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:if(null!=n.limits?.ihave&&s.ihave.length===n.limits.ihave)throw new qr('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");s.ihave.push(e.ControlIHave.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.iwant&&s.iwant.length===n.limits.iwant)throw new qr('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");s.iwant.push(e.ControlIWant.codec().decode(t,t.uint32()));break;case 3:if(null!=n.limits?.graft&&s.graft.length===n.limits.graft)throw new qr('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");s.graft.push(e.ControlGraft.codec().decode(t,t.uint32()));break;case 4:if(null!=n.limits?.prune&&s.prune.length===n.limits.prune)throw new qr('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");s.prune.push(e.ControlPrune.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(n=e.ControlMessage||(e.ControlMessage={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(18),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.topicID=e.string();break;case 2:if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(s=e.ControlIHave||(e.ControlIHave={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes())}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(i=e.ControlIWant||(e.ControlIWant={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.topicID=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(o=e.ControlGraft||(e.ControlGraft={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.topicID&&(r.uint32(10),r.string(t.topicID)),null!=t.peers)for(const n of t.peers)r.uint32(18),e.PeerInfo.codec().encode(n,r);null!=t.backoff&&(r.uint32(24),r.uint64Number(t.backoff)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peers:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.topicID=t.string();break;case 2:if(null!=n.limits?.peers&&s.peers.length===n.limits.peers)throw new qr('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");s.peers.push(e.PeerInfo.codec().decode(t,t.uint32()));break;case 3:s.backoff=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(a=e.ControlPrune||(e.ControlPrune={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.peerID=e.bytes();break;case 2:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(c=e.PeerInfo||(e.PeerInfo={})),e.codec=()=>(null==l&&(l=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscriptions)for(const n of t.subscriptions)r.uint32(10),e.SubOpts.codec().encode(n,r);if(null!=t.messages)for(const n of t.messages)r.uint32(18),e.Message.codec().encode(n,r);null!=t.control&&(r.uint32(26),e.ControlMessage.codec().encode(t.control,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscriptions:[],messages:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:if(null!=n.limits?.subscriptions&&s.subscriptions.length===n.limits.subscriptions)throw new qr('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");s.subscriptions.push(e.SubOpts.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.messages&&s.messages.length===n.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");s.messages.push(e.Message.codec().decode(t,t.uint32()));break;case 3:s.control=e.ControlMessage.codec().decode(t,t.uint32());break;default:t.skipType(7&r)}}return s}))),l),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ug||(Ug={}));class Xg{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let e=0;e{const 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){const t=this.msgs.get(e);if(null==t)return null;t.validated||this.notValidatedCount--;const{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach((e=>{const 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){const t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function Jg(e){switch(e){case Dg.Ignore:return Vg.Ignore;case Dg.Reject:return Vg.Reject;default:throw new Error("Unreachable")}}!function(e){e.StrictSign="StrictSign",e.StrictNoSign="StrictNoSign"}(Kg||(Kg={})),function(e){e[e.Signing=0]="Signing",e[e.Anonymous=1]="Anonymous"}(Fg||(Fg={})),function(e){e.Error="error",e.Ignore="ignore",e.Reject="reject",e.Blacklisted="blacklisted"}(Vg||(Vg={})),function(e){e.InvalidSignature="invalid_signature",e.InvalidSeqno="invalid_seqno",e.InvalidPeerId="invalid_peerid",e.SignaturePresent="signature_present",e.SeqnoPresent="seqno_present",e.FromPresent="from_present",e.TransformFailed="transform_failed"}(qg||(qg={})),function(e){e.duplicate="duplicate",e.invalid="invalid",e.valid="valid"}(Hg||(Hg={})),function(e){e.forward="forward",e.publish="publish"}(jg||(jg={})),function(e){e.Fanout="fanout",e.Random="random",e.Subscribed="subscribed",e.Outbound="outbound",e.NotEnough="not_enough",e.Opportunistic="opportunistic"}($g||($g={})),function(e){e.Dc="disconnected",e.BadScore="bad_score",e.Prune="prune",e.Excess="excess"}(zg||(zg={})),function(e){e.GraftBackoff="graft_backoff",e.BrokenPromise="broken_promise",e.MessageDeficit="message_deficit",e.IPColocation="IP_colocation"}(Gg||(Gg={})),function(e){e.LowScore="low_score",e.MaxIhave="max_ihave",e.MaxIasked="max_iasked"}(Wg||(Wg={})),function(e){e.graylist="graylist",e.publish="publish",e.gossip="gossip",e.mesh="mesh"}(Yg||(Yg={}));const Qg="ERR_INVALID_PEER_SCORE_PARAMS",Zg={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},ey={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};function ty(e={}){return{...Zg,...e,topics:null!=e.topics?Object.entries(e.topics).reduce(((e,[t,r])=>(e[t]=function(e={}){return{...ey,...e}}(r),e)),{}):{}}}function ry(e){if(e.topicWeight<0)throw new Ga("invalid topic weight; must be >= 0",Qg);if(0===e.timeInMeshQuantum)throw new Ga("invalid TimeInMeshQuantum; must be non zero",Qg);if(e.timeInMeshWeight<0)throw new Ga("invalid TimeInMeshWeight; must be positive (or 0 to disable)",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new Ga("invalid TimeInMeshQuantum; must be positive",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new Ga("invalid TimeInMeshCap; must be positive",Qg);if(e.firstMessageDeliveriesWeight<0)throw new Ga("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",Qg);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new Ga("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new Ga("invalid FirstMessageDeliveriesCap; must be positive",Qg);if(e.meshMessageDeliveriesWeight>0)throw new Ga("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new Ga("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new Ga("invalid MeshMessageDeliveriesCap; must be positive",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new Ga("invalid MeshMessageDeliveriesThreshold; must be positive",Qg);if(e.meshMessageDeliveriesWindow<0)throw new Ga("invalid MeshMessageDeliveriesWindow; must be non-negative",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new Ga("invalid MeshMessageDeliveriesActivation; must be at least 1s",Qg);if(e.meshFailurePenaltyWeight>0)throw new Ga("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new Ga("invalid MeshFailurePenaltyDecay; must be between 0 and 1",Qg);if(e.invalidMessageDeliveriesWeight>0)throw new Ga("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new Ga("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",Qg)}const ny={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function sy(e={}){return{...ny,...e}}function iy(e,t,r=(()=>!0)){const n=new Set;if(t<=0)return n;for(const s of e){if(n.size>=t)break;r(s)&&(n.add(s),e.delete(s))}return n}class oy 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 ay(e,t,r,n){let s=0;Object.entries(t.topics).forEach((([e,t])=>{const n=r.topics[e];if(void 0===n)return;let i=0;if(t.inMesh){let e=t.meshTime/n.timeInMeshQuantum;e>n.timeInMeshCap&&(e=n.timeInMeshCap),i+=e*n.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>n.firstMessageDeliveriesCap&&(o=n.firstMessageDeliveriesCap),i+=o*n.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&s>r.topicScoreCap&&(s=r.topicScoreCap);const i=r.appSpecificScore(e);if(s+=i*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),i=null!=t?t.size:0;if(i>r.IPColocationFactorThreshold){const e=i-r.IPColocationFactorThreshold;s+=e*e*r.IPColocationFactorWeight}})),t.behaviourPenalty>r.behaviourPenaltyThreshold){const e=t.behaviourPenalty-r.behaviourPenaltyThreshold;s+=e*e*r.behaviourPenaltyWeight}return s}var cy,ly=__webpack_require__(2153);!function(e){e[e.unknown=0]="unknown",e[e.valid=1]="valid",e[e.invalid=2]="invalid",e[e.ignored=3]="ignored"}(cy||(cy={}));class uy{records;queue;constructor(){this.records=new Map,this.queue=new ly}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:cy.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);const r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){const e=Date.now();let t=this.queue.peekFront();for(;null!=t&&t.expirenew Set));scoreCache=new Map;deliveryRecords=new uy;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,function(e){for(const[t,r]of Object.entries(e.topics))try{ry(r)}catch(e){throw new Ga(`invalid score parameters for topic ${t}: ${e.message}`,Qg)}if(e.topicScoreCap<0)throw new Ga("invalid topic score cap; must be positive (or 0 for no cap)",Qg);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new Ga("missing application specific score function",Qg);if(e.IPColocationFactorWeight>0)throw new Ga("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",Qg);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new Ga("invalid IPColocationFactorThreshold; must be at least 1",Qg);if(e.behaviourPenaltyWeight>0)throw new Ga("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new Ga("invalid BehaviourPenaltyDecay; must be between 0 and 1",Qg);if(e.decayInterval<1e3)throw new Ga("invalid DecayInterval; must be at least 1s",Qg);if(e.decayToZero<=0||e.decayToZero>=1)throw new Ga("invalid DecayToZero; must be between 0 and 1",Qg)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??ay,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){null==this._backgroundInterval?(this._backgroundInterval=setInterval((()=>{this.background()}),this.params.decayInterval),this.log("started")):this.log("Peer score already running")}stop(){null!=this._backgroundInterval?(clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")):this.log("Peer score already stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map((([e,t])=>[e,t])))}messageFirstSeenTimestampMs(e){const t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){const e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach(((r,n)=>{r.connected?(Object.entries(r.topics).forEach((([r,n])=>{const s=this.params.topics[r];void 0!==s&&(n.firstMessageDeliveries*=s.firstMessageDeliveriesDecay,n.firstMessageDeliveriess.meshMessageDeliveriesActivation&&(n.meshMessageDeliveriesActive=!0)))})),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenaltyr.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n))}))}score(e){this.metrics?.scoreFnCalls.inc();const t=this.peerStats.get(e);if(null==t)return 0;const r=Date.now(),n=this.scoreCache.get(e);if(null!=n&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();const s=this.computeScore(e,t,this.params,this.peerIPs),i=r+this.scoreCacheValidityMs;return null!=n?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-n.score)),n.score=s,n.cacheUntil=i):this.scoreCache.set(e,{score:s,cacheUntil:i}),s}addPenalty(e,t,r){const n=this.peerStats.get(e);null!=n&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){const t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.delete(t);const n=this.peerIPs.get(t);null!=n&&(n.delete(e),0===n.size&&this.peerIPs.delete(t))}removePeer(e){const t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0)return this.removeIPsForPeer(e,t.knownIPs),void this.peerStats.delete(e);Object.entries(t.topics).forEach((([e,t])=>{t.firstMessageDeliveries=0;const r=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries{t!==e.toString()&&this.markDuplicateMessageDelivery(t,r)}))):this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-n.firstSeenTsMs,cy[n.status])}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Vg.Error:return void this.markInvalidMessageDelivery(e,r);case Vg.Blacklisted:return}const s=this.deliveryRecords.ensureRecord(t);if(s.status===cy.unknown){if(n===Vg.Ignore)return s.status=cy.ignored,void s.peers.clear();s.status=cy.invalid,this.markInvalidMessageDelivery(e,r),s.peers.forEach((e=>{this.markInvalidMessageDelivery(e,r)})),s.peers.clear()}else this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeenTsMs,cy[s.status])}duplicateMessage(e,t,r){const n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case cy.unknown:n.peers.add(e);break;case cy.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case cy.invalid:this.markInvalidMessageDelivery(e,r);case cy.ignored:}}markInvalidMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const 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){const n=this.peerStats.get(e);if(null!=n){const e=void 0!==r?Date.now():0,s=this.getPtopicStats(n,t);if(null!=s&&s.inMesh){const n=this.params.topics[t];if(void 0!==r){const s=e-r,i=s>n.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,s,i),i)return}const i=n.meshMessageDeliveriesCap;s.meshMessageDeliveries=Math.min(i,s.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(const r of t){const 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}}function dy(e,t,r,n,s){let i=0;const o=new Map;if(Object.entries(t.topics).forEach((([e,t])=>{const n=s.get(e)??"unknown",a=r.topics[e];if(void 0===a)return;let c=o.get(n);null==c&&(c={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(n,c));let l=0,u=0,h=0,d=0,p=0;t.inMesh&&(l+=Math.max(t.meshTime/a.timeInMeshQuantum,a.timeInMeshCap)*a.timeInMeshWeight);let f=t.firstMessageDeliveries;if(f>a.firstMessageDeliveriesCap&&(f=a.firstMessageDeliveriesCap),u+=f*a.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&i>r.topicScoreCap){i=r.topicScoreCap;const e=r.topicScoreCap/i;for(const t of o.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let a=0,c=0,l=0;return a+=r.appSpecificScore(e)*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),s=null!=t?t.size:0;if(s>r.IPColocationFactorThreshold){const e=s-r.IPColocationFactorThreshold;c+=e*e*r.IPColocationFactorWeight}})),l+=t.behaviourPenalty*t.behaviourPenalty*r.behaviourPenaltyWeight,i+=a+c+l,{byTopic:o,p5w:a,p6w:c,p7w:l,score:i}}class py{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=fs(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),ys(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(is.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 fy{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=ys(this.rawStream,(e=>ls(e,t)))}async close(){this.closeController.abort()}}class gy{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){const r=t[Math.floor(Math.random()*t.length)],n=this.msgIdToStrFn(r);let s=this.promises.get(n);null==s&&(s=new Map,this.promises.set(n,s));const i=Date.now();s.has(e)||(s.set(e,i+this.gossipsubIWantFollowupMs),null!=this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(n)||this.requestMsByMsg.set(n,i)))}getBrokenPromises(){const e=Date.now(),t=new Map;let r=0;return this.promises.forEach(((n,s)=>{n.forEach(((s,i)=>{sFr(ky)}(Iy||(Iy={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ry||(Ry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ty||(Ty={}));class Cy{_key;constructor(e){this._key=Ly(e,by)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Ry.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class Py{_key;_publicKey;constructor(e,t){this._key=Ly(e,wy),this._publicKey=Ly(t,by)}sign(e){return function(e,t){const r=e.subarray(0,vy);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function By(e){if(e.length>wy){const t=(e=Ly(e,wy+by)).subarray(0,wy),r=e.subarray(wy,e.length);return new Py(t,r)}const t=(e=Ly(e,wy)).subarray(0,wy),r=e.subarray(by);return new Py(t,r)}function Dy(e){return e=Ly(e,by),new Cy(e)}async function Ny(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Ey(e,t),publicKey:t}}();return new Py(e,t)}async function xy(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vy)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Ey(t,r),publicKey:r}}(e);return new Py(t,r)}function Ly(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Oy(e){const t=[await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Uy(e)],r=await My({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function My(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sy.get().subtle.exportKey("jwk",e.privateKey),Sy.get().subtle.exportKey("jwk",e.publicKey)])}async function Uy(e){return Sy.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 Ky(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fy(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const qy=8192;class Hy{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sy.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ry.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yy(16)}sign(e){return async function(e,t){const r=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sy.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Hy(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url"))),Hd.fromBigInt(Vy($t(e.d,"base64url"))),Hd.fromBigInt(Vy($t(e.p,"base64url"))),Hd.fromBigInt(Vy($t(e.q,"base64url"))),Hd.fromBigInt(Vy($t(e.dp,"base64url"))),Hd.fromBigInt(Vy($t(e.dq,"base64url"))),Hd.fromBigInt(Vy($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ty.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sy.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=yy(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=yy(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function $y(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Fy(r[1].toBigInt()),"base64url"),e:An(Fy(r[2].toBigInt()),"base64url"),d:An(Fy(r[3].toBigInt()),"base64url"),p:An(Fy(r[4].toBigInt()),"base64url"),q:An(Fy(r[5].toBigInt()),"base64url"),dp:An(Fy(r[6].toBigInt()),"base64url"),dq:An(Fy(r[7].toBigInt()),"base64url"),qi:An(Fy(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Oy(t);return new jy(r.privateKey,r.publicKey)}function zy(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Fy(r[0].toBigInt()),"base64url"),e:An(Fy(r[1].toBigInt()),"base64url")}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Hy(t)}async function Gy(e){if(Ky(e)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Oy(e);return new jy(t.privateKey,t.publicKey)}async function Wy(e){if(e>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sy.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 My(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new jy(t.privateKey,t.publicKey)}function Yy(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Xy{_key;constructor(e){Yy(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(my(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Ry.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}}class Jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Yy(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(my(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Xy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Qy(e){return new Jy(e)}function Zy(e){return new Xy(e)}async function em(){const e=$c.utils.randomPrivateKey();return new Jy(e)}const tm={rsa:S,ed25519:E,secp256k1:_};function rm(e){const t=Object.keys(tm).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function nm(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return tm[e];throw rm(e)}function sm(e){const t=Ry.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPublicKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PublicKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw rm(t.Type??"unknown")}}const im=$t("libp2p-pubsub:");function om(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 am(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function cm(e){return An(e,"base64")}function lm(e){if(e.length<=1)return e;for(let t=0;t{const r=$t(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})(e.from.toBytes(),e.sequenceNumber)}async function hm(e){return Pt.encode(e.data)}var dm,pm;!function(e){e[e.ip4=4]="ip4",e[e.ip6=41]="ip6"}(dm||(dm={}));class fm{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(){const e=Date.now();for(const[t,r]of this.entries.entries()){if(!(r.validUntilMs=Date.now()?t.value:void 0}clear(){this.entries.clear()}}!function(e){e[e.started=0]="started",e[e.stopped=1]="stopped"}(pm||(pm={}));class gm extends ni{globalSignaturePolicy;multicodecs=[Lg,xg];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=fs({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=Lg;opts;decodeRpcLimits;metrics;status={code:pm.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();const 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:ty(t.scoreParams),scoreThresholds:sy(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Mg,this.globalSignaturePolicy=r.globalSignaturePolicy??Pg,r.fallbackToFloodsub&&this.multicodecs.push(Ng),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 fm({validityMs:r.seenTTL}),this.publishedMessageIds=new fm({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Pg:this.msgIdFn=um;break;case Bg:this.msgIdFn=hm;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new fm({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??cm,this.mcache=t.messageCache??new Xg(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");const e=Math.max(...Object.values(r.scoreParams.topics).map((e=>e.meshMessageDeliveriesWindow)),1e3),n=function(e,t,r){return{protocolsEnabled:e.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:e.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:e.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:e.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:e.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:e.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:e.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:e.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:e.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:e.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:e.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:e.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:e.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:e.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:e.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:e.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:e.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:e.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:e.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:e.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:e.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:e.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:e.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:e.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:e.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:e.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:e.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:e.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:e.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:e.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:e.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:e.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:e.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:e.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:e.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:e.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:e.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:e.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:e.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:e.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:e.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:e.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:e.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:e.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:e.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:e.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:e.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:e.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:e.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:e.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:e.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:e.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:e.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:e.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*r.maxMeshMessageDeliveriesWindowSec,.5*r.maxMeshMessageDeliveriesWindowSec,Number(r.maxMeshMessageDeliveriesWindowSec),2*r.maxMeshMessageDeliveriesWindowSec,4*r.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:e.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:e.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:e.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:e.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:e.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:e.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:e.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:e.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:e.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:e.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:e.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*r.behaviourPenaltyThreshold,.5*r.behaviourPenaltyThreshold,Number(r.behaviourPenaltyThreshold),2*r.behaviourPenaltyThreshold,4*r.behaviourPenaltyThreshold]}),ihaveRcvIgnored:e.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:e.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:e.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:e.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:e.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:e.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:e.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:e.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:e.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:e.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:e.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:e.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*r.gossipPromiseExpireSec,Number(r.gossipPromiseExpireSec),2*r.gossipPromiseExpireSec,4*r.gossipPromiseExpireSec]}),iwantPromiseUntracked:e.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:e.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:e.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:e.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:e.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:e.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:e.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:t,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){const n=this.toTopic(e);switch(t){case $g.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case $g.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case $g.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case $g.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case $g.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case $g.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:n},r);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:n},r)}},onRemoveFromMesh(e,t,r){const n=this.toTopic(e);switch(t){case zg.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case zg.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case zg.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case zg.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){const r=this.toTopic(e.message.topic);switch(t){case Dg.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case Dg.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case Dg.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){const n=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:n},t),this.ihaveRcvNotSeenMsgids.inc({topic:n},r)},onIwantRcv(e,t){for(const[t,r]of e){const e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},r)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){const r=this.toTopic(e);this.msgForwardCount.inc({topic:r},1),this.msgForwardPeers.inc({topic:r},t)},onPublishMsg(e,t,r,n,s){const i=this.toTopic(e);this.msgPublishCount.inc({topic:i},1),this.msgPublishBytes.inc({topic:i},r*n),this.msgPublishPeersByTopic.inc({topic:i},r),this.directPeersPublishedTotal.inc({topic:i},t.direct),this.floodsubPeersPublishedTotal.inc({topic:i},t.floodsub),this.meshPeersPublishedTotal.inc({topic:i},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:i},t.fanout),this.msgPublishTime.observe({topic:i},s/1e3)},onMsgRecvPreValidation(e){const t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){const t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){const r=this.toTopic(e);switch(t){case Hg.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case Hg.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case Hg.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){const r=this.toTopic(e),n=t.reason===Vg.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:n},1),this.msgReceivedInvalidByTopic.inc({topic:r},1)},onDuplicateMsgDelivery(e,t,r){const n=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:n},t/1e3),r&&this.duplicateMsgLateDelivery.inc({topic:n},1)},onPublishDuplicateMsg(e){const 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){const t=e.control.ihave?.length??0,r=e.control.iwant?.length??0,n=e.control.graft?.length??0,s=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),r>0&&this.rpcSentIWant.inc(r),n>0&&this.rpcSentGraft.inc(n),s>0&&this.rpcSentPrune.inc(s),(t>0||r>0||n>0||s>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let r=0,n=0,s=0,i=0;for(const o of e)o>=t.graylistThreshold&&r++,o>=t.publishThreshold&&n++,o>=t.gossipThreshold&&s++,o>=0&&i++;this.peersByScoreThreshold.set({threshold:Yg.graylist},r),this.peersByScoreThreshold.set({threshold:Yg.publish},n),this.peersByScoreThreshold.set({threshold:Yg.gossip},s),this.peersByScoreThreshold.set({threshold:Yg.mesh},i),this.score.set(e)},registerScoreWeights(e){for(const[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){const r=new Map;e.forEach(((e,t)=>{const n=this.topicStrToLabel.get(t)??"unknown";let s=r.get(n);null==s&&(s=new Set,r.set(n,s)),e.forEach((e=>s?.add(e)))}));for(const[e,n]of r){const r=[];n.forEach((e=>{r.push(t.get(e)??0)})),this.scorePerMesh.set({topic:e},r)}}}}(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3});n.mcacheSize.addCollect((()=>{this.onScrapeMetrics(n)}));for(const e of this.multicodecs)n.protocolsEnabled.set({protocol:e},1);this.metrics=n}else this.metrics=null;this.gossipTracer=new gy(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new hy(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=>hl(e)))}isStarted(){return this.status.code===pm.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await async function(e,t){switch(e){case Pg:{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");const e=await async function(e){const t=Ty.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPrivateKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PrivateKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw rm(t.Type??"RSA")}}(t.privateKey);return{type:Fg.Signing,author:t,key:t.publicKey,privateKey:e}}case Bg:return{type:Fg.Anonymous};default:throw new Error(`Unknown signature policy "${e}"`)}}(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=fs({objectMode:!0}),ys(this.outboundInflightQueue,(async e=>{for await(const{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})})));const 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}))));const 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:pm.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!==pm.started)return;const{registrarTopologyIds:e}=this.status;this.status={code:pm.stopped};const t=this.components.registrar;await Promise.all(this.multicodecs.map((async e=>t.unhandle(e)))),e.forEach((e=>{t.unregister(e)})),this.outboundInflightQueue.end();const r=[];for(const e of this.streamsOutbound.values())r.push(e.close());this.streamsOutbound.clear();for(const e of 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;const 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;const r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{const n=new py(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);const s=n.protocol;s===Ng&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:s},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;const r=e.toString();if(!this.peers.has(r))return;const 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);const s=new fy(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,s),this.pipePeerReadStream(e,s.source).catch((e=>{this.log(e)}))}addPeer(e,t,r){const n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.add(n),this.score.addPeer(n);const s=function(e){for(const t of e.tuples())switch(t[0]){case dm.ip4:case dm.ip6:return $l(t[0],t[1])}return null}(r);null!==s?this.score.addIP(n,s):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){const t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);const r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);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);for(const e of this.topics.values())e.delete(t);for(const[e,r]of this.mesh)r.delete(t)&&this.metrics?.onRemoveFromMesh(e,zg.Dc,1);for(const 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===pm.started}getMeshPeers(e){const t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){const t=this.topics.get(e);return(null!=t?Array.from(t):[]).map((e=>hl(e)))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ys(t,(async t=>{for await(const r of t)try{const t=r.subarray(),n=Ug.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()))return this.log("received message from unacceptable peer %p",e),void this.metrics?.rpcRecvNotAccepted.inc();const r=null!=t.subscriptions?t.subscriptions.length:0,n=null!=t.messages?t.messages.length:0;let s=0,i=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(s=t.control.ihave.length),null!=t.control.iwant&&(i=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 ${s} iwant ${i} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){const r=[];t.subscriptions.forEach((t=>{const n=t.topic,s=!0===t.subscribe;if(null!=n){if(null!=this.allowedTopics&&!this.allowedTopics.has(n))return;this.handleReceivedSubscription(e,n,s),r.push({topic:n,subscribe:s})}})),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:r}})}for(const r of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(r.topic))continue;const 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);const r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);const n=r.code;switch(n){case Hg.duplicate:return this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),void this.mcache.observeDuplicate(r.msgIdStr,e.toString());case Hg.invalid:if(null!=r.msgIdStr){const 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);return void this.metrics?.onMsgRecvInvalid(t.topic,r);case Hg.valid: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)&&(this.components.peerId.equals(e)&&!this.opts.emitSelf||(super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new ii("message",{detail:r.msg})))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){const r=this.fastMsgIdFn?.(t),n=void 0!==r?this.fastMsgIdCache?.get(r):void 0;if(null!=n)return{code:Hg.duplicate,msgIdStr:n};const s=await async function(e,t){switch(e){case Bg:return null!=t.signature?{valid:!1,error:qg.SignaturePresent}:null!=t.seqno?{valid:!1,error:qg.SeqnoPresent}:null!=t.key?{valid:!1,error:qg.FromPresent}:{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case Pg:{if(null==t.seqno)return{valid:!1,error:qg.InvalidSeqno};if(8!==t.seqno.length)return{valid:!1,error:qg.InvalidSeqno};if(null==t.signature)return{valid:!1,error:qg.InvalidSignature};if(null==t.from)return{valid:!1,error:qg.InvalidPeerId};let e,s;try{e=dl(t.from)}catch(e){return{valid:!1,error:qg.InvalidPeerId}}if(null!=t.key){if(s=sm(t.key),void 0!==e.publicKey&&!Qn(s.bytes,e.publicKey))return{valid:!1,error:qg.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:qg.InvalidPeerId};s=sm(e.publicKey)}const i={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},o=Jn([im,Ug.Message.encode(i)]);return await s.verify(o,t.signature)?{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${An(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??(r=s,nm(n=(n??"rsa").toLowerCase()),r.bytes)}}:{valid:!1,error:qg.InvalidSignature}}default:throw new Error("Unreachable")}var r,n}(this.globalSignaturePolicy,t);if(!s.valid)return{code:Hg.invalid,reason:Vg.Error,error:s.error};const i=s.message;try{null!=this.dataTransform&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:Hg.invalid,reason:Vg.Error,error:qg.TransformFailed}}const o=await this.msgIdFn(i),a=this.msgIdToStrFn(o),c={msgId:o,msgIdStr:a};if(void 0!==r&&null!=this.fastMsgIdCache&&this.fastMsgIdCache.put(r,a)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(a))return{code:Hg.duplicate,msgIdStr:a};this.seenCache.put(a);const l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,i)}catch(e){const r=e.code;"ERR_TOPIC_VALIDATOR_IGNORE"===r&&(t=Dg.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===r?Dg.Reject:Dg.Ignore}if(t!==Dg.Accept)return{code:Hg.invalid,reason:Jg(t),msgIdStr:a}}return{code:Hg.valid,messageId:c,msg:i}}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;const r=null!=t.ihave?this.handleIHave(e,t.ihave):[],n=null!=t.iwant?this.handleIWant(e,t.iwant):[],s=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===s.length)return;const i=this.sendRpc(e,om(n,{iwant:r,prune:s})),o=r[0]?.messageIDs;null!=o&&(i?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;const t=Date.now(),r=this.acceptFromWhitelist.get(e);if(null!=r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;const 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[];const r=this.score.score(e);if(r10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIhave}),[];const s=this.iasked.get(e)??0;if(s>=Og)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIasked}),[];const i=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=>{const t=this.msgIdToStrFn(e);this.seenCache.has(t)||(i.set(t,e),r++)})),this.metrics?.onIhaveRcv(e,t.length,r)})),0===i.size)return[];let o=i.size;o+s>Og&&(o=Og-s),this.log("IHAVE: Asking for %d out of %d messages from %s",o,i.size,e);let a=Array.from(i.values());return lm(a),a=a.slice(0,o),this.iasked.set(e,s+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];const r=this.score.score(e);if(r{t?.forEach((t=>{const r=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(r,e);null!=o?(s.set(o.msg.topic,1+(s.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):n.set(r,o.msg)):i++}))})),this.metrics?.onIwantRcv(s,i),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){const r=[],n=this.score.score(e),s=Date.now();let i=this.opts.doPX;return t.forEach((({topicID:t})=>{if(null==t)return;const o=this.mesh.get(t);if(null==o)return void(i=!1);if(o.has(e))return;if(this.direct.has(e))return this.log("GRAFT: ignoring request from direct peer %s",e),r.push(t),void(i=!1);const a=this.backoff.get(t)?.get(e);if("number"==typeof a&&s=this.opts.Dhi&&!this.outbound.get(e)?(r.push(t),void this.addBackoff(e,t)):(this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),void this.metrics?.onAddToMesh(t,$g.Subscribed,1))})),0===r.length?[]:Promise.all(r.map((async t=>this.makePrune(e,t,i,!1))))}async handlePrune(e,t){const r=this.score.score(e);for(const{topicID:n,backoff:s,peers:i}of t){if(null==n)continue;const 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,zg.Prune,1)),"number"==typeof s&&s>0?this.doAddBackoff(e,n,1e3*s):this.addBackoff(e,n),null!=i&&i.length>0){if(r{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Gg.BrokenPromise)}))}clearBackoff(){if(this.heartbeatTicks%15!=0)return;const e=Date.now();this.backoff.forEach(((t,r)=>{t.forEach(((r,n)=>{r+1*this.opts.heartbeatInterval{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&&(lm(e),e=e.slice(0,this.opts.prunePeers));const t=[];await Promise.all(e.map((async e=>{if(null==e.peerID)return;const r=dl(e.peerID),n=r.toString();if(!this.peers.has(n))if(null!=e.signedPeerRecord)try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,r))return void this.log("bogus peer record obtained through px: could not add peer record to address book");t.push(n)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}else t.push(n)}))),0!==t.length&&await Promise.all(t.map((async e=>this.connect(e))))}async connect(e){this.log("Initiating connection with %s",e);const t=hl(e),r=await this.components.connectionManager.openConnection(t);for(const e of this.multicodecs)for(const n of this.components.registrar.getTopologies(e))n.onConnect?.(t,r)}subscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub is not started");const t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==pm.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);const 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,$g.Fanout,t.size)),t.size!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e)))).forEach((e=>{t.add(e)})),this.metrics?.onAddToMesh(e,$g.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!==pm.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);const 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){const n=new Set,s=this.topics.get(e);null!=s&&(this.direct.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&n.add(e)})),this.floodsubPeers.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&n.add(e)})));const i=this.mesh.get(e);return null!=i&&i.size>0&&i.forEach((e=>{t===e||r?.has(e)||n.add(e)})),n}selectPeersToPublish(e){const 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++)}));const s=this.mesh.get(e);if(null!=s&&s.size>0)s.forEach((e=>{t.add(e),r.mesh++}));else{const n=this.fanout.get(e);if(null!=n&&n.size>0)n.forEach((e=>{t.add(e),r.fanout++}));else{const 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);const s=this.selectPeersToForward(t.topic,r,n);s.forEach((e=>{this.sendRpc(e,om([t]))})),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,r){const n=Date.now(),s=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");const{raw:i,msg:o}=await async function(e,t,r,n){switch(e.type){case Fg.Signing:{const s={from:e.author.toBytes(),data:n,seqno:yy(8),topic:t,signature:void 0,key:void 0},i=Jn([im,Ug.Message.encode(s)]);return s.signature=await e.privateKey.sign(i),s.key=e.key,{raw:s,msg:{type:"signed",from:e.author,data:r,sequenceNumber:BigInt(`0x${An(s.seqno,"base16")}`),topic:t,signature:s.signature,key:s.key}}}case Fg.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 new Error("Unreachable")}}(this.publishConfig,e,t,s),a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),l=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(l)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}const{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(c),this.mcache.put({msgId:a,msgIdStr:c},i,!0),this.publishedMessageIds.put(c);const f=r?.batchPublish??this.opts.batchPublish,g=om([i]);if(f)this.sendRpcInBatch(u,g);else for(const e of u)this.sendRpc(e,g)||u.delete(e);const y=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=i.data?i.data.length:0,y),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:o}})),super.dispatchEvent(new ii("message",{detail:o}))),{recipients:Array.from(u.values()).map((e=>hl(e)))}}sendRpcInBatch(e,t){const r=Ug.encode(t),n=is.single(r);for(const s of e){const i=this.streamsOutbound.get(s);if(null!=i){try{i.pushPrefixed(n)}catch(t){e.delete(s),this.log.error(`Cannot send rpc to ${s}`,t)}this.metrics?.onRpcSent(t,r.length)}else this.log(`Cannot send RPC to ${s} as there is no open stream to it available`),e.delete(s)}}reportMessageValidationResult(e,t,r){let n;if(r===Dg.Accept){if(n=this.mcache.validate(e),null!=n){const{message:r,originatingPeers:s}=n;this.score.deliverMessage(t,e,r.topic),this.forwardMessage(e,n.message,t,s)}}else if(n=this.mcache.remove(e),null!=n){const s=Jg(r),{message:i,originatingPeers:o}=n;this.score.rejectMessage(t,e,i.topic,s);for(const t of o)this.score.rejectMessage(t,e,i.topic,s)}const s=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,s)}sendGraft(e,t){const r=om([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){const r=om([],{prune:[await this.makePrune(e,t,this.opts.doPX,!0)]});this.sendRpc(e,r)}sendRpc(e,t){const 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;const n=this.control.get(e);null!=n&&(this.piggybackControl(e,t,n),this.control.delete(e));const s=this.gossip.get(e);null!=s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));const i=Ug.encode(t);try{r.push(i)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=n&&this.control.set(e,n),null!=s&&this.gossip.set(e,s),!1}return this.metrics?.onRpcSent(t,i.length),!0}piggybackControl(e,t,r){const n=am(t);for(const t of r.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&n.control.graft.push(t);for(const t of r.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||n.control.prune.push(t)}piggybackGossip(e,t,r){am(t).control.ihave=r}async sendGraftPrune(e,t,r){const n=this.opts.doPX,s=!1;for(const[i,o]of e){const e=o.map((e=>({topicID:e})));let a=[];const c=t.get(i);null!=c&&(a=await Promise.all(c.map((async e=>this.makePrune(i,e,n&&!r.get(i),s)))),t.delete(i)),this.sendRpc(i,om([],{graft:e,prune:a}))}for(const[e,i]of t){const t=await Promise.all(i.map((async t=>this.makePrune(e,t,n&&!r.get(e),s))));this.sendRpc(e,om([],{prune:t}))}}emitGossip(e){const t=this.mcache.getGossipIDs(new Set(e.keys()));for(const[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(0===r.length)return;if(lm(r),r.length>Og&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),0===t.size)return;let n=this.opts.Dlazy;const s=.25*t.size;let i=t;s>n&&(n=s),n>i.size?n=i.size:i=lm(Array.from(i)).slice(0,n),i.forEach((t=>{let n=r;r.length>Og&&(n=lm(n.slice()).slice(0,Og)),this.pushGossip(t,{topicID:e,messageIDs:n})}))}flush(){for(const[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,om([],{ihave:t}));for(const[e,t]of this.control.entries()){this.control.delete(e);const r=om([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);const 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===xg)return{topicID:t,peers:[]};const s=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=s/1e3;if(this.doAddBackoff(e,t,s),!r)return{topicID:t,peers:[],backoff:i};const 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=>{const t=hl(e);let r;try{r=await this.components.peerStore.get(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:t.toBytes(),signedPeerRecord:r?.peerRecordEnvelope}})));return{topicID:t,peers:a,backoff:i}}runHeartbeat=()=>{const e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch((e=>{this.log("Error running heartbeat",e)})).finally((()=>{if(null!=e&&e(),this.status.code===pm.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(){const{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:s,fanoutTTL:i}=this.opts;this.heartbeatTicks++;const o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},c=new Map,l=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();const h=new Map;this.mesh.forEach(((i,o)=>{const d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){const e=lm(Array.from(d)),t=this.backoff.get(o);for(const r of e){const e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!i.has(r)&&!this.direct.has(r)){const e=a(r);(null==t||!t.has(r))&&e>=0&&p.add(r),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(r)}}}const g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),i.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);const r=l.get(e);null==r?l.set(e,[o]):r.push(o)},y=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),i.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);const r=c.get(e);null==r?c.set(e,[o]):r.push(o)};if(i.forEach((e=>{const t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,zg.BadScore),u.set(e,!0))})),i.size!0))).forEach((e=>{y(e,$g.NotEnough)}))}var m,b;if(i.size>r){let t=Array.from(i);t.sort(((e,t)=>a(t)-a(e))),t=t.slice(0,n).concat(lm(t.slice(n)));let r=0;if(t.slice(0,e).forEach((e=>{this.outbound.get(e)&&r++})),r{const r=t[e];for(let r=e;r>0;r--)t[r]=t[r-1];t[0]=r};if(r>0){let s=r;for(let r=1;r0;r++)this.outbound.get(t[r])&&(n(r),s--)}let s=e-r;for(let r=e;r0;r++)this.outbound.get(t[r])&&(n(r),s--)}t.slice(e).forEach((e=>{g(e,zg.Excess)}))}if(i.size>=t){let e=0;i.forEach((t=>{this.outbound.get(t)&&e++})),e!0===this.outbound.get(e))).forEach((e=>{y(e,$g.Outbound)}))}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&i.size>1){const e=Array.from(i).sort(((e,t)=>a(e)-a(t))),t=Math.floor(i.size/2),r=a(e[t]);if(ra(e)>r));for(const t of e)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",t,o),y(t,$g.Opportunistic)}}}));const d=Date.now();this.fanoutLastpub.forEach(((e,t)=>{e+i{const n=this.topics.get(r);t.forEach((e=>{(!n?.has(e)||a(e)=this.opts.scoreThresholds.publishThreshold&&i.push(r),e>=this.opts.scoreThresholds.gossipThreshold&&o.add(r)}}}if(t.size{t.add(e),o?.delete(e)}))}})),this.emitGossip(h),await this.sendGraftPrune(c,l,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new ii("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=(()=>!0)){const n=this.topics.get(e);if(null==n)return new Set;let s=[];return n.forEach((e=>{const t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&r(e)&&s.push(e)})),s=lm(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}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;const r=Date.now();e.connectedPeersBackoffSec.reset();for(const n of this.backoff.values()){t+=n.size;for(const[t,s]of n.entries())this.peers.has(t)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);for(const[t,r]of this.topics)e.topicPeersCount.set({topicStr:t},r.size);for(const[t,r]of this.mesh)e.meshPeerCounts.set({topicStr:t},r.size);const n=[],s=new Map;e.behaviourPenalty.reset();for(const t of this.peers.keys()){const r=this.score.score(t);n.push(r),s.set(t,r),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,s);const i=function(e,t,r,n,s){const i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(const o of e){const e=t.get(o);if(null!=e){const t=dy(o,e,r,n,s);for(const[e,r]of t.byTopic){let t=i.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.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)}i.p5w.push(t.p5w),i.p6w.push(t.p6w),i.p7w.push(t.p7w),i.score.push(t.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(i)}}const ym=["/vac/waku/relay/2.0.0"];function mm(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}new qn("relay"),new qn("relay"),ym[0];const bm=32,wm=64,vm=32;function Em(e,t){const r=new Uint8Array(wm);for(let n=0;nFr(km)}(Im||(Im={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Rm||(Rm={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Tm||(Tm={}));class Cm{_key;constructor(e){this._key=Lm(e,bm)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Rm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class Pm{_key;_publicKey;constructor(e,t){this._key=Lm(e,wm),this._publicKey=Lm(t,bm)}sign(e){return function(e,t){const r=e.subarray(0,vm);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Bm(e){if(e.length>wm){const t=(e=Lm(e,wm+bm)).subarray(0,wm),r=e.subarray(wm,e.length);return new Pm(t,r)}const t=(e=Lm(e,wm)).subarray(0,wm),r=e.subarray(bm);return new Pm(t,r)}function Dm(e){return e=Lm(e,bm),new Cm(e)}async function Nm(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Em(e,t),publicKey:t}}();return new Pm(e,t)}async function xm(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vm)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Em(t,r),publicKey:r}}(e);return new Pm(t,r)}function Lm(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Om(e){const t=[await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Um(e)],r=await Mm({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Mm(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sm.get().subtle.exportKey("jwk",e.privateKey),Sm.get().subtle.exportKey("jwk",e.publicKey)])}async function Um(e){return Sm.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 Km(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fm(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Vm(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const Hm=8192;class jm{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sm.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Rm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class $m{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Fm(16)}sign(e){return async function(e,t){const r=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sm.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new jm(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url"))),Hd.fromBigInt(qm($t(e.d,"base64url"))),Hd.fromBigInt(qm($t(e.p,"base64url"))),Hd.fromBigInt(qm($t(e.q,"base64url"))),Hd.fromBigInt(qm($t(e.dp,"base64url"))),Hd.fromBigInt(qm($t(e.dq,"base64url"))),Hd.fromBigInt(qm($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Tm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sm.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Fm(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Fm(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function zm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Vm(r[1].toBigInt()),"base64url"),e:An(Vm(r[2].toBigInt()),"base64url"),d:An(Vm(r[3].toBigInt()),"base64url"),p:An(Vm(r[4].toBigInt()),"base64url"),q:An(Vm(r[5].toBigInt()),"base64url"),dp:An(Vm(r[6].toBigInt()),"base64url"),dq:An(Vm(r[7].toBigInt()),"base64url"),qi:An(Vm(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Om(t);return new $m(r.privateKey,r.publicKey)}function Gm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Vm(r[0].toBigInt()),"base64url"),e:An(Vm(r[1].toBigInt()),"base64url")}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new jm(t)}async function Wm(e){if(Km(e)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Om(e);return new $m(t.privateKey,t.publicKey)}async function Ym(e){if(e>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sm.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 Mm(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new $m(t.privateKey,t.publicKey)}function Xm(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Jm{_key;constructor(e){Xm(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(mm(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Rm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}}class Qm{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Xm(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(mm(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Jm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Zm(e){return new Qm(e)}function eb(e){return new Jm(e)}async function tb(){const e=$c.utils.randomPrivateKey();return new Qm(e)}const rb={rsa:I,ed25519:A,secp256k1:k};function nb(e){const t=Object.keys(rb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const sb=Symbol.for("@libp2p/content-routing"),ib=Symbol.for("@libp2p/peer-routing");function ob(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Fn.enabled(`${e}:trace`)&&null!=Fn.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Fn(`${e}:trace`)),Object.assign(Fn(e),{error:Fn(`${e}:error`),trace:t})}(e)}}function ab(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}Fn.formatters.b=e=>null==e?"undefined":Fe.baseEncode(e),Fn.formatters.t=e=>null==e?"undefined":Ce.baseEncode(e),Fn.formatters.m=e=>null==e?"undefined":qe.baseEncode(e),Fn.formatters.p=e=>null==e?"undefined":e.toString(),Fn.formatters.c=e=>null==e?"undefined":e.toString(),Fn.formatters.k=e=>null==e?"undefined":e.toString(),Fn.formatters.a=e=>null==e?"undefined":e.toString();class cb{set;constructor(e){if(this.set=new Set,null!=e)for(const 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 ab(this.set.entries(),(e=>{const t=hl(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=hl(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return ab(this.set.values(),(e=>hl(e)))}intersection(e){const t=new cb;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new cb;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new cb;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}function lb(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const ub=32,hb=64,db=32;function pb(e,t){const r=new Uint8Array(hb);for(let n=0;nFr(bb)}(mb||(mb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(wb||(wb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(vb||(vb={}));class Eb{_key;constructor(e){this._key=Rb(e,ub)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return wb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Sb{_key;_publicKey;constructor(e,t){this._key=Rb(e,hb),this._publicKey=Rb(t,ub)}sign(e){return function(e,t){const r=e.subarray(0,db);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Eb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function _b(e){if(e.length>hb){const t=(e=Rb(e,hb+ub)).subarray(0,hb),r=e.subarray(hb,e.length);return new Sb(t,r)}const t=(e=Rb(e,hb)).subarray(0,hb),r=e.subarray(ub);return new Sb(t,r)}function Ab(e){return e=Rb(e,ub),new Eb(e)}async function Ib(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:pb(e,t),publicKey:t}}();return new Sb(e,t)}async function kb(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==db)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:pb(t,r),publicKey:r}}(e);return new Sb(t,r)}function Rb(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Tb(e){const t=[await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Pb(e)],r=await Cb({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Cb(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([fb.get().subtle.exportKey("jwk",e.privateKey),fb.get().subtle.exportKey("jwk",e.publicKey)])}async function Pb(e){return fb.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 Bb(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Db(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Nb(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const Lb=8192;class Ob{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return fb.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return wb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Mb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Db(16)}sign(e){return async function(e,t){const r=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await fb.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ob(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url"))),Hd.fromBigInt(xb($t(e.d,"base64url"))),Hd.fromBigInt(xb($t(e.p,"base64url"))),Hd.fromBigInt(xb($t(e.q,"base64url"))),Hd.fromBigInt(xb($t(e.dp,"base64url"))),Hd.fromBigInt(xb($t(e.dq,"base64url"))),Hd.fromBigInt(xb($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return vb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=fb.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Db(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Db(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Ub(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Nb(r[1].toBigInt()),"base64url"),e:An(Nb(r[2].toBigInt()),"base64url"),d:An(Nb(r[3].toBigInt()),"base64url"),p:An(Nb(r[4].toBigInt()),"base64url"),q:An(Nb(r[5].toBigInt()),"base64url"),dp:An(Nb(r[6].toBigInt()),"base64url"),dq:An(Nb(r[7].toBigInt()),"base64url"),qi:An(Nb(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Tb(t);return new Mb(r.privateKey,r.publicKey)}function Kb(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Nb(r[0].toBigInt()),"base64url"),e:An(Nb(r[1].toBigInt()),"base64url")}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ob(t)}async function Fb(e){if(Bb(e)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Tb(e);return new Mb(t.privateKey,t.publicKey)}async function Vb(e){if(e>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await fb.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 Cb(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Mb(t.privateKey,t.publicKey)}function qb(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Hb{_key;constructor(e){qb(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(lb(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return wb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}}class jb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),qb(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(lb(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Hb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function $b(e){return new jb(e)}function zb(e){return new Hb(e)}async function Gb(){const e=$c.utils.randomPrivateKey();return new jb(e)}const Wb={rsa:T,ed25519:R,secp256k1:C};function Yb(e){const t=Object.keys(Wb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Xb(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return Wb[e];throw Yb(e)}function Jb(e,t){return Xb(t=(t??"rsa").toLowerCase()),e.bytes}const Qb=async()=>{const e=await async function(e,t){return Xb("Ed25519").generateKeyPair(2048)}(),t=await Zb(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function Zb(e){return pl(Jb(e.public),(t=e,Xb(r=(r??"rsa").toLowerCase()),t.bytes));var t,r}async function ew(e){return async function(e,t,r){if(null!=t)return Zb(await async function(e){const t=vb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPrivateKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PrivateKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Yb(t.Type??"RSA")}}(t));if(null!=r)return async function(e){return pl(Jb(e))}(function(e){const t=wb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPublicKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PublicKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Yb(t.Type??"unknown")}}(r));return dl(e)}($t(e.id,"base58btc"),null!=e.privKey?$t(e.privKey,"base64pad"):void 0,null!=e.pubKey?$t(e.pubKey,"base64pad"):void 0)}class tw{map;constructor(e){if(this.map=new Map,null!=e)for(const[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 ab(this.map.entries(),(e=>[hl(e[0]),e[1]]))}forEach(e){this.map.forEach(((t,r)=>{e(t,hl(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 ab(this.map.keys(),(e=>hl(e)))}values(){return this.map.values()}get size(){return this.map.size}}var rw=__webpack_require__(228);class nw{#o=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority)return void this.#o.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const r=Math.trunc(s/2);let o=n+r;i=e[o],t.priority-i.priority<=0?(n=++o,s-=r+1):s=r}var i;return n}(this.#o,r);this.#o.splice(n,0,r)}dequeue(){const 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 sw extends rw{#a;#c;#l=0;#u;#h;#d=0;#p;#f;#o;#g;#y=0;#m;#b;#w;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:nw,...e}).intervalCap&&e.intervalCap>=1))throw new 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 new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#a=e.carryoverConcurrencyCount,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#u=e.intervalCap,this.#h=e.interval,this.#o=new e.queueClass,this.#g=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#w=!0===e.throwOnTimeout,this.#b=!1===e.autoStart}get#v(){return this.#c||this.#l{this.#A()}),t)),!0;this.#l=this.#a?this.#y:0}return!1}#_(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#y&&this.emit("idle"),!1;if(!this.#b){const e=!this.#R;if(this.#v&&this.#E){const t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#c||void 0!==this.#p||(this.#p=setInterval((()=>{this.#I()}),this.#h),this.#d=Date.now()+this.#h)}#I(){0===this.#l&&0===this.#y&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#l=this.#a?this.#y:0,this.#T()}#T(){for(;this.#_(););}get concurrency(){return this.#m}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#m=e,this.#T()}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.#y++,this.#l++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Xs(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#C(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof zs&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#S()}}),t),this.emit("add"),this.#_()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#b?(this.#b=!1,this.#T(),this):this}pause(){this.#b=!0}clear(){this.#o=new this.#g}async onEmpty(){0!==this.#o.size&&await this.#P("empty")}async onSizeLessThan(e){this.#o.sizethis.#o.size{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#y}get isPaused(){return this.#b}}const iw={},ow=e=>{e.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)}))};ow.addEventListener=(e,t)=>{null==iw[e]&&(iw[e]=[]),iw[e].push(t)},ow.removeEventListener=(e,t)=>{null!=iw[e]&&(iw[e]=iw[e].filter((e=>e===t)))},ow.dispatchEvent=function(e,t,r){null!=iw[e]&&iw[e].forEach((e=>e(t,r)))};const aw=ow,cw="lock:worker:request-read",lw="lock:worker:release-read",uw="lock:master:grant-read",hw="lock:worker:request-write",dw="lock:worker:release-write",pw="lock:master:grant-write",fw=(e,t,r,n,s)=>(i,o)=>{if(o.data.type!==r)return;const a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r||null==r.data)return;const s=r.data.type,o=(r.data.name,r.data.identifier);s===n&&o===a.identifier&&(i.removeEventListener("message",t),e())};i.addEventListener("message",t)}))}}}))},gw=(e,t,r,n)=>async()=>{const s=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:s,name:e}),new Promise((t=>{const i=o=>{if(null==o||null==o.data)return;const a=o.data.type,c=o.data.identifier;a===r&&c===s&&(globalThis.removeEventListener("message",i),t((()=>{globalThis.postMessage({type:n,identifier:s,name:e})})))};globalThis.addEventListener("message",i)}))},yw={singleProcess:!1},mw={};let bw;async function ww(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Xs((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const vw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const Ew={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Sw,_w,Aw;function Iw(e,t){const r=Sw.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new cl(e);if("Ed25519"===e.type)return new ll(e);if("secp256k1"===e.type)return new ul(e);throw new Ga("Not a PeerId","ERR_INVALID_PARAMETERS")}({...e,publicKey:e.publicKey}));const n=new Map,s=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry({multiaddr:hu(e),isCertified:t??!1}))),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Aw.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=Aw.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),_w.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.addresses.push(_w.codec().decode(t,t.uint32()));break;case 2:n.protocols.push(t.string());break;case 4:n.publicKey=t.bytes();break;case 5:n.peerRecordEnvelope=t.bytes();break;case 6:{const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());n.metadata.set(r.key,r.value);break}case 7:{const r=e.Peer$tagsEntry.codec().decode(t,t.uint32());n.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return n}))),n),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Sw||(Sw={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(_w||(_w={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Aw||(Aw={}));const kw="/",Rw=(new TextEncoder).encode(kw),Tw=Rw[0];class Cw{_buf;constructor(e,t){if("string"==typeof e)this._buf=$t(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Tw)throw new Error("Invalid key")}toString(e="utf8"){return An(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Cw(e.join(kw))}static random(){return new Cw(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Cw(e):"function"==typeof e.uint8Array?new Cw(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Rw),this._buf[0]!==Tw){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Tw,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Tw;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;es)return!1}return t.lengthe.namespaces())),[].concat(...t))]);var t}}const Pw="/peers/";function Bw(e){if(!tl(e)||null==e.type)throw new Ga("Invalid PeerId",Ew.ERR_INVALID_PARAMETERS);const t=e.toCID().toString();return new Cw(`${Pw}${t}`)}async function Dw(e,t,r){const n=new Map;for(const s of r){if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=hu(s.multiaddr)),!uu(s.multiaddr))throw new Ga("Multiaddr was invalid",Ew.ERR_INVALID_PARAMETERS);if(!await t(e,s.multiaddr))continue;const r=s.isCertified??!1,i=s.multiaddr.toString(),o=n.get(i);null!=o?s.isCertified=o.isCertified||r:n.set(i,{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 Nw(e,t,r,n){if(null==t)throw new Ga("Invalid PeerData",Ew.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!Qn(t.publicKey,e.publicKey))throw new Ga("publicKey bytes do not match peer id publicKey bytes",Ew.ERR_INVALID_PARAMETERS);const s=n.existingPeer;if(null!=s&&!e.equals(s.id))throw new Ga("peer id did not match existing peer id",Ew.ERR_INVALID_PARAMETERS);let i=s?.addresses??[],o=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(i=[],null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(a=xw(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lw})),null!=t.tags&&(c=xw(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Ow,map:Mw})),null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?a.delete(t):a.set(t,r);a=xw([...a.entries()],{validate:Lw})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(c);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);c=xw([...r.entries()],{validate:Ow,map:Mw})}null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)}const u={addresses:await Dw(e,n.addressFilter??(async()=>!0),i),protocols:[...o.values()].sort(((e,t)=>e.localeCompare(t))),metadata:a,tags:c,publicKey:s?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:l};return"RSA"!==e.type&&delete u.publicKey,u}function xw(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Lw(e,t){if("string"!=typeof e)throw new Ga("Metadata key must be a string",Ew.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new Ga("Metadata value must be a Uint8Array",Ew.ERR_INVALID_PARAMETERS)}function Ow(e,t){if("string"!=typeof e)throw new Ga("Tag name must be a string",Ew.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ga("Tag value must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new Ga("Tag value must be between 0-100",Ew.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ga("Tag ttl must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new Ga("Tag ttl must be between greater than 0",Ew.ERR_INVALID_PARAMETERS)}}function Mw(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 Uw(e,t,r){const n=e.toString().split("/")[2],s=dl(Ce.decode(n)),i=r.get(s);if(null!=i)return i;const o=Iw(s,t);return r.set(s,o),o}class Kw{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},vw,e);return null==bw&&(bw=(e=>{if(e=Object.assign({},yw,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return aw.addEventListener("message",fw(e,"requestReadLock",cw,lw,uw)),aw.addEventListener("message",fw(e,"requestWriteLock",hw,dw,pw)),e}return{isWorker:!0,readLock:e=>gw(e,cw,uw,lw),writeLock:e=>gw(e,hw,pw,dw)}})(t),!0!==bw.isWorker&&(bw.addEventListener("requestReadLock",(e=>{null!=mw[e.data.name]&&mw[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),bw.addEventListener("requestWriteLock",(async e=>{null!=mw[e.data.name]&&mw[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==mw[t.name]&&(mw[t.name]=((e,t)=>{if(!0===bw.isWorker)return{readLock:bw.readLock(e,t),writeLock:bw.writeLock(e,t)};const r=new sw({concurrency:1});let n;return{async readLock(){if(null!=n)return ww(n,t);n=new sw({concurrency:t.concurrency,autoStart:!1});const e=n,s=ww(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),s},writeLock:async()=>(n=null,ww(r,t))}})(t.name,t)),mw[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Bw(e))}async delete(e){if(this.peerId.equals(e))throw new Ga("Cannot delete self peer",Ew.ERR_INVALID_PARAMETERS);await this.datastore.delete(Bw(e))}async load(e){return Iw(e,await this.datastore.get(Bw(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter});return this.#D(e,s,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async*all(e){const t=new tw;for await(const{key:r,value:n}of this.datastore.query(function(e,t){return null==e?{}:{prefix:Pw,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(Uw(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(Uw(r.key,r.value,t),Uw(n.key,n.value,t))))}}(e??{},t))){const e=Uw(r,n,t);e.id.equals(this.peerId)||(yield e)}}async#B(e){try{const t=await this.datastore.get(Bw(e));return{existingBuf:t,existingPeer:Iw(e,t)}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async#D(e,t,r,n){const s=Sw.encode(t);return null!=r&&Qn(s,r)?{peer:Iw(e,s),previous:n,updated:!1}:(await this.datastore.put(Bw(e),s),{peer:Iw(e,s),previous:n,updated:!0})}}class Fw{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 Kw(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const 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");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Xn(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");const 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");const 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");const 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");const r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const 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");const r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const 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");const r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const 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){const r=await Hp.openAndCertify(e,Gu.DOMAIN);if(!1===t?.equals(r.peerId))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,r.peerId),!1;const n=Gu.createFromProtobuf(r.payload);let s;try{s=await this.get(r.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=s?.peerRecordEnvelope){const e=await Hp.createFromProtobuf(s.peerRecordEnvelope),t=Gu.createFromProtobuf(e.payload);if(t.seqNumber>=n.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,n.seqNumber),!1}return await this.patch(n.peerId,{peerRecordEnvelope:e,addresses:n.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}))}}const Vw=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},qw=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[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}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},Hw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Xn(e);yield*r.sort(t)}():function*(){const r=Xn(e);yield*r.sort(t)}()},jw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class $w{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const 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 Vw(this.putMany(e,r)),e=[],await Vw(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=qw(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=qw(r,(()=>t++>=n))}return null!=e.limit&&(r=jw(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=qw(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=qw(r,(()=>n++>=t))}return null!=e.limit&&(r=jw(r,e.limit)),r}}class zw extends $w{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw r=r??new Error("Not Found"),as(r,"ERR_NOT_FOUND");var r;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Cw(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Cw(e)}}const Gw=e=>e;function Ww(e,t){const r=e.getPeerId();return null!=r&&hl(r).equals(t)&&(e=e.decapsulate(hu(`/p2p/${t.toString()}`))),e}class Yw{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){const{listen:r=[],announce:n=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.observed=new Map,this.announceFilter=t.announceFilter??Gw,this._updatePeerStoreAddresses=function(e,t){let r;return function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>hu(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=>hu(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>hu(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>hu(e)))}addObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).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)));const t=new Set(e);return this.announceFilter(Array.from(t).map((e=>hu(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}class Xw{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=ob())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>function(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}(e))).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")}}const Jw=["metrics","connectionProtector","dns"],Qw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var Zw=__webpack_require__(5507);const ev=["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 Zw.Netmask(e)));function tv(e){return xl(e)?function(e){for(const t of ev)if(t.contains(e))return!0;return!1}(e):Ll(e)?/^::$/.test(t=e)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t):void 0;var t}function rv(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(tv(`${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}}function nv(e){try{const{address:t}=e.nodeAddress();return Boolean(tv(t))}catch{return!0}}function sv(e,t){const r=function(e,t){const r=nv(e.multiaddr),n=nv(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;const n=function(e,t){const r=Sf.exactMatch(e.multiaddr),n=Sf.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==n)return n;const s=function(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}(e,t);return s}class iv extends Event{constructor(e,t){super(e),this.detail=t}}function ov(e){const t=[uv.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}const av=60;function cv(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:uv[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:uv[e.type],TTL:e.TTL??e.ttl??av,data:e.data instanceof Uint8Array?An(e.data):e.data})))}}function lv(e,t={}){const r=new sw({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ov(n.types).forEach((e=>{s.append("type",uv[e])})),n.onProgress?.(new iv("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=cv(await t.json());return n.onProgress?.(new iv("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw new Error("No DNS response received");return i}}var uv,hv=__webpack_require__(194);class dv{lru;constructor(e){this.lru=hv(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return cv({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:uv[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??av),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class pv{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new dv(t)),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["."]=[lv("https://cloudflare-dns.com/dns-query"),lv("https://dns.google/resolve")])}async query(e,t={}){const r=ov(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new iv("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new iv("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(uv||(uv={}));const{code:fv}=jl("dnsaddr"),gv=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Ga("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");const[,n]=e.stringTuples().find((([e])=>e===fv))??[],s=t?.dns??function(e={}){return new pv(e)}(),i=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[uv.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=hu(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},yv=__webpack_require__(6864);var mv,bv,wv;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"}(mv||(mv={})),(wv=bv||(bv={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",wv.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",wv.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",wv.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",wv.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",wv.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",wv.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",wv.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",wv.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",wv.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",wv.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",wv.ERR_DIALED_SELF="ERR_DIALED_SELF",wv.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",wv.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",wv.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",wv.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",wv.ERR_INVALID_KEY="ERR_INVALID_KEY",wv.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",wv.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",wv.ERR_INVALID_PEER="ERR_INVALID_PEER",wv.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",wv.ERR_NOT_FOUND="ERR_NOT_FOUND",wv.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",wv.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",wv.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",wv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",wv.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",wv.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",wv.ERR_FIND_SELF="ERR_FIND_SELF",wv.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",wv.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",wv.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",wv.ERR_INVALID_CMS="ERR_INVALID_CMS",wv.ERR_MISSING_KEYS="ERR_MISSING_KEYS",wv.ERR_NO_KEY="ERR_NO_KEY",wv.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",wv.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",wv.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",wv.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",wv.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",wv.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",wv.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",wv.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",wv.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",wv.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",wv.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",wv.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",wv.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",wv.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",wv.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",wv.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",wv.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",wv.ERR_INVALID_RECORD="ERR_INVALID_RECORD",wv.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",wv.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",wv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",wv.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",wv.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",wv.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";const vv={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:gv},addressSorter:sv},transportManager:{faultTolerance:dg.FATAL_ALL}};function Ev(e){if(tl(e))return{peerId:e,multiaddrs:[]};let t;if(Array.isArray(e)||(e=[e]),e.length>0){const r=e[0].getPeerId();t=null==r?void 0:hl(r),e.forEach((e=>{if(!uu(e))throw new Ga("Invalid Multiaddr",bv.ERR_INVALID_MULTIADDR);const r=e.getPeerId();if(null==r){if(null!=t)throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}else{const e=hl(r);if(null==t||!t.equals(e))throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}}))}return{peerId:t,multiaddrs:e}}class Sv 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 _v(e,t,r,n){const s=new Sv(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(s):new Promise(((i,o)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void o(e)}a(),i(e)},l=e=>{a(),o(e.detail)},u=()=>{a(),o(s)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Av{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=us(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new za)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Iv{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new za),this.cleanup())}async join(e={}){const t=new Av(new 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();const e=await gi(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 kv extends ni{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(0===this.size)return queueMicrotask((()=>{this.safeDispatchEvent("empty")})),0===this.running&&queueMicrotask((()=>{this.safeDispatchEvent("idle")})),!1;if(this.pending{for(let t=0;t(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{e.abort(new za)})),this.clear()}async onEmpty(e){0!==this.size&&await _v(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.sizethis.size{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail)},i=()=>{r()},o=()=>{r(new Ga("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class Rv extends kv{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}const Tv=42e4,Cv="last-dial-failure",Pv=5,Bv=100,Dv=25,Nv=0,xv=5e3,Lv=Tv,Ov=10;class Mv{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??Pv,this.autoDialPriority=t.autoDialPriority??Nv,this.autoDialIntervalMs=t.autoDialInterval??xv,this.autoDialMaxQueueLength=t.maxQueueLength??Bv,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Lv,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ov,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Rv({concurrency:t.autoDialConcurrency??Dv,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;const e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections)return void(this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections));if(this.queue.size>this.autoDialMaxQueueLength)return this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),void this.sheduleNextAutodial();this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);const r=new cb(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)]}),s=n.sort((()=>Math.random()>.5?1:-1)),i=new tw;for(const e of s)i.has(e.id)||i.set(e.id,[...e.tags.values()].reduce(((e,t)=>e+t.value),0));const o=s.sort(((e,t)=>{const r=i.get(e.id)??0,n=i.get(t.id)??0;return r>n?-1:r{const t=e.metadata.get(Cv);if(null==t)return!0;const r=parseInt(An(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs}));this.log("selected %d/%d peers to dial",o.length,n.length);for(const e of o)this.queue.add((async()=>{const t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections)return this.log("got enough connections now %d/%d",t,this.minConnections),void this.queue.clear();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))}}const Uv=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],Kv={maxConnections:100,allow:[]};class Fv{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kv.maxConnections,this.allow=t.allow??Kv.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(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new tw;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),s=Math.max(t-this.maxConnections,0),i=[];for(const e of n)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString())))||i.push(e),i.length===s)break;await Promise.all(i.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??Uv;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return rn?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:ne.options.priority>t.options.priority?-1:e.options.priority{this.log.error("error in dial queue",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Ev(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if(null!=s)return this.log("already connected to %a",s.remoteAddr),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ga("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=>{const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let s=0;const i=[];for(const o of n){if(s===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",s,r),new Ga("Peer had more than maxPeerAddrsToDial",bv.ERR_TOO_MANY_ADDRESSES);s++;try{const r=await this.components.transportManager.dial(o.multiaddr,{...e,signal:t});return this.log("dial to %a succeeded",o.multiaddr),r}catch(e){if(this.log.error("dial failed to %a",o.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[Cv]:$t(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Ga(e.message,Ya);i.push(e)}}if(1===i.length)throw i[0];throw new Wa(i,"All multiaddr dials failed",bv.ERR_TRANSPORT_DIAL_FAILED)}finally{t.clear()}}),{peerId:r,priority:t.priority??$v,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal})}createDialAbortController(e){return qv([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:hu(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Ga("Tried to dial self",bv.ERR_DIALED_SELF);if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Ga("The dial request is blocked by gater.allowDialPeer",bv.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{const 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!==bv.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const 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!==bv.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of lu.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(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){const t=`/p2p/${e.toString()}`;s=s.map((e=>{const r=e.multiaddr.protos().pop();return!0===r?.path?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Ga("The dial request has no valid addresses",bv.ERR_NO_VALID_ADDRESSES);const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=c.sort(this.addressSorter);if(0===l.length)throw new Ga("The connection gater denied all addresses in the dial request",bv.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnTransientConnection||null!=r.find((e=>!Sf.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const $v=50,zv=5,Gv=100,Wv=5,Yv=10,Xv=25,Jv=0,Qv=100,Zv=Tv,eE=10;class tE{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Gv;const r=t.minConnections??zv;if(this.maxConnectionshu(e))),this.deny=(t.deny??[]).map((e=>hu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Yv,this.inboundConnectionRateLimiter=new qf({points:t.inboundConnectionThreshold??Wv,duration:1}),this.autoDial=new Mv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??Xv,autoDialPriority:t.autoDialPriority??Jv,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Zv,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eE,maxQueueLength:t.autoDialMaxQueueLength??Qv}),this.connectionPruner=new Fv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new jv(e,{addressSorter:t.addressSorter??sv,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:gv},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,outbound:0};for(const t of this.connections.values())for(const r of t)"inbound"===r.direction?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const 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:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const 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()=>{const 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();const e=[];for(const t of this.connections.values())for(const 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){const{detail:t}=e;if(!this.started)return void await t.close();const r=t.remotePeer,n=this.connections.get(r);let s=!1;null!=n?n.push(t):(s=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e;if(!this.started)return;const r=t.remotePeer;let 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(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new Ga("Not started",bv.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();const{peerId:r}=Ev(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>!e.transient));if(null!=e)return this.log("had an existing non-transient connection to %p",r),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??$v});let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)e.id===n.id&&(i=!0);return i||s.push(n),n}async closeConnections(e,t={}){const 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){if(this.deny.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const 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({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>hu(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class rE{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 Ga("No content routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=new cb;for await(const s of gs(...r.routers.map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Ga("No content routers available",bv.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 Ga(mv.NOT_STARTED_YET,bv.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 Ga(mv.NOT_STARTED_YET,bv.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class nE{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=N(n);for(let e=0;ee.equals(t)))}add(e){if(!(e instanceof nE))throw new TypeError("Invalid Fingerprint");for(let t=0;te.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const oE={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aE={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cE=new globalThis.TextEncoder;__webpack_require__(8437);const lE={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!oE[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=oE[t];let s=aE[t],i=e;for(;i.length>0;){const e=cE.encodeInto(i,r);i=i.slice(e.read);for(let i=0;ifunction(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),$t(t,"base16")}(lE.hash(e,t))};class uE{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??lE,this.seed=e.seed??sE(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new iE(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new iE(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[sE(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=95}}const hE={1:.5,2:.84,4:.95,8:.98};function dE(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=hE[r],s=Math.round(e/n);return{filterSize:s,bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log(s/r))+2,64)}}class pE{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??lE,this.seed=e.seed??sE(0,Math.pow(2,10)),this.filterSeries=[new uE({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=$t(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new uE({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=$t(e));for(let t=0;te+t.count),0)}}const fE=globalThis.CustomEvent??Event;class gE{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 Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new Ga("Should not try to find self",bv.ERR_FIND_SELF);const r=this,n=gs(...this.routers.map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new Ga(mv.NOT_FOUND,bv.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=function(e,t=.001,r){return new pE({...dE(1024,t),...r??{}})}();for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,s=new EventTarget,i=[];let o,a=us(),c=us(),l=!1,u=!1;function h(){return n?i[0]?.done:Boolean(i.find((e=>e.done)))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=us(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new fE("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new fE("task-complete"))}))}l=!0,s.dispatchEvent(new fE("task-complete"))}catch(e){o=e,s.dispatchEvent(new fE("task-complete"))}}));;){if(h()||(c=us(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),l&&0===i.length)break}}(async function*(){const n=gs(...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){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id.toBytes())||(n.add(s.id.toBytes()),yield s))}}class yE extends ni{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=qv([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=us();const e=await _v(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=qv([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=Fm(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await gi(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("randomwalk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class mE{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){const t=this.handlers.get(e);if(null==t)throw new Ga(`No handler registered for protocol ${e}`,bv.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new Ga(`Handler already registered for protocol ${e}`,bv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const n=yv.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){(Array.isArray(e)?e:[e]).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 Ga("invalid topology",bv.ERR_INVALID_PARAMETERS);const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.peerStore.get(t).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{e.code!==bv.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())r.transient&&!0!==e.notifyOnTransient||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class bE extends Map{metric;constructor(e){super();const{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){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class wE{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){const{name:t,metrics:r}=e;let n;return n=null!=r?new bE({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??dg.FATAL_ALL}add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ga("Transport must have a valid tag",bv.ERR_INVALID_KEY);if(this.transports.has(t))throw new Ga(`There is already a transport with the tag ${t}`,bv.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(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new Ga(`No transport available for address ${String(e)}`,bv.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=bv.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Ga("Not started",bv.ERR_NODE_NOT_STARTED);if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t=[];for(const[r,n]of this.transports.entries()){const s=n.listenFilter(e),i=[];for(const e of s){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let s=this.listeners.get(r)??[];null==s&&(s=[],this.listeners.set(r,s)),s.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=s.findIndex((e=>e===t));s.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),i.push(t.listen(e))}if(0!==i.length){if(null==(await Promise.allSettled(i)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==dg.NO_FATAL)throw new Ga(`Transport (${r}) could not listen on any available address`,bv.ERR_NO_VALID_ADDRESSES)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===dg.FATAL_ALL)throw new Ga(e,bv.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const vE="/multistream/1.0.0",EE=1024,SE=$t("\n");async function _E(e,t,r){await e.write(t,r)}async function AE(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==SE[0])throw t.log.error("Invalid mss message - missing newline",r),new Ga("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}(e,t);return An(r.subarray())}async function IE(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=vi(e,{...r,maxDataLength:EE,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await AE(n,r);if(r.log.trace('handle: read "%s"',e),e!==vE){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await _E(n,$t(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log('handle: respond with "na" for "%s"',e),await _E(n,$t("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new rs(...t.map((e=>is.single($t(`${e}\n`)))),$t("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await _E(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',vE,e),await _E(n,$t(`${vE}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',vE,e)}}async function kE(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=us();let c=!1,l=!1;const u=us();let h=!1,d=!1;const p=us(),f=vi({sink:n,source:s},{...r,maxDataLength:EE});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',vE,t),await f.writeV([$t(`${vE}\n`),$t(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',vE,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await AE(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===vE&&(e=await AE(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength);const e=`${t}\n`;yield new rs(Uint8Array.from([19]),$t(`${vE}\n`),G(e.length),$t(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength),c=!0,l=!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){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await gi(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=vi(e,{...r,maxDataLength:EE}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',vE,s);const i=$t(`${vE}\n`),o=$t(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await AE(n,r);if(r.log.trace('select: read "%s"',a),a===vE&&(r.log.trace("select: reading protocol response"),a=await AE(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await _E(n,$t(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await AE(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const RE=Symbol.for("@libp2p/connection");class TE{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,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=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[RE]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ga("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new Ga("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&!0!==t?.runOnTransientConnection)throw new Ga("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const 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){const t=AbortSignal.timeout(500);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 CE(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class PE{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){const n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new Ga(`The multiaddr connection is blocked by gater.${r}`,bv.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Ga("connection denied",bv.ERR_CONNECTION_DENIED);let r,n,s,i,o;const a=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new Ga("inbound upgrade timeout",Ya))};a.addEventListener("abort",c,{once:!0});try{if(!0===await(this.components.connectionGater.denyInboundConnection?.(e)))throw new Ga("The multiaddr connection is blocked by gater.acceptConnection",bv.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,!0!==t?.skipEncryption){({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(a));const e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{const t=e.remoteAddr.getPeerId();if(null==t)throw new Ga("inbound connection that skipped encryption must have a peer id",bv.ERR_INVALID_MULTIADDR);const r=hl(t);o="native",n=r}if(s=r,null!=t?.muxerFactory)i=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexInbound({...a,...r},this.muxers);i=e.muxerFactory,s=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:s,muxerFactory:i,remotePeer:n,transient:t?.transient})}finally{a.removeEventListener("abort",c),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){const r=e.remoteAddr.getPeerId();let n,s,i,o,a,c;null!=r&&(n=hl(r),await this.shouldBlockConnection(n,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(l=await t.protect(e))}try{if(s=l,!0!==t?.skipEncryption){({conn:s,remotePeer:i,protocol:a}=await this._encryptOutbound(l,n));const e={...l,...s};await this.shouldBlockConnection(i,e,"denyOutboundEncryptedConnection")}else{if(null==n)throw new Ga("Encryption was skipped but no peer id was passed",bv.ERR_INVALID_PEER);a="native",i=n}if(o=s,null!=t?.muxerFactory)c=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexOutbound({...l,...s},this.muxers);c=e.muxerFactory,o=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:a,direction:"outbound",maConn:e,upgradedConn:o,muxerFactory:c,remotePeer:i,transient:t?.transient})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,transient:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),{stream:r,protocol:n}=await IE(e,t,{log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",n);const s=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(n,this.components.registrar);if(CE(n,"inbound",u)===s){const t=new Ga(`Too many inbound protocol streams for protocol "${n}" - limit ${s}`,bv.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=n,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(i,{protocols:[n]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:n})})).catch((async t=>{u.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()}))}}),l=async(e,t={})=>{if(null==c)throw new Ga("Stream is not multiplexed",bv.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",e);const r=await c.newStream();u.log.trace("started new stream %s for protocols %s",r.id,e);try{if(null==t.signal){r.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const n=AbortSignal.timeout(3e4);t={...t,signal:n}}r.log.trace("selecting protocol from protocols %s",e);const{stream:n,protocol:s}=await kE(r,e,{...t,log:r.log,yieldBytes:!0});r.log("selected protocol %s",s);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,t),a=CE(s,"outbound",u);if(a>=o){const e=new Ga(`Too many outbound protocol streams for protocol "${s}" - ${a}/${o}`,bv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw r.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[s]}),r.source=n.source,r.sink=n.sink,r.protocol=s,null!=n.closeWrite&&(r.closeWrite=n.closeWrite),null!=n.closeRead&&(r.closeRead=n.closeRead),null!=n.close&&(r.close=n.close),this.components.metrics?.trackProtocolStream(r,u),r}catch(t){if(u.log.error("could not create new stream for protocols %s",e,t),null==r.timeline.close&&r.abort(t),null!=t.code)throw t;throw new Ga(String(t),bv.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>(null!=u&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,transient:a,logger:this.components.logger,newStream:l??(()=>{throw new Ga("connection is not multiplexed",bv.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=c?c.streams:[],close:async e=>{null!=c&&(u.log.trace("close muxer"),await c.close(e)),u.log.trace("close maconn"),await n.close(e),u.log.trace("closed maconn")},abort:e=>{n.abort(e),null!=c&&c.abort(e)}},u=new TE(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(t.transient&&!0!==i.runOnTransientConnection)throw new Ga("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:r})}async _encryptInbound(e){const t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{const{stream:r,protocol:n}=await IE(e,t,{log:e.log}),s=this.connectionEncryption.get(n);if(null==s)throw new Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await s.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new Ga(t.message,bv.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await kE(e,r,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(null==i)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,n,t),protocol:s}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new Ga(r.message,bv.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const{stream:n,protocol:s}=await kE(e,r,{log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new Ga(String(t),bv.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{const{stream:n,protocol:s}=await IE(e,r,{log:e.log});return{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Ga(String(t),bv.ERR_MUXER_UNAVAILABLE)}}}class BE extends ni{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new ni,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new ii(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??ob(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new Xw(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Qw.includes(r)){const e=t.components[r];if(null==e&&!Jw.includes(r))throw new Ga(`${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)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.6.1"},logger:this.logger,events:t,datastore:e.datastore??new zw,connectionGater:rv(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Fw(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){const 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 PE(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 wE(this.components,e.transportManager)),this.configureComponent("connectionManager",new tE(this.components,e.connectionManager)),this.configureComponent("registrar",new mE(this.components)),this.configureComponent("addressManager",new Yw(this.components,e.addresses));const s=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new gE(this.components,{routers:s}));const i=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new rE(this.components,{routers:i})),this.configureComponent("randomWalk",new yE(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#x(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[sb]&&(this.log("registering service %s for content routing",t),i.push(r[sb])),null!=r[ib]&&(this.log("registering service %s for peer routing",t),s.push(r[ib])),null!=r[Pl]&&(this.log("registering service %s for peer discovery",t),r[Pl].addEventListener?.("peer",(e=>{this.#x(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}}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(){const e=new cb;for(const 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)throw new Ga("no protocols were provided to open a stream",bv.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ga("no protocols were provided to open a stream",bv.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){uu(e)&&(e=hl(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{const t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==bv.ERR_NOT_FOUND)throw e}const r=Jn([$t("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return function(e){const t=Rm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPublicKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PublicKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw nb(t.Type??"unknown")}}(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)}#x(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error(new Error(bv.ERR_DISCOVERED_SELF))}}async function DE(e={}){const t=e.peerId??=await Qb();if(null==t.privateKey)throw new Ga("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await async function(e){const t=Tm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPrivateKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PrivateKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw nb(t.Type??"RSA")}}(t.privateKey),new BE(await async function(e){const t=yv(vv,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ga(mv.ERR_PROTECTOR_REQUIRED,bv.ERR_PROTECTOR_REQUIRED);if(!(await pl(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new Ga("Private key doesn't match peer id",bv.ERR_INVALID_KEY);return t}(e))}class NE{numPeers;constructor(e){this.numPeers=e?.numPeersToUse??3}}const xE=new qn("sdk:filter"),LE={keepAlive:6e4};class OE{protocol;pubsubTopic;peers;receivedMessagesHashStr=[];keepAliveTimer=null;subscriptionCallbacks;constructor(e,t,r){this.protocol=r,this.peers=t,this.pubsubTopic=e,this.subscriptionCallbacks=new Map}async subscribe(e,t,r=LE){const n=Array.isArray(e)?e:[e];for(const e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:mn.TOPIC_DECODER_MISMATCH}],successes:[]};const s=jr(n),i=Array.from(s.keys()),o=this.peers.map((async e=>this.protocol.subscribe(this.pubsubTopic,e,i))),a=await Promise.allSettled(o),c=this.handleResult(a,"subscribe");return s.forEach(((e,r)=>{const n={decoders:e,callback:t};this.subscriptionCallbacks.set(r,n)})),r?.keepAlive&&this.startKeepAlivePings(r.keepAlive),c}async unsubscribe(e){const t=this.peers.map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.keepAliveTimer&&this.stopKeepAlivePings(),n}async ping(){const e=this.peers.map((async e=>this.protocol.ping(e))),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){const e=this.peers.map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.keepAliveTimer&&this.stopKeepAlivePings(),r}async processIncomingMessage(e){const t=function(e,t){const r=function(e,t){const r=Tn(e),n=Tn(t.contentTopic),s=function(e){if(e)return function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(e.valueOf())}(t.timestamp),i=Cn([r,t.payload,n,t.meta,s].filter(Hr));return gn(i)}(e,t);return Rn(r)}(this.pubsubTopic,e);if(this.receivedMessagesHashStr.includes(t))return void xE.info("Message already received, skipping");this.receivedMessagesHashStr.push(t);const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(xE.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:s}=e,{contentTopic:i}=r;if(i)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),i=await Promise.any(e);await s(i)}catch(e){xE.error("Error decoding message",e)}else xE.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):xE.error("No subscription callback available for ",r)}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)xE.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:mn.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}startKeepAlivePings(e){this.keepAliveTimer?xE.info("Recurring pings already set up."):this.keepAliveTimer=setInterval((()=>{(async()=>{try{xE.info("Recurring ping to peers."),await this.ping()}catch(e){xE.error("Stopping recurring pings due to failure",e),this.stopKeepAlivePings()}})()}),e)}stopKeepAlivePings(){this.keepAliveTimer?(xE.info("Stopping recurring pings."),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null):xE.info("Already stopped recurring pings.")}}class ME extends NE{protocol;activeSubscriptions=new Map;async handleIncomingMessage(e,t){const r=this.getActiveSubscription(e);r?await r.processIncomingMessage(t):xE.error(`No subscription locally registered for topic ${e}`)}constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Ls(this.handleIncomingMessage.bind(this),e,t),this.activeSubscriptions=new Map}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}async createSubscription(e){const t="string"==typeof e?e:Bn(e)?.[0];Nn(t,this.protocol.pubsubTopics);let r=[];try{r=await this.protocol.getPeers()}catch(e){return xE.error("Error getting peers to initiate subscription: ",e),{error:mn.GENERIC_FAIL,subscription:null}}return 0===r.length?{error:mn.NO_PEER_AVAILABLE,subscription:null}:(xE.info(`Creating filter subscription with ${r.length} peers: `,r.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(t)??this.setActiveSubscription(t,new OE(t,r,this.protocol))})}async subscribe(e,t,r=LE){const n=this.getUniquePubsubTopics(e);if(0===n.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(n.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:s,error:i}=await this.createSubscription(n[0]);if(i)throw Error(`Failed to create subscription: ${i}`);await s.subscribe(e,t,r);const o=Array.from(jr(Array.isArray(e)?e:[e]).keys());return async()=>{await s.unsubscribe(o)}}toSubscriptionIterator(e){return async function(e,t,r){const n=r?.iteratorDelay??60,s=[];let i;i=await e.subscribe(t,(e=>{s.push(e)}));const o=Number.isInteger(r?.timeoutMs),a=r?.timeoutMs??0,c=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-c>=a)return;await $r(n);const e=s.shift();if(!i&&0===s.length)return e;!e&&i||(yield e)}}(),async stop(){i&&(await i(),i=void 0)}}}(this,e)}getUniquePubsubTopics(e){return Array.isArray(e)?0===e.length?[]:[...new Set(e.map((e=>e.pubsubTopic)))]:[e.pubsubTopic]}}const UE=new qn("sdk:light-push");class KE extends NE{protocol;constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Us(e,t)}async send(e,t){const r=[],n=[],{pubsubTopic:s}=e;try{Nn(s,this.protocol.pubsubTopics)}catch(e){return UE.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:mn.TOPIC_NOT_CONFIGURED}],successes:[]}}const i=await this.protocol.getPeers();if(!i.length)return{successes:r,failures:[{error:mn.NO_PEER_AVAILABLE}]};const o=i.map((r=>this.protocol.send(e,t,r))),a=await Promise.allSettled(o);for(const e of a)if("fulfilled"===e.status){const{failure:t,success:s}=e.value;s&&r.push(s),t&&n.push(t)}else UE.error("Failed to send message to peer",e.reason),n.push({error:mn.GENERIC_FAIL});return{successes:r,failures:n}}}const FE=new qn("waku:store:protocol");class VE extends NE{protocol;constructor(e,t){super({numPeersToUse:1}),this.protocol=new $s(e,t)}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:s}=this.validateDecodersAndPubsubTopic(e,t),i=this.constructOptions(r,n,t),o=(await this.protocol.getPeers({numPeers:this.numPeers,maxBootstrapPeers:1}))[0];if(!o)throw new Error("No peers available to query");const a=this.protocol.queryPerPage(i,s,o);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t,r))break}async queryWithPromiseCallback(e,t,r){let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}createCursor(e){if(!(e&&e.timestamp&&e.payload&&e.contentTopic))throw new Error("Message is missing required fields");const t=Tn(e.contentTopic),r=gn(Cn([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 new Error("No decoders provided");const r=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(r.length>1)throw new Error("API does not support querying multiple pubsub topics at once");const n=r[0];if(Nn(n,this.protocol.pubsubTopics),t?.cursor?.pubsubTopic&&t.cursor.pubsubTopic!==n)throw new Error(`Cursor pubsub topic (${t?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${n})`);const s=new Map;e.forEach((e=>{if(s.has(e.contentTopic))throw new Error("API does not support different decoder per content topic");s.set(e.contentTopic,e)}));const i=e.filter((e=>e.pubsubTopic===n)).map((e=>e.contentTopic));if(0===i.length)throw new Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:i,decodersAsMap:s}}constructOptions(e,t,r={}){let n,s;return r?.timeFilter&&(n=r.timeFilter.startTime,s=r.timeFilter.endTime),n||FE.warn("No start time provided"),s||FE.warn("No end time provided"),Object.assign({pubsubTopic:e,pageDirection:bn.BACKWARD,pageSize:10},r,{contentTopics:t,startTime:n,endTime:s})}async processMessages(e,t,r){let n=!1,s=(await Promise.all(e)).filter(Hr);return this.shouldReverseOrder(r)&&(s=s.reverse()),await Promise.all(s.map((async e=>{e&&!n&&(n=Boolean(await t(e)))}))),n}shouldReverseOrder(e){return void 0===e?.pageDirection||e?.pageDirection===bn.BACKWARD}}async function qE(e={}){const t=await async function(e){(function(e){e.pubsubTopics?eR.info("Using pubsubTopics array to bootstrap the node."):e.contentTopics?eR.info("Using contentTopics and default cluster ID (1) to bootstrap the node."):e.shardInfo&&eR.info("Using shardInfo parameters to bootstrap the node.")})(e),e.contentTopics&&(e.shardInfo={contentTopics:e.contentTopics});const t=e.shardInfo?Mn(e.shardInfo):void 0;e.pubsubTopics=t?.pubsubTopics??e.pubsubTopics??[Sn];const r=e?.libp2p??{},n=r.peerDiscovery??[];var s,i;e?.defaultBootstrap&&n.push(...(s=e.pubsubTopics,[Uk(s.includes(Sn)?[GE.DEPRECATED_DEFAULT_PUBSUB]:[GE.SANDBOX,GE.TEST],Zk),(e,t)=>new Jk(e,t),Wk(s)])),e?.bootstrapPeers&&n.push((i={list:e.bootstrapPeers},e=>new ju(e,i))),r.peerDiscovery=n;const o=await async function(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"));const s=t?{pubsub:t}:{},i=e?{metadata:pi(e)}:{};return async function(e={}){const t=await DE(e);return!1!==e.start&&await t.start(),t}({connectionManager:{minConnections:1},transports:[Cg({filter:Rg})],streamMuxers:[ag()],connectionEncryption:[Cl()],...r,services:{identify:Mf({agentVersion:n??HE}),ping:ug({maxInboundStreams:r?.pingMaxInboundStreams??jE}),...i,...s,...r?.services}})}(t?.shardInfo,function(e={}){return t=>{e={...e,msgIdFn:({data:e})=>gn(e),globalSignaturePolicy:Kg.StrictNoSign,fallbackToFloodsub:!1};const r=new gm(t,e);return r.multicodecs=ym,r}}(e),r,e?.userAgent);return o}(e),r=function(e={}){return t=>new VE(t,e)}(e),n=function(e={}){return t=>new KE(t,e)}(e),s=(i=e,e=>new ME(e,i));var i;return new zE(e,t,r,n,s)}const HE="js-waku",jE=10,$E=new qn("waku");class zE{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r,n,s,i){if(0==e.pubsubTopics.length)throw new Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r&&(this.store=r(t)),s&&(this.filter=s(t)),n&&(this.lightPush=n(t)),i&&(this.relay=i(t));const o=e.pingKeepAlive||300,a=this.relay?e.relayKeepAlive||300:0,c=this.libp2p.peerId.toString();this.connectionManager=li.create(c,t,{pingKeepAlive:o,relayKeepAlive:a},this.pubsubTopics,this.relay),$E.info("Waku node created",c,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){const r=t??[],n=function(e){return tl(e)?e:hu(e)}(e);void 0===t&&(this.relay&&r.push(yn.Relay),this.store&&r.push(yn.Store),this.filter&&r.push(yn.Filter),this.lightPush&&r.push(yn.LightPush));const s=[];return r.includes(yn.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>s.push(e))):$E.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Store)&&(this.store?s.push(this.store.protocol.multicodec):$E.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(yn.LightPush)&&(this.lightPush?s.push(this.lightPush.protocol.multicodec):$E.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Filter)&&(this.filter?s.push(this.filter.protocol.multicodec):$E.error("Filter codec not included in dial codec: protocol not mounted locally")),$E.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,s)}async start(){await this.libp2p.start()}async stop(){this.connectionManager.stop(),await this.libp2p.stop()}async subscribeToContentTopic(e,t,r){return(await async function(e,t,r){r.waku=r.waku??await qE({shardInfo:{contentTopics:[e]}});const{decoder:n,subscription:s}=await async function(e,t,r){if(!e.filter)throw new Error("Filter protocol missing from Waku node");const{shardInfo:n}=e.libp2p.components.metadata;if(!n)throw new Error("Shard info missing from Waku node.");const s=Bn(n),i=Ln(t);if(!s.includes(i))throw new Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await ei(e,[yn.Filter]);let o=Yn(t,i);o&&(o=o??o);const{subscription:a,error:c}=await e.filter.createSubscription(i);if(c)throw new Error("Failed to create subscription for content topic.");return{decoder:o,subscription:a}}(r.waku,e,r.peer);return await s.subscribe(n,t),{subscription:s,waku:r.waku}}(e,r,{waku:this,peer:t})).subscription}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}getLocalMultiaddrWithID(){const 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()}}const GE={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",DEPRECATED_DEFAULT_PUBSUB:"enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im"},WE="bootstrap",YE={store:2,filter:1,lightPush:1};var XE=__webpack_require__(495),JE=__webpack_require__.t(XE,2);const QE=BigInt(0),ZE=BigInt(1),eS=BigInt(2),tS=BigInt(3),rS=BigInt(8),nS=Object.freeze({a:QE,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:ZE,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),sS=(e,t)=>(e+t/eS)/t,iS={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=nS,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ZE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=sS(i*e,t),c=sS(-n*e,t);let l=NS(e-a*r-c*s,t),u=NS(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},oS=32,aS=32,cS=oS+1,lS=2*oS+1;function uS(e){const{a:t,b:r}=nS,n=NS(e*e),s=NS(n*e);return NS(s+t*e+r)}const hS=nS.a===QE;class dS extends Error{constructor(e){super(e)}}function pS(e){if(!(e instanceof fS))throw new TypeError("JacobianPoint expected")}class fS{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof mS))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(mS.ZERO)?fS.ZERO:new fS(e.x,e.y,ZE)}static toAffineBatch(e){const t=function(e,t=nS.P){const r=new Array(e.length),n=LS(e.reduce(((e,n,s)=>n===QE?e:(r[s]=e,NS(e*n,t))),ZE),t);return e.reduceRight(((e,n,s)=>n===QE?e:(r[s]=NS(e*r[s],t),NS(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return fS.toAffineBatch(e).map(fS.fromAffine)}equals(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a);return l===u&&h===d}negate(){return new fS(this.x,NS(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=NS(e*e),s=NS(t*t),i=NS(s*s),o=e+s,a=NS(eS*(NS(o*o)-n-i)),c=NS(tS*n),l=NS(c*c),u=NS(l-eS*a),h=NS(c*(a-u)-rS*i),d=NS(eS*t*r);return new fS(u,h,d)}add(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===QE||i===QE)return this;if(t===QE||r===QE)return e;const a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a),p=NS(u-l),f=NS(d-h);if(p===QE)return f===QE?this.double():fS.ZERO;const g=NS(p*p),y=NS(p*g),m=NS(l*g),b=NS(f*f-y-eS*m),w=NS(f*(m-b)-h*y),v=NS(n*o*p);return new fS(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=fS.ZERO;if("bigint"==typeof e&&e===QE)return t;let r=DS(e);if(r===ZE)return this;if(!hS){let e=t,n=this;for(;r>QE;)r&ZE&&(e=e.add(n)),n=n.double(),r>>=ZE;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=iS.splitScalar(r),a=t,c=t,l=this;for(;s>QE||o>QE;)s&ZE&&(a=a.add(l)),o&ZE&&(c=c.add(l)),l=l.double(),s>>=ZE,o>>=ZE;return n&&(a=a.negate()),i&&(c=c.negate()),c=new fS(NS(c.x*iS.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=hS?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i>=u,o>a&&(o-=l,e+=ZE);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(gS(p,n[h])):s=s.add(gS(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=DS(e);if(hS){const{k1neg:e,k1:i,k2neg:o,k2:a}=iS.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=gS(e,c),u=gS(o,u),u=new fS(NS(u.x*iS.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return fS.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(fS.ZERO);null==e&&(e=s?rS:LS(n));const i=e,o=NS(i*i),a=NS(o*i),c=NS(t*o),l=NS(r*a),u=NS(n*i);if(s)return mS.ZERO;if(u!==ZE)throw new Error("invZ was invalid");return new mS(c,l)}}function gS(e,t){const r=t.negate();return e?r:t}fS.BASE=new fS(nS.Gx,nS.Gy,ZE),fS.ZERO=new fS(QE,ZE,QE);const yS=new WeakMap;class mS{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,yS.delete(this)}hasEvenY(){return this.y%eS===QE}static fromCompressedHex(e){const t=32===e.length,r=PS(t?e:e.subarray(1));if(!VS(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=nS,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=xS(l,tS)*l%t,h=xS(u,tS)*l%t,d=xS(h,eS)*c%t,p=xS(d,n)*d%t,f=xS(p,s)*p%t,g=xS(f,o)*f%t,y=xS(g,a)*g%t,m=xS(y,o)*f%t,b=xS(m,tS)*l%t,w=xS(b,i)*p%t,v=xS(w,r)*c%t,E=xS(v,eS);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(uS(r));const s=(n&ZE)===ZE;t?s&&(n=NS(-n)):!(1&~e[0])!==s&&(n=NS(-n));const i=new mS(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=PS(e.subarray(1,oS+1)),r=PS(e.subarray(oS+1,2*oS+1)),n=new mS(t,r);return n.assertValidity(),n}static fromHex(e){const t=BS(e),r=t.length,n=t[0];if(r===oS)return this.fromCompressedHex(t);if(r===cS&&(2===n||3===n))return this.fromCompressedHex(t);if(r===lS&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${cS} compressed bytes or ${lS} uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return mS.BASE.multiply(HS(e))}static fromSignature(e,t,r){const{r:n,s}=jS(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const i=OS(BS(e)),{n:o}=nS,a=2===r||3===r?n+o:n,c=LS(a,o),l=NS(-i*c,o),u=NS(s*c,o),h=1&r?"03":"02",d=mS.fromHex(h+IS(a)),p=mS.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return CS(this.toHex(e))}toHex(e=!1){const t=IS(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${IS(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!VS(t)||!VS(r))throw new Error(e);const n=NS(r*r);if(NS(n-uS(t))!==QE)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new mS(this.x,NS(-this.y))}double(){return fS.fromAffine(this).double().toAffine()}add(e){return fS.fromAffine(this).add(fS.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return fS.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=fS.fromAffine(this),s=t===QE||t===ZE||this!==mS.BASE?n.multiplyUnsafe(t):n.multiply(t),i=fS.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(fS.ZERO)?void 0:o.toAffine()}}function bS(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function wS(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${_S(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:PS(r),left:e.subarray(t+2)}}mS.BASE=new mS(nS.Gx,nS.Gy),mS.ZERO=new mS(QE,QE);class vS{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?_S(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new vS(TS(n.slice(0,64)),TS(n.slice(64,128)))}static fromDER(e){const t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${_S(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=wS(e.subarray(2)),{data:n,left:s}=wS(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${_S(s)}`);return{r:t,s:n}}(t?e:CS(e));return new vS(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!FS(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!FS(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=nS.n>>ZE;return this.s>e}normalizeS(){return this.hasHighS()?new vS(this.r,NS(-this.s,nS.n)):this}toDERRawBytes(){return CS(this.toDERHex())}toDERHex(){const e=bS(RS(this.s)),t=bS(RS(this.r)),r=e.length/2,n=t.length/2,s=RS(r),i=RS(n);return`30${RS(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return CS(this.toCompactHex())}toCompactHex(){return IS(this.r)+IS(this.s)}}function ES(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;tt.toString(16).padStart(2,"0")));function _S(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r0)return BigInt(e);if("bigint"==typeof e&&FS(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function NS(e,t=nS.P){const r=e%t;return r>=QE?r:t+r}function xS(e,t){const{P:r}=nS;let n=e;for(;t-- >QE;)n*=n,n%=r;return n}function LS(e,t=nS.P){if(e===QE||t<=QE)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=NS(e,t),n=t,s=QE,i=ZE,o=ZE,a=QE;for(;r!==QE;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==ZE)throw new Error("invert: does not exist");return NS(s,t)}function OS(e,t=!1){const r=function(e){const t=8*e.length-8*aS,r=PS(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=nS;return r>=n?r-n:r}let MS,US;class KS{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new 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 JS.hmacSha256(this.k,...e)}hmacSync(...e){return US(this.k,...e)}checkSync(){if("function"!=typeof US)throw new dS("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new 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;const t=[];for(;e0)t=BigInt(e);else if("string"==typeof e){if(e.length!==2*aS)throw new Error("Expected 32 bytes of private key");t=TS(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(e.length!==aS)throw new Error("Expected 32 bytes of private key");t=PS(e)}if(!FS(t))throw new Error("Expected private key: 0 < key < n");return t}function jS(e){if(e instanceof vS)return e.assertValidity(),e;try{return vS.fromDER(e)}catch(t){return vS.fromCompact(e)}}function $S(e){return PS(e.length>oS?e.slice(0,oS):e)}function zS(e){const t=$S(e),r=NS(t,nS.n);return GS(r{e=BS(e);const t=aS+8;if(e.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return kS(NS(PS(e),nS.n-ZE)+ZE)},randomBytes:(e=32)=>{if(YS.web)return YS.web.getRandomValues(new Uint8Array(e));if(YS.node){const{randomBytes:t}=YS.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>JS.hashToPrivateKey(JS.randomBytes(aS+8)),precompute(e=8,t=mS.BASE){const r=t===mS.BASE?t:new mS(t.x,t.y);return r._setWindowSize(e),r.multiply(tS),r},sha256:async(...e)=>{if(YS.web){const t=await YS.web.subtle.digest("SHA-256",ES(...e));return new Uint8Array(t)}if(YS.node){const{createHash:t}=YS.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(YS.web){const r=await YS.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=ES(...t),s=await YS.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(YS.node){const{createHmac:r}=YS.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=XS[e];if(void 0===r){const t=await JS.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return JS.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof MS)throw new dS("sha256Sync is undefined, you need to set it");let r=XS[e];if(void 0===r){const t=MS(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return MS(r,...t)},_JacobianPoint:fS};Object.defineProperties(JS,{sha256Sync:{configurable:!1,get:()=>MS,set(e){MS||(MS=e)}},hmacSha256Sync:{configurable:!1,get:()=>US,set(e){US||(US=e)}}});var QS=__webpack_require__(1176);function ZS(e){return new Uint8Array(QS.keccak256.arrayBuffer(e))}function e_(e,t,r){try{return function(e,t,r,n=WS){let s;try{s=jS(e),t=BS(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=OS(t);let c;try{c=function(e){return e instanceof mS?(e.assertValidity(),e):mS.fromHex(e)}(r)}catch(e){return!1}const{n:l}=nS,u=LS(o,l),h=NS(a*u,l),d=NS(i*u,l),p=mS.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&NS(p.x,l)===i}(vS.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const t_="Invalid record id";function r_(e,t){switch(t){case"udp":return r_(e,"udp4")||r_(e,"udp6");case"tcp":return r_(e,"tcp4")||r_(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=hu("/"+e+"/"+$l(e,r));return s=s.encapsulate(hu("/"+t+"/"+$l(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}function n_(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const s_=32,i_=64,o_=32;function a_(e,t){const r=new Uint8Array(i_);for(let n=0;nFr(d_)}(h_||(h_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(p_||(p_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(f_||(f_={}));class g_{_key;constructor(e){this._key=E_(e,s_)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return p_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class y_{_key;_publicKey;constructor(e,t){this._key=E_(e,i_),this._publicKey=E_(t,s_)}sign(e){return function(e,t){const r=e.subarray(0,o_);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new g_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function m_(e){if(e.length>i_){const t=(e=E_(e,i_+s_)).subarray(0,i_),r=e.subarray(i_,e.length);return new y_(t,r)}const t=(e=E_(e,i_)).subarray(0,i_),r=e.subarray(s_);return new y_(t,r)}function b_(e){return e=E_(e,s_),new g_(e)}async function w_(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:a_(e,t),publicKey:t}}();return new y_(e,t)}async function v_(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==o_)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:a_(t,r),publicKey:r}}(e);return new y_(t,r)}function E_(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function S_(e){const t=[await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await A_(e)],r=await __({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function __(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([c_.get().subtle.exportKey("jwk",e.privateKey),c_.get().subtle.exportKey("jwk",e.publicKey)])}async function A_(e){return c_.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 I_(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function k_(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function R_(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const C_=8192;class P_{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return c_.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return p_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class B_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return k_(16)}sign(e){return async function(e,t){const r=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await c_.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new P_(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url"))),Hd.fromBigInt(T_($t(e.d,"base64url"))),Hd.fromBigInt(T_($t(e.p,"base64url"))),Hd.fromBigInt(T_($t(e.q,"base64url"))),Hd.fromBigInt(T_($t(e.dp,"base64url"))),Hd.fromBigInt(T_($t(e.dq,"base64url"))),Hd.fromBigInt(T_($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return f_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=c_.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=k_(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=k_(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function D_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(R_(r[1].toBigInt()),"base64url"),e:An(R_(r[2].toBigInt()),"base64url"),d:An(R_(r[3].toBigInt()),"base64url"),p:An(R_(r[4].toBigInt()),"base64url"),q:An(R_(r[5].toBigInt()),"base64url"),dp:An(R_(r[6].toBigInt()),"base64url"),dq:An(R_(r[7].toBigInt()),"base64url"),qi:An(R_(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await S_(t);return new B_(r.privateKey,r.publicKey)}function N_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(R_(r[0].toBigInt()),"base64url"),e:An(R_(r[1].toBigInt()),"base64url")}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new P_(t)}async function x_(e){if(I_(e)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await S_(e);return new B_(t.privateKey,t.publicKey)}async function L_(e){if(e>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await c_.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 __(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new B_(t.privateKey,t.publicKey)}function O_(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class M_{_key;constructor(e){O_(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(n_(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return p_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}}class U_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),O_(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(n_(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new M_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function K_(e){return new U_(e)}function F_(e){return new M_(e)}async function V_(){const e=$c.utils.randomPrivateKey();return new U_(e)}const q_={rsa:B,ed25519:P,secp256k1:D};function H_(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function j_(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class $_ 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(){const e=this.get("id");if(!e)throw new Error("id not found.");return Rn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(t_)}get rs(){const e=this.get("rs");if(e)return Un(e)}get rsv(){const e=this.get("rsv");if(e)return Un(e)}get ip(){return z_(this,"ip","ip4")}set ip(e){W_(this,"ip","ip4",e)}get tcp(){return G_(this,"tcp","tcp")}set tcp(e){Y_(this,"tcp","tcp",e)}get udp(){return G_(this,"udp","udp")}set udp(e){Y_(this,"udp","udp",e)}get ip6(){return z_(this,"ip6","ip6")}set ip6(e){W_(this,"ip6","ip6",e)}get tcp6(){return G_(this,"tcp6","tcp")}set tcp6(e){Y_(this,"tcp6","tcp",e)}get udp6(){return G_(this,"udp6","udp")}set udp6(e){Y_(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){X_(this,"waku2",e,(e=>new Uint8Array([j_(e)])))}}function z_(e,t,r){const n=e.get(t);if(n)return $l(r,n)}function G_(e,t,r){const n=e.get(t);if(n)return Number($l(r,n))}function W_(e,t,r,n){X_(e,t,n,zl.bind({},r))}function Y_(e,t,r,n){W_(e,t,r,n?.toString(10))}function X_(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function J_(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=BS(e),s=HS(t),i=[GS(s),zS(n)];if(null!=r){!0===r&&(r=JS.randomBytes(oS));const e=BS(r);if(e.length!==oS)throw new Error(`sign: Expected ${oS} bytes of extra data`);i.push(e)}return{seed:ES(...i),m:$S(n),d:s}}(e,t,r.extraEntropy),o=new KS(32,aS);let a;for(await o.reseed(n);!(a=qS(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(ZS(t),e,{der:!1})}const Q_=new qn("enr");var Z_,eA;!function(e){e.TCP="tcp",e.UDP="udp"}(Z_||(Z_={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(eA||(eA={}));class tA extends $_{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){const n=new tA(e,t,r);try{const e=n.publicKey;e&&(n.peerId=await function(e){return pl(new q_.secp256k1.Secp256k1PublicKey(e).bytes,void 0)}(e))}catch(e){Q_.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=mS.fromHex(e).toRawBytes(!1);return kn(ZS(t.slice(1)))}(this.publicKey):void 0;throw new Error(t_)}getLocationMultiaddr=r_.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Q_.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new 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(){const e=[];for(const t of Object.values(eA)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const 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 new Error(t_);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return e_(t,ZS(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(t_);return this.signature=await J_(t,e),this.signature}}let rA=!1,nA=!1;const sA={debug:1,default:2,info:2,warning:3,error:4,off:5};let iA=sA.default,oA=null;const aA=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var cA,lA;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(cA||(cA={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(lA||(lA={}));const uA="0123456789abcdef";class hA{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==sA[r]&&this.throwArgumentError("invalid log level name","logLevel",e),iA>sA[r]||console.log.apply(console,t)}debug(...e){this._log(hA.levels.DEBUG,e)}info(...e){this._log(hA.levels.INFO,e)}warn(...e){this._log(hA.levels.WARNING,e)}makeError(e,t,r){if(nA)return this.makeError("censored error",t,{});t||(t=hA.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4],r+=uA[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}`);const s=e;let i="";switch(t){case lA.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case lA.CALL_EXCEPTION:case lA.INSUFFICIENT_FUNDS:case lA.MISSING_NEW:case lA.NONCE_EXPIRED:case lA.REPLACEMENT_UNDERPRICED:case lA.TRANSACTION_REPLACED:case lA.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=new Error(e);return o.reason=s,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,hA.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"),aA&&this.throwError("platform missing String.prototype.normalize",hA.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:aA})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,hA.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",hA.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",hA.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",hA.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return oA||(oA=new hA("logger/5.7.0")),oA}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),rA){if(!e)return;this.globalLogger().throwError("error censorship permanent",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}nA=!!e,rA=!!t}static setLogLevel(e){const t=sA[e.toLowerCase()];null!=t?iA=t:hA.globalLogger().warn("invalid log level - "+e)}static from(e){return new hA(e)}}hA.errors=lA,hA.levels=cA;const dA=new hA("bytes/5.7.0");function pA(e){return!!e.toHexString}function fA(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return fA(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function gA(e){return"number"==typeof e&&e==e&&e%1==0}function yA(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!gA(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function mA(e,t){if(t||(t={}),"number"==typeof e){dA.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),fA(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),pA(e)&&(e=e.toHexString()),bA(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":dA.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e>4]+wA[15&n]}return t}return dA.throwArgumentError("invalid hexlify value","value",e)}const EA=new hA("rlp/5.7.0");function SA(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function _A(e,t,r){let n=0;for(let s=0;st+1+n&&EA.throwError("child data too short",hA.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function kA(e,t){if(0===e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&EA.throwError("data short segment too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data long segment too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:vA(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:vA(e.slice(t+1,t+1+r))}}return{consumed:1,result:vA(e[t])}}const RA=new qn("enr:decoder");class TA{static fromString(e){if(!e.startsWith(tA.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${tA.RECORD_PREFIX}'`);return TA.fromRLP($t(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=mA(e),r=kA(t,0);return r.consumed!==t.length&&EA.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(In);return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;eCA.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let s=0;for(let i=0;i(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},DA={name:"v6",size:16,isFormat:e=>e.length>0&&PA.test(e),encode(e,t,r){let n=16+(r=~~r),s=-1,i=0,o=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l>8),r=97?u-=87:u>=65?u-=55:(u-=48,o=10*o+u),i=(i<<4)+u)}if(!1===a)!0===c?(r>8),r=s+2;e--)t[e]=t[e-2];t[s]=0,t[s+1]=0,s=r}if(s!==r&&-1!==s)for(r>n-2&&(r=n-2);n>s;)t[--n]=rs?t[--r]:0;else for(;r=qA||(64512&e.charCodeAt(i))!==qA?t+=3:(n=i,t+=4)}}return t}function jA(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(HA(e)+r));let s=r;for(let r=0;r>6,t[s++]=128|63&i;else if((63488&i)!==VA)t[s++]=224|(61440&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i;else{const o=r+1;if(o===n||i>=qA)t[s++]=239,t[s++]=191,t[s++]=189;else{const n=e.charCodeAt(o);(64512&n)!==qA?(t[s++]=239,t[s++]=191,t[s++]=189):(r=o,i=65536|(1023&i)<<10|1023&n,t[s++]=240|(1835008&i)>>18,t[s++]=128|(258048&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i)}}}return jA.bytes=s-r,t}function $A(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let s=t;s191&&t<224)r=(31&t)<<6|63&e[s++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;const i=VA|r>>10&1023;n+=String.fromCharCode(i),r=qA|1023&r}else r=(15&t)<<12|(63&e[s++])<<6|63&e[s++];n+=String.fromCharCode(r)}return $A.bytes=r-t,n}jA.bytes=0,$A.bytes=0;const zA=e=>e instanceof Uint8Array;function GA(e){return"string"==typeof e?HA(e):e.byteLength}function WA(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):jA(e)}function YA(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return jA(t,e,r),jA.bytes}const XA=Math.pow(2,24),JA=Math.pow(2,16),QA=Math.pow(2,8),ZA=(e,t)=>e[t]*XA+e[t+1]*JA+e[t+2]*QA+e[t+3],eI=(e,t)=>e[t]<<8|e[t+1],tI=(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),rI=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function nI(e,t,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=t.length||n>=s?0:function(e,t,r,n,s){s-n>t.length-r&&(s=n+t.length-r);let i=s-n;const o=e.length-n;return i>o&&(i=o),(0!==n||se)}}const iI=sI({encode(e,t,r){t||(t=new Uint8Array(iI.encodingLength(e))),r||(r=0);const n=r,s=e.replace(/^\.|\.$/gm,"");if(s.length){const e=s.split(".");for(let n=0;n=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(i+=o?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=eI(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,i+=o?0:1,o=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=a+1,s>254)throw new Error("Cannot decode name (name too long)");r.push($A(e,t,t+a)),t+=a,i+=o?0:a}}return iI.decode.bytes=i,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:GA(e.replace(/^\.|\.$/gm,""))+2}),oI=sI({encode(e,t,r){t||(t=new Uint8Array(oI.encodingLength(e))),r||(r=0);const n=YA(t,e,r+1);return t[r]=n,oI.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=$A(e,t+1,t+1+r);return oI.decode.bytes=r+1,n},encodingLength:e=>GA(e)+1}),aI=sI({bytes:12,encode(e,t,r){t||(t=new Uint8Array(aI.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),s="response"===e.type?32768:0;return rI(t,e.id||0,r),rI(t,n|s,r+2),rI(t,e.questions.length,r+4),rI(t,e.answers.length,r+6),rI(t,e.authorities.length,r+8),rI(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw new Error("Header must be 12 bytes");const r=eI(e,t+2);return{id:eI(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:MA(r>>11&15),flag_aa:1==(r>>10&1),flag_tc:1==(r>>9&1),flag_rd:1==(r>>8&1),flag_ra:1==(r>>7&1),flag_z:1==(r>>6&1),flag_ad:1==(r>>5&1),flag_cd:1==(r>>4&1),rcode:OA(15&r),questions:new Array(eI(e,t+4)),answers:new Array(eI(e,t+6)),authorities:new Array(eI(e,t+8)),additionals:new Array(eI(e,t+10))}},encodingLength:()=>12}),cI=sI({encode(e,t,r){t||(t=new Uint8Array(cI.encodingLength(e))),r||(r=0);const n=e.length;return rI(t,n,r),nI(e,t,r+2,0,n),cI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n=e.slice(t+2,t+2+r);return cI.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),lI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(lI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),lI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=eI(e,t),n=iI.decode(e,t+2);return lI.decode.bytes=r+2,n},encodingLength:e=>iI.encodingLength(e)+2}),uI=sI({encode(e,t,r){t||(t=new Uint8Array(uI.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mname,t,r),r+=iI.encode.bytes,iI.encode(e.rname,t,r),r+=iI.encode.bytes,tI(t,e.serial||0,r),r+=4,tI(t,e.refresh||0,r),r+=4,tI(t,e.retry||0,r),r+=4,tI(t,e.expire||0,r),r+=4,tI(t,e.minimum||0,r),rI(t,(r+=4)-n-2,n),uI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=iI.decode(e,t),t+=iI.decode.bytes,n.rname=iI.decode(e,t),t+=iI.decode.bytes,n.serial=ZA(e,t),t+=4,n.refresh=ZA(e,t),t+=4,n.retry=ZA(e,t),t+=4,n.expire=ZA(e,t),t+=4,n.minimum=ZA(e,t),t+=4,uI.decode.bytes=t-r,n},encodingLength:e=>22+iI.encodingLength(e.mname)+iI.encodingLength(e.rname)}),hI=sI({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t0;){const r=e[t++];if(--n,ne?(zA(e)?e.length:GA(e))+2:2}),pI=sI({encode(e,t,r){t||(t=new Uint8Array(pI.encodingLength(e))),r||(r=0);const n=r;return r+=2,oI.encode(e.cpu,t,r),r+=oI.encode.bytes,oI.encode(e.os,t,r),r+=oI.encode.bytes,rI(t,r-n-2,n),pI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=oI.decode(e,t),t+=oI.decode.bytes,n.os=oI.decode(e,t),t+=oI.decode.bytes,pI.decode.bytes=t-r,n},encodingLength:e=>oI.encodingLength(e.cpu)+oI.encodingLength(e.os)+2}),fI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(fI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),fI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=iI.decode(e,t+2);return fI.decode.bytes=iI.decode.bytes+2,r},encodingLength:e=>iI.encodingLength(e)+2}),gI=sI({encode(e,t,r){t||(t=new Uint8Array(gI.encodingLength(e))),r||(r=0),rI(t,e.priority||0,r+2),rI(t,e.weight||0,r+4),rI(t,e.port||0,r+6),iI.encode(e.target,t,r+8);const n=iI.encode.bytes+6;return rI(t,n,r),gI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n={};return n.priority=eI(e,t+2),n.weight=eI(e,t+4),n.port=eI(e,t+6),n.target=iI.decode(e,t+8),gI.decode.bytes=r+2,n},encodingLength:e=>8+iI.encodingLength(e.target)}),yI=sI({encode(e,t,r){const n=yI.encodingLength(e);return t||(t=new Uint8Array(yI.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=yI.ISSUER_CRITICAL),rI(t,n-2,r),t[r+=2]=e.flags||0,r+=1,oI.encode(e.tag,t,r),r+=oI.encode.bytes,YA(t,e.value,r),r+=GA(e.value),yI.encode.bytes=n,t},decode(e,t){t||(t=0);const r=eI(e,t),n=t+=2,s={};return s.flags=e[t],t+=1,s.tag=oI.decode(e,t),t+=oI.decode.bytes,s.value=$A(e,t,n+r),s.issuerCritical=!!(s.flags&yI.ISSUER_CRITICAL),yI.decode.bytes=r+2,s},encodingLength:e=>oI.encodingLength(e.tag)+oI.encodingLength(e.value)+2});yI.ISSUER_CRITICAL=128;const mI=sI({encode(e,t,r){t||(t=new Uint8Array(mI.encodingLength(e))),r||(r=0);const n=r;return r+=2,rI(t,e.preference||0,r),r+=2,iI.encode(e.exchange,t,r),r+=iI.encode.bytes,rI(t,r-n-2,n),mI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=eI(e,t),t+=2,n.exchange=iI.decode(e,t),t+=iI.decode.bytes,mI.decode.bytes=t-r,n},encodingLength:e=>4+iI.encodingLength(e.exchange)}),bI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(bI.encodingLength(e))),r||(r=0),rI(t,4,r),r+=2,BA.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,BA.decode(e,t)),bytes:6}),wI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(wI.encodingLength(e))),r||(r=0),rI(t,16,r),r+=2,DA.encode(e,t,r),wI.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=DA.decode(e,t);return wI.decode.bytes=18,r},bytes:18}),vI=e=>new Uint8Array(e),EI=sI({encode(e,t,r){t||(t=new Uint8Array(EI.encodingLength(e))),r||(r=0);const n=r,s=FA(e.code);if(rI(t,s,r),r+=2,e.data)rI(t,e.data.length,r),r+=2,nI(e.data,t,r),r+=e.data.length;else switch(s){case 8:{const n=e.sourcePrefixLength||0,s=e.family||function(e){return NA(e)===BA.size?1:2}(e.ip),i=function(e,t,r){r=~~r;const n=NA(e);return"function"==typeof t&&(t=t(r+n)),n===BA.size?BA.encode(e,t,r):DA.encode(e,t,r)}(e.ip,vI),o=Math.ceil(n/8);rI(t,o+4,r),rI(t,s,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,nI(i,t,r,0,o),r+=o}break;case 11:e.timeout?(rI(t,2,r),r+=2,rI(t,e.timeout,r),r+=2):(rI(t,0,r),r+=2);break;case 12:{const n=e.length||0;rI(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;rI(t,n,r),r+=2;for(const n of e.tags)rI(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return EI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=eI(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);const n=eI(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=eI(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const s=new Uint8Array(1===r.family?4:16);nI(e,s,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===BA.size)return BA.decode(e,t,r);if(r===DA.size)return DA.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${BA.size} for v4 or ${DA.size} for v6.`)}(s)}break;case 11:n>0&&(r.timeout=eI(e,t),t+=2);break;case 14:r.tags=[];for(let s=0;s0;)n[i++]=EI.decode(e,t),t+=EI.decode.bytes,s-=EI.decode.bytes;return SI.decode.bytes=t-r,n},encodingLength:e=>2+VI(e||[],EI)}),_I=sI({encode(e,t,r){t||(t=new Uint8Array(_I.encodingLength(e))),r||(r=0);const n=r,s=e.key;if(!zA(s))throw new Error("Key must be a Buffer");return r+=2,rI(t,e.flags,r),t[r+=2]=_I.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,nI(s,t,r+=1,0,s.length),r+=s.length,_I.encode.bytes=r-n,rI(t,_I.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);if(t+=2,n.flags=eI(e,t),e[t+=2]!==_I.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+s+2),t+=n.key.length,_I.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.key)});_I.PROTOCOL_DNSSEC=3,_I.ZONE_KEY=128,_I.SECURE_ENTRYPOINT=32768;const AI=sI({encode(e,t,r){t||(t=new Uint8Array(AI.encodingLength(e))),r||(r=0);const n=r,s=e.signature;if(!zA(s))throw new Error("Signature must be a Buffer");return r+=2,rI(t,LA(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,tI(t,e.originalTTL,r),r+=4,tI(t,e.expiration,r),r+=4,tI(t,e.inception,r),r+=4,rI(t,e.keyTag,r),r+=2,iI.encode(e.signersName,t,r),nI(s,t,r+=iI.encode.bytes,0,s.length),r+=s.length,AI.encode.bytes=r-n,rI(t,AI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.typeCovered=xA(eI(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=ZA(e,t),t+=4,n.expiration=ZA(e,t),t+=4,n.inception=ZA(e,t),t+=4,n.keyTag=eI(e,t),t+=2,n.signersName=iI.decode(e,t),t+=iI.decode.bytes,n.signature=e.slice(t,r+s+2),t+=n.signature.length,AI.decode.bytes=t-r,n},encodingLength:e=>20+iI.encodingLength(e.signersName)+GA(e.signature)}),II=sI({encode(e,t,r){t||(t=new Uint8Array(II.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mbox||".",t,r),r+=iI.encode.bytes,iI.encode(e.txt||".",t,r),r+=iI.encode.bytes,II.encode.bytes=r-n,rI(t,II.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=iI.decode(e,t)||".",t+=iI.decode.bytes,n.txt=iI.decode(e,t)||".",t+=iI.decode.bytes,II.decode.bytes=t-r,n},encodingLength:e=>2+iI.encodingLength(e.mbox||".")+iI.encodingLength(e.txt||".")}),kI=sI({encode(e,t,r){t||(t=new Uint8Array(kI.encodingLength(e))),r||(r=0);const n=r,s=[];for(let t=0;t>8]&&(s[r>>8]=[]),s[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e2+iI.encodingLength(e.nextDomain)+kI.encodingLength(e.rrtypes)}),TI=sI({encode(e,t,r){t||(t=new Uint8Array(TI.encodingLength(e))),r||(r=0);const n=r,s=e.salt;if(!zA(s))throw new Error("salt must be a Buffer");const i=e.nextDomain;if(!zA(i))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,rI(t,e.iterations,r),t[r+=2]=s.length,nI(s,t,r+=1,0,s.length),t[r+=s.length]=i.length,nI(i,t,r+=1,0,i.length),r+=i.length,kI.encode(e.rrtypes,t,r),r+=kI.encode.bytes,TI.encode.bytes=r-n,rI(t,TI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=eI(e,t);const i=e[t+=2];t+=1,n.salt=e.slice(t,t+i);const o=e[t+=i];return t+=1,n.nextDomain=e.slice(t,t+o),t+=o,n.rrtypes=kI.decode(e,t,s-(t-r)),t+=kI.decode.bytes,TI.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+kI.encodingLength(e.rrtypes)}),CI=sI({encode(e,t,r){t||(t=new Uint8Array(CI.encodingLength(e))),r||(r=0);const n=r,s=e.digest;if(!zA(s))throw new Error("Digest must be a Buffer");return r+=2,rI(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,nI(s,t,r+=1,0,s.length),r+=s.length,CI.encode.bytes=r-n,rI(t,CI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.keyTag=eI(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+s+2),t+=n.digest.length,CI.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.digest)});function PI(e){switch(e.toUpperCase()){case"A":return bI;case"PTR":case"CNAME":case"DNAME":return fI;case"TXT":return hI;case"NULL":return dI;case"AAAA":return wI;case"SRV":return gI;case"HINFO":return pI;case"CAA":return yI;case"NS":return lI;case"SOA":return uI;case"MX":return mI;case"OPT":return SI;case"DNSKEY":return _I;case"RRSIG":return AI;case"RP":return II;case"NSEC":return RI;case"NSEC3":return TI;case"DS":return CI}return cI}const BI=sI({encode(e,t,r){t||(t=new Uint8Array(BI.encodingLength(e))),r||(r=0);const n=r;if(iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");rI(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,rI(t,e.flags||0,r+6),r+=8,SI.encode(e.options||[],t,r),r+=SI.encode.bytes}else{let n=KA(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),rI(t,n,r+2),tI(t,e.ttl||0,r+4),r+=8;const s=PI(e.type);s.encode(e.data,t,r),r+=s.encode.bytes}return BI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=iI.decode(e,t),t+=iI.decode.bytes,r.type=xA(eI(e,t)),"OPT"===r.type)r.udpPayloadSize=eI(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=eI(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=SI.decode(e,t+8),t+=8+SI.decode.bytes;else{const n=eI(e,t+2);r.ttl=ZA(e,t+4),r.class=UA(-32769&n),r.flush=!!(32768&n);const s=PI(r.type);r.data=s.decode(e,t+8),t+=8+s.decode.bytes}return BI.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return iI.encodingLength(e.name)+8+PI(e.type).encodingLength(t)}}),DI=sI({encode(e,t,r){t||(t=new Uint8Array(DI.encodingLength(e))),r||(r=0);const n=r;return iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),r+=2,rI(t,KA(void 0===e.class?"IN":e.class),r),r+=2,DI.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=iI.decode(e,t),t+=iI.decode.bytes,n.type=xA(eI(e,t)),t+=2,n.class=UA(eI(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),DI.decode.bytes=t-r,n},encodingLength:e=>iI.encodingLength(e.name)+4}),NI=256,xI={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(FI(e))),r||(r=0);const s=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),aI.encode(e,t,r),r+=aI.encode.bytes,r=qI(e.questions,DI,t,r),r=qI(e.answers,BI,t,r),r=qI(e.authorities,BI,t,r),r=qI(e.additionals,BI,t,r),xI.encode.bytes=r-s,n&&UI.bytes!==t.length?t.slice(0,UI.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=aI.decode(e,t);return t+=aI.decode.bytes,t=HI(n.questions,DI,e,t),t=HI(n.answers,BI,e,t),t=HI(n.authorities,BI,e,t),t=HI(n.additionals,BI,e,t),xI.decode.bytes=t-r,n},encodingLength:function(e){return aI.encodingLength(e)+VI(e.questions||[],DI)+VI(e.answers||[],BI)+VI(e.authorities||[],BI)+VI(e.additionals||[],BI)}};function LI(e,t){if(e.questions)throw new Error("Only one .question object expected instead of a .questions array!");const r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}xI.encode.bytes=0,xI.decode.bytes=0;const OI={encode:function(e,t,r){return t=xI.encode(LI(e,"query"),t,r),OI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return OI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"query"))}};OI.encode.bytes=0,OI.decode.bytes=0;const MI={encode:function(e,t,r){return t=xI.encode(LI(e,"response"),t,r),MI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return MI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"response"))}};MI.encode.bytes=0,MI.decode.bytes=0;const UI=xI.encode,KI=xI.decode,FI=xI.encodingLength;function VI(e,t){let r=0;for(let n=0;n255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==s[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);s[r]=e,i[e]=r}const o=r.charCodeAt(0),a={name:e,encodingLength(e){const 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);const i=n%4,c=n-i;let l=r,u=0;for(;u>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===i){const r=s[e.charCodeAt(u)]<<10|s[e.charCodeAt(u+1)]<<4|s[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===i&&(t[l++]=s[e.charCodeAt(u)]<<2|s[e.charCodeAt(u+1)]>>4);return a.encode.bytes=l-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);const s=r-t,c=s%3,l=t+s-c,u=[];for(let r=t;r>18&63],i[t>>12&63],i[t>>6&63],i[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(i[t>>10],i[t>>4&63],i[t<<2&63]),1===n&&u.push(o)}else if(1===c){const t=e[r-1];u.push(i[t>>2],i[t<<4&63]),1===n&&u.push(o,o)}return a.decode.bytes=s,String.fromCharCode.apply(String,u)}};return a}jI("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const $I=jI("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let zI="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;zI||(zI=class extends Error{constructor(e="Request aborted."){super(e)}}),zI.prototype.name="AbortError",zI.prototype.code="ABORT_ERR";const GI="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class WI 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}}}WI.prototype.name="HTTPStatusError",WI.prototype.code="HTTP_STATUS";class YI extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:ZI(this.cause)}}}YI.prototype.name="ResponseError",YI.prototype.code="RESPONSE_ERR";class XI extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}XI.prototype.name="TimeoutError",XI.prototype.code="ETIMEOUT";const JI=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,QI=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function ZI(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const ek=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,tk=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,rk=/\[(((pk|name)=([^\]]+)))\]/gi;function nk(e,t){t.lastIndex=0;const r={};for(;;){const n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class sk extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${ik.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}sk.prototype.name="InvalidProtocolError",sk.prototype.code="EPROTOCOL";const ik=["http:","https:","udp4:","udp6:"];class ok{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;const 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))throw new Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`);this.port=r}}toJSON(){return this.toString()}}class ak extends ok{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){const 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 ck extends ak{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw new Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class lk extends ak{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw new Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function uk(e){return QI.test(e)&&!JI.test(e)?`[${e}]`:e}class hk extends ok{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 new 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){const e=QI.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||JI.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${uk(this.host)}:${this.port}${this.path}`;try{this.url=new GI(t)}catch(e){throw new Error(e.message+` [${t}]`)}}toString(){const 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,s=this.name?` [name=${this.name}]`:"",i=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",o=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${uk(this.host)}${t}${n}${r}${i}${o}${s}`}}function dk(e){let t;if("string"==typeof e)t=function(e){const t=ek.exec(e),r=t[2]||"https:",n=t[3],s=t[5],i=t[6],o=t[7];if("https:"===r||"http:"===r){const e=nk(o,tk);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:s,path:i,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=nk(o,rk),i=/^\[(.*)\]$/.exec(n);if(i&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!i&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return i?new lk({protocol:"udp6:",ipv6:i[1],port:s,pk:t.pk,name:t.name}):new ck({protocol:"udp4:",ipv4:n,port:s,pk:t.pk,name:t.name})}throw new sk(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Can not convert ${e} to an endpoint`);if(e instanceof ok)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new ck(t);if("udp6:"===r)return new lk(t);if("https:"===r||"http:"===r)return new hk(t);throw new sk(r,JSON.stringify(t))}const pk="application/dns-message";function fk(){}function gk(e,t,r,n,s){return new Promise(((i,o)=>{const a=new GI(e);"GET"===t&&r&&(a.search="?dns="+$I.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",pk),"POST"===t&&l.setRequestHeader("Content-Type",pk),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new XI(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new WI(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new WI(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new WI(c,l.status,t));else{let e;if("string"==typeof l.response)e=jA(l.response);else if(l.response instanceof Uint8Array)e=l.response;else{if(!(Array.isArray(l.response)||l.response instanceof ArrayBuffer))throw new Error("Unprocessable response "+l.response);e=new Uint8Array(l.response)}u(null,e)}},"POST"===t?l.send(r):l.send(),s&&s.addEventListener("abort",h);let u=function(e,t){u=fk,s&&s.removeEventListener("abort",h),i(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new zI);try{l.abort()}catch(e){}}}))}function yk(e){const t=null===e.time||void 0===e.time?Date.now():e.time,r=function(e){return e.filter((e=>e.cors||e.endpoint.cors))}(e.data.map((e=>(e.endpoint=dk(Object.assign({name:e.name},e.endpoint)),e)))),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}}Error;const mk=yk({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});const bk=new GI("https://martinheidegger.github.io/dns-query/resolvers.json");function wk(e){return/^@/.test(e)}const vk=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:bk,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r,n){const s=t?t.localStoragePrefix+t.name:null;if(s)try{const e=JSON.parse(localStorage.getItem(s));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:i}=await gk(e,"GET",null,r,void 0),o={time:Date.now(),data:JSON.parse($A(i))};if(s)try{localStorage.setItem(s,JSON.stringify(o))}catch(e){o.time=null}return o}(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=>yk({data:e.data.resolvers,time:e.time}))).catch((()=>t||mk)):Promise.resolve(mk),this._dataP):this._dataP.then((e=>e.timee.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=_k),"dns"===e&&(e=Ak),"function"==typeof e)return this.data().then((t=>t.endpoints.filter(e)));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(wk))try{return Promise.resolve(e.map(dk))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(wk(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return dk(e)}))))}};function Ek(e,t){return t=Object.assign({retries:5,timeout:3e4},t),e.question?(r=t.endpoints,function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(r)?r:Promise.resolve(r)).then((r=>{if(!Array.isArray(r)||0===r.length)throw new Error("No endpoints defined to lookup dns records.");return Sk(r.map(dk),function(e){const t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(e),t)})).then((e=>(e.question=e.questions[0],delete e.questions,e))):Promise.reject(new Error("To request data you need to specify a .question!"));var r}function Sk(e,t,r){const n=1===e.length?e[0]:e[Math.floor(Math.random()*e.length)%e.length];return function(e,t,r,n){return n&&n.aborted?Promise.reject(new zI):"udp4:"===e.protocol||"udp6:"===e.protocol?function(){throw new Error('Only "doh" endpoints are supported in the browser')}():function(e,t,r,n){return function(e,t,r,n,s){return gk(e,t,r,n,s)}(e.url,e.method,UI(Object.assign({flags:NI},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new YI("Empty.");else try{const e=KI(t);return e.response=r,e}catch(e){n=new YI("Invalid packet (cause="+e.message+")",e)}throw Object.assign(n,{response:r})}))}(e,t,r,n)}(n,t,r.timeout,r.signal).then((e=>(e.endpoint=n.toString(),e)),(s=>{if("AbortError"===s.name||0===r.retries)throw s.endpoint=n.toString(),s;return r.retries>0&&(r.retries-=1),Sk(e,t,r)}))}function _k(e){return"https:"===e.protocol||"http:"===e.protocol}function Ak(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const Ik=new qn("dns-over-https");class kk{endpoints;retries;static async create(e,t){const r=e??await vk.endpoints("doh");return new kk(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await Ek({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw Ik.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=t.map((e=>e.data)),n=[];return r.forEach((e=>{"string"==typeof e?n.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?n.push(e):n.push(Rn(e))})):n.push(Rn(e))})),n}}var Rk=__webpack_require__(5818);class Tk{static RECORD_PREFIX=tA.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 new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=Tk.parseRootValues(e),n=Rk.decode.asBytes(t),s=e.split(" sig")[0],i=Tn(s);if(!e_($t(r.signature,"base64url").slice(0,64),ZS(i),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const Ck=new qn("discovery:fetch_nodes");function Pk(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function Bk(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function Dk(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function Nk(e,t,r){if(Pk(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relaythis._search(s,i)));return xk.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){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=Tk.parseTree(e[r]),i={domain:s,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=new Set;for(;!Pk(n,i)&&othis._search(s,i))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(Tk.ROOT_PREFIX)?Tk.ROOT_PREFIX:e.startsWith(Tk.BRANCH_PREFIX)?Tk.BRANCH_PREFIX:e.startsWith(Tk.RECORD_PREFIX)?Tk.RECORD_PREFIX:""}(r);try{switch(i){case Tk.ROOT_PREFIX:return n=Tk.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case Tk.BRANCH_PREFIX:return s=Tk.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case Tk.RECORD_PREFIX:return TA.fromString(r);default:return null}}catch(t){return xk.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return xk.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const Ok=new qn("peer-discovery-dns");class Mk extends ni{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;Ok.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(Ok.info("Starting peer discovery via dns"),this._started=!0,void 0===this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await Lk.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[WE]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(WE)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:Kn(r)}}})),s&&this.dispatchEvent(new ii("peer",{detail:t}))}}stop(){this._started=!1}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}function Uk(e,t=YE){return r=>new Mk(r,{enrUrls:e,wantedNodeCapabilityCount:t})}class Kk{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new Kk({query:{numPeers:t},response:void 0})}encode(){return Or.encode(this.proto)}static decode(e){const t=Or.decode(e);return new Kk(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const Fk="/vac/waku/peer-exchange/2.0.0-alpha1",Vk=new qn("peer-exchange");class qk extends _s{constructor(e,t){super(Fk,e,Vk,t)}async query(e){const{numPeers:t}=e,r=Kk.createRequest({numPeers:BigInt(t)}),n=await this.peerStore.get(e.peerId);if(!n)return{peerInfos:null,error:mn.NO_PEER_AVAILABLE};let s;try{s=await this.getStream(n)}catch(e){return Vk.error("Failed to get stream",e),{peerInfos:null,error:mn.NO_STREAM_AVAILABLE}}const i=await ys([r.encode()],is,s,ls,(async e=>await Xn(e)));try{const e=new rs;i.forEach((t=>{e.append(t)}));const{response:t}=Kk.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Hr).map((async e=>({ENR:await TA.fromRLP(e)})))),error:null}:(Vk.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:mn.EMPTY_PAYLOAD})}catch(e){return Vk.error("Failed to decode push reply",e),{peerInfos:null,error:mn.DECODE_FAILED}}}}const Hk=new qn("peer-exchange-discovery"),jk=1e4,$k=3,zk=wn.PEER_EXCHANGE;class Gk extends ni{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(Fk)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>Hk.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new qk(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(Hk.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(Hk.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=jk,maxRetries:n=$k}=this.options;Hk.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const s=this.queryAttempts.get(t)??1;s>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,s+1),this.startRecurringQueries(e).catch((e=>{Hk.error(`Error in startRecurringQueries: ${e}`)}))}),r*s)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return Hk.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){Hk.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;r&&n&&(await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{tags:{[zk]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:Kn(s)}}}),Hk.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){Hk.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}function Wk(e){return t=>new Gk(t,e)}const Yk=new qn("peer-exchange-discovery"),Xk=wn.LOCAL;class Jk extends ni{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){Yk.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=await ew({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[hu(t)],tags:{[this.options?.tagName??Xk]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:[hu(t)]}})))}Yk.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(Yk.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find((e=>e.toString().includes("ws")||e.toString().includes("wss")));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),s=this.getPeersFromLocalStorage(),i=s.findIndex((e=>e.id===t.toString()));i>=0?s[i].address=n.toString():s.push({id:t.toString(),address:n.toString()}),this.peers=s,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(Qk):[]}catch(e){return Yk.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){Yk.error("Error saving peers to local storage:",e)}}}function Qk(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const Zk={lightPush:1,filter:1,store:1},eR=new qn("sdk:create");var tR,rR=__webpack_require__(2549),nR=function(e,t,r,n){return new(r||(r=Promise))((function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},sR=function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0?[4,this.send(this.queue)]:[3,2];case 1:e.sent()&&(console.log("Sent ",this.queue.length," telemetry logs"),this.queue=[]),e.label=2;case 2:return[2]}}))}))}),this.intervalPeriod)),[2]}))}))},e.prototype.stop=function(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)},e.prototype.send=function(e){return nR(this,void 0,void 0,(function(){var t,r,n,s=this;return sR(this,(function(i){switch(i.label){case 0:t=e.map((function(e){return{id:++s.requestId,telemetryType:e.messageType.toString(),telemetryData:e}})),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=i.sent()).status?(console.error("Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=i.sent(),console.error("Error sending messages to telemetry service: ",n),console.error("Failed trying to send the following messages: ",t),[2,!1];case 4:return[2]}}))}))},e}(),oR=function(e){return t=void 0,r=void 0,s=function(){var t,r,n;return function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&(e.push([{messageType:tR.LIGHT_PUSH_FILTER,timestamp:Math.floor((new Date).getTime()/1e3),peerIdSender:r,peerIdReporter:r,sequenceHash:o,sequenceTotal:a,sequenceIndex:c,contentTopic:lR,pubsubTopic:Sn}]),d=document.createElement("div"),p=document.getElementById("messagesSent"),d.textContent="Message: ".concat(o," ").concat(c," of ").concat(a),p.insertBefore(d,p.firstChild),p.insertBefore(document.createElement("br"),p.firstChild),document.dispatchEvent(dR),c++),h.failures.length>0&&console.error("Failed to send message",h.failures),c{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,s=2,i=!0;s{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),s=new Array(123),i=0;i<64;)s[n[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;r.encode=function(e,t,r){for(var s,i=null,o=[],a=0,c=0;t>2],s=(3&l)<<4,c=1;break;case 1:o[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:o[a++]=n[s|l>>6],o[a++]=n[63&l],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[s],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,i=r,a=0,c=0;c1)break;if(void 0===(l=s[l]))throw Error(o);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(o);return r-i},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function s(e){if("string"!=typeof e){var r=i();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";e.exports=i;var n=r(8045),s=r(4153)("fs");function i(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&s&&s.readFile?s.readFile(e,(function(n,s){return n&&"undefined"!=typeof XMLHttpRequest?i.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))})):i.xhr(e,t,r):n(i,this,e,t)}i.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var s=0;s{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3]}function i(e,n,s){t[0]=e,n[s]=r[3],n[s+1]=r[2],n[s+2]=r[1],n[s+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?s:i,e.writeFloatBE=n?i:s,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var s=t<0?1:0;if(s&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var i=Math.floor(Math.log(t)/Math.LN2);e((s<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),s=2*(n>>31)+1,i=n>>>23&255,o=8388607&n;return 255===i?o?NaN:s*(1/0):0===i?1401298464324817e-60*s*o:s*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,i)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3],n[s+4]=r[4],n[s+5]=r[5],n[s+6]=r[6],n[s+7]=r[7]}function i(e,n,s){t[0]=e,n[s]=r[7],n[s+1]=r[6],n[s+2]=r[5],n[s+3]=r[4],n[s+4]=r[3],n[s+5]=r[2],n[s+6]=r[1],n[s+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?s:i,e.writeDoubleBE=n?i:s,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,s,i){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,i+t),e(1/n>0?0:2147483648,s,i+r);else if(isNaN(n))e(0,s,i+t),e(2146959360,s,i+r);else if(n>17976931348623157e292)e(0,s,i+t),e((o<<31|2146435072)>>>0,s,i+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,i+t),e((o<<31|a/4294967296)>>>0,s,i+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,s,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,s,i+r)}}}function o(e,t,r,n,s){var i=e(n,s+t),o=e(n,s+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+i;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,i,4,0)}(),e}function r(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 n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},s=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),s="";r&&(s=t.shift()+"/");for(var i=0;i0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return s+t.join("/")};r.resolve=function(e,t,r){return r||(t=s(t)),n(t)?t:(r||(e=s(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?s(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,s=n>>>1,i=null,o=n;return function(r){if(r<1||r>s)return e(r);o+r>n&&(i=e(n),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?i[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[o++]=55296+(n>>10),i[o++]=56320+(1023&n)):i[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))},r.write=function(e,t,r){for(var n,s,i=r,o=0;o>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-i}},7833:(e,t,r)=>{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;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,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&&"undefined"!=typeof process&&"env"in process&&(e=process.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=(()=>{let e=!1;return()=>{e||(e=!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(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,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:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(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(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{},this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}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._headthis._capacity&&this.pop(),this._head1e4&&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._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var s,i=this._list[t];if(e0;s--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}},t.prototype.remove=function(e,t){var r,n=e,s=t;if(n===(0|n)&&this._head!==this._tail){var i=this.size(),o=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=i)return r=this.toArray(),this.clear(),r;var a;for(n+t>i&&(t=i-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;s>0;)this._list[n=n-1+o&this._capacityMask]=void 0,s--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;s>0;)this._list[n=n+1+o&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>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){var s,i,o,a=arguments.length,c=this._list.length,l=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(s=r;s>0;s--)this.unshift(i[s-1])}else{var u=(i=new Array(n-(r+t))).length;for(s=0;sthis._tail){for(i=this._head;i>>=1,this._capacityMask>>>=1},t.prototype._nextPowerOf2=function(e){var t=1<{"use strict";function t(e,t){for(const 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 new 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(r){n.message=e.message,n.stack=e.stack;const s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(e)),t(new s,n)}}},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},9939:(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;const t={value:e,done:!1};if(this.pullQueue.length){const 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){this.isStopped=!0,this.remove();for(const e of 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(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const 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}={}){const s=new r;s.highWaterMark=t,s.lowWaterMark=n,s.removeCallback=e({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on:(e,t)=>{s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=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,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},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 s=0,i=n.length,o=new Array(i);s{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 s(s,i){r[s]=i,++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])?(s(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,i=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},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new 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){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,s,i,o,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],o=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,i=0,o=0;i191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):l(i,n);for(var a=0;a191)&&l(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(i,n),r>1114111&&l(i,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,s,i,o,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,y=f>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var m=f-y;return 2===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e[l],a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,i,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],s=c[3],i=c[4],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i]):1===l?h+=o[t>>>3]+o[t<<2&31]+"======":2===l?(r=c[1],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,i&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4866:e=>{e.exports=function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6368:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},1176:(e,t,r)=>{var n;!function(){"use strict";var s="input is invalid type",i="object"==typeof window,o=i?window:{};o.JS_SHA3_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=global:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[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],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(s);return[e,!1]},S=function(e){return 0===E(e)[0].length},_=function(e){for(var t=[],r=0;r>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 F(e,t,r){K.call(this,e,t,r)}K.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(i[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[l]<=o){for(this.start=r-o,this.block=i[c],r=0;r>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},K.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},K.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t==0&&(r=_(r),V(r),i=0)}return s&&(e=r[i],a+=h[e>>4&15]+h[15&e],s>1&&(a+=h[e>>12&15]+h[e>>8&15]),s>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},K.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=_(n),V(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},F.prototype=new K,F.prototype.finalize=function(){return this.encode(this.outputBits,!0),K.prototype.finalize.call(this)};var V=function(e){var t,r,n,s,i,o,a,c,l,u,h,d,p,g,y,m,b,w,v,E,S,_,A,I,k,R,T,C,P,B,D,N,x,L,O,M,U,K,F,V,q,H,j,$,z,G,W,Y,X,J,Q,Z,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=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],c=e[4]^e[14]^e[24]^e[34]^e[44],l=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],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(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=s^(c<<1|l>>>31),r=i^(l<<1|c>>>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=c^(d<<1|p>>>31),r=l^(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^(s<<1|i>>>31),r=h^(i<<1|s>>>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,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,H=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,L=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,B=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,N=e[45]<<29|e[44]>>>3,x=e[44]<<29|e[45]>>>3,I=e[6]<<28|e[7]>>>4,k=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,K=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,$=e[8]<<27|e[9]>>>5,z=e[9]<<27|e[8]>>>5,R=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,V=e[38]<<8|e[39]>>>24,q=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,A=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~b&v,e[10]=I^~R&C,e[11]=k^~T&P,e[20]=L^~M&K,e[21]=O^~U&F,e[30]=$^~G&Y,e[31]=z^~W&X,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~C&B,e[13]=T^~P&D,e[22]=M^~K&V,e[23]=U^~F&q,e[32]=G^~Y&J,e[33]=W^~X&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&_,e[5]=v^~S&A,e[14]=C^~B&N,e[15]=P^~D&x,e[24]=K^~V&H,e[25]=F^~q&j,e[34]=Y^~J&Z,e[35]=X^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~_&g,e[7]=S^~A&y,e[16]=B^~N&I,e[17]=D^~x&k,e[26]=V^~H&L,e[27]=q^~j&O,e[36]=J^~Z&$,e[37]=Q^~ee&z,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=A^~y&b,e[18]=N^~I&R,e[19]=x^~k&T,e[28]=H^~L&M,e[29]=j^~O&U,e[38]=Z^~$&G,e[39]=ee^~z&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=B;else{for(N=0;NObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)s.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)i.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):e}const 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),i=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!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,l(t),r):u(t)}e.exports=function(...e){const t=p(u(c),this!==a&&this||{},c);let r={_:{}};for(const s of e)if(void 0!==s){if(!n(s))throw new TypeError("`"+s+"` is not an Option Object");r=p(r,{_:s},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,i=7*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\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(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=s?o(c,l,s,"day"):l>=n?o(c,l,n,"hour"):l>=r?o(c,l,r,"minute"):l>=t?o(c,l,t,"second"):c+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8437:(e,t,r)=>{e.exports=r(4327)},4327:function(e,t){!function(r,n){"use strict";var s={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function i(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t255)return!1;return!0}function o(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<>>32-t}function c(e){return e=o(e^=e>>>16,2246822507),(e=o(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<>>32-t,e[1]<>>32-t]:(t-=32,[e[1]<>>32-t,e[0]<>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<>>32-t,e[1]<>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}s.x86.hash32=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%4,l=e.length-r,u=t,h=0,d=3432918353,p=461845907,f=0;f>>0},s.x86.hash128=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%16,l=e.length-r,u=t,h=t,d=t,p=t,f=0,g=0,y=0,m=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},s.x64.hash128=function(e,t){if(s.inputValidation&&!i(e))return n;t=t||0;for(var r=e.length%16,o=e.length-r,a=[0,t],c=[0,t],g=[0,0],y=[0,0],m=[2277735313,289559509],b=[1291169091,658871167],w=0;w>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)+("00000000"+(c[0]>>>0).toString(16)).slice(-8)+("00000000"+(c[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=s),t.murmurHash3=s}()},5507:function(e,t){(function(){var e,r,n,s,i,o,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,s,i,o,a;for(t=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw new 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 new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new 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 new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},s=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),i=n("A"),r=function(e){var t,r,a,c,l;for(c=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")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-i)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new 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)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(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(c(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(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},9504:(e,t,r)=>{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!1,mode:n});return s.start(t),s},n.aes.createEncryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var s=g({key:e,output:r,decrypt:!0,mode:n});return s.start(t),s},n.aes.createDecryptionCipher=function(e,t){return g({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.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){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var s=0;s>>=2,s=0;s>8^255&h^99,i[g]=h,o[h]=g,p=(d=e[h])<<24^h<<16^h<<8^h^d,f=((r=e[g])^(n=e[r])^(s=e[n]))<<24^(g^s)<<16^(g^n^s)<<8^g^r^s;for(var m=0;m<4;++m)c[m][g]=p,l[m][h]=f,p=p<<24|p>>>8,f=f<<24|f>>>8;0===g?g=y=1:(g=r^e[e[e[r^s]]],y^=e[e[y]])}}function p(e,t){for(var r,n=e.slice(0),s=1,o=n.length,c=h*(o+6+1),u=o;u>>16&255]<<24^i[r>>>8&255]<<16^i[255&r]<<8^i[r>>>24]^a[s]<<24,s++):o>6&&u%o==4&&(r=i[r>>>24]<<24^i[r>>>16&255]<<16^i[r>>>8&255]<<8^i[255&r]),n[u]=n[u-o]^r;if(t){for(var d,p=l[0],f=l[1],g=l[2],y=l[3],m=n.slice(0),b=(u=0,(c=n.length)-h);u>>24]]^f[i[d>>>16&255]]^g[i[d>>>8&255]]^y[i[255&d]];n=m}return n}function f(e,t,r,n){var s,a,u,h,d,p,f,g,y,m,b,w,v=e.length/4-1;n?(s=l[0],a=l[1],u=l[2],h=l[3],d=o):(s=c[0],a=c[1],u=c[2],h=c[3],d=i),p=t[0]^e[0],f=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S>>24]^a[f>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],b=s[f>>>24]^a[g>>>16&255]^u[y>>>8&255]^h[255&p]^e[++E],w=s[g>>>24]^a[y>>>16&255]^u[p>>>8&255]^h[255&f]^e[++E],y=s[y>>>24]^a[p>>>16&255]^u[f>>>8&255]^h[255&g]^e[++E],p=m,f=b,g=w;r[0]=d[p>>>24]<<24^d[f>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[n?3:1]=d[f>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&p]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[p>>>8&255]<<8^d[255&f]^e[++E],r[n?1:3]=d[y>>>24]<<24^d[p>>>16&255]<<16^d[f>>>8&255]<<8^d[255&g]^e[++E]}function g(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},2746:(e,t,r)=>{var n=r(276);r(7619),r(6418);var s=e.exports=n.asn1=n.asn1||{};function i(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}function o(e,t,r,n){var a;i(e,t,2);var c=e.getByte();t--;var l=192&c,u=31&c;a=e.length();var h,d,p=function(e,t){var r=e.getByte();if(t--,128!==r){var n;if(128&r){var s=127&r;i(e,t,s),n=e.getInt(s<<3)}else n=r;if(n<0)throw new Error("Negative length: "+n);return n}}(e,t);if(t-=a-e.length(),void 0!==p&&p>t){if(n.strict){var f=new Error("Too few bytes to read ASN.1 value.");throw f.available=e.length(),f.remaining=t,f.requested=p,f}p=t}var g=!(32&~c);if(g)if(h=[],void 0===p)for(;;){if(i(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;p>0;)a=e.length(),h.push(o(e,p,r+1,n)),t-=a-e.length(),p-=a-e.length();if(void 0===h&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&(d=e.bytes(p)),void 0===h&&n.decodeBitStrings&&l===s.Class.UNIVERSAL&&u===s.Type.BITSTRING&&p>1){var y=e.read,m=t,b=0;if(u===s.Type.BITSTRING&&(i(e,t,1),b=e.getByte(),t--),0===b)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),v=a-e.length();t-=v,u==s.Type.BITSTRING&&v++;var E=w.tagClass;v!==p||E!==s.Class.UNIVERSAL&&E!==s.Class.CONTEXT_SPECIFIC||(h=[w])}catch(e){}void 0===h&&(e.read=y,t=m)}if(void 0===h){if(void 0===p){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");p=t}if(u===s.Type.BMPSTRING)for(h="";p>0;p-=2)i(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(p),t-=p}var S=void 0===d?null:{bitStringContents:d};return s.create(l,u,g,h,S)}s.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},s.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},s.create=function(e,t,r,i,o){if(n.util.isArray(i)){for(var a=[],c=0;c1)||(0!==e.value.charCodeAt(0)||128&e.value.charCodeAt(1))&&(255!==e.value.charCodeAt(0)||128&~e.value.charCodeAt(1))?i.putBytes(e.value):i.putBytes(e.value.substr(1));if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);for(t.putByte(128|l.length),a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(i),t},s.oidToDer=function(e){var t,r,s,i,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c>>=7,t||(i|=128),r.push(i),t=!1}while(s>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},s.derToOid=function(e){var t;"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var s=0;e.length()>0;)s<<=7,128&(r=e.getByte())?s+=127&r:(t+="."+(s+r),s=0);return t},s.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,s=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},s.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,s=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);return"+"!==d&&"-"!==d||(l=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),l*=6e4,"+"===d&&(l*=-1),u=!0),"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,s),t.setUTCHours(i,o,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,s),t.setHours(i,o,a,c)),t},s.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=-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=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},s.derToInteger=function(e){"string"==typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},s.validate=function(e,t,r,i){var o=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)i&&(e.tagClass!==t.tagClass&&i.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&i.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c0&&(i+="\n");for(var o="",c=0;c1?i+="0x"+n.util.bytesToHex(e.value.slice(1)):i+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?i+=" (1 unused bit shown)":d>1&&(i+=" ("+d+" unused bits shown)")}}else if(e.type===s.Type.OCTETSTRING)a.test(e.value)||(i+="("+e.value+") "),i+="0x"+n.util.bytesToHex(e.value);else if(e.type===s.Type.UTF8)try{i+=n.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;i+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===s.Type.PRINTABLESTRING||e.type===s.Type.IA5String?i+=e.value:a.test(e.value)?i+="0x"+n.util.bytesToHex(e.value):0===e.value.length?i+="[null]":i+=e.value}return i}},4058:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!=typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var s=0,i=t.length,o=t.charAt(0),a=[0];for(s=0;s0;)a.push(l%i),l=l/i|0}for(s=0;0===e[s]&&s=0;--s)n+=t[a[s]]}else n=function(e,t){var r=0,n=t.length,s=t.charAt(0),i=[0];for(r=0;r0;)i.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var s=0;s>=8;for(;u>0;)a.push(255&u),u>>=8}for(var h=0;e[h]===o&&h{var n=r(276);r(7619),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 new 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 new 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 s=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)};s.prototype.start=function(e){e=e||{};var t={};for(var r in 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)},s.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()},s.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)))}},6370:(e,t,r)=>{var n=r(276);r(7619),n.cipher=n.cipher||{};var s=e.exports=n.cipher.modes=n.cipher.modes||{};function i(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 s=0;s0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},s.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},s.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2||(e.truncate(n),0))},s.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=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.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=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0)e.read-=this.blockSize;else for(s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},s.ofb.prototype.decrypt=s.ofb.prototype.encrypt,s.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=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},s.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=i(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},s.ctr.prototype.decrypt=s.ctr.prototype.encrypt,s.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},s.gcm.prototype.start=function(e){if(!("iv"in e))throw new 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(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var s=r.length();if(12===s)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*s)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var i=t.length()%this.blockSize;for(i&&t.fillWithByte(0,this.blockSize-i),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()])},s.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 s=0;s0&&(i=this.blockSize-i),this._partialOutput.clear(),s=0;s0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!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)},s.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))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 s=0;s0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},s.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,s=this._m[r][n];t[0]^=s[0],t[1]^=s[1],t[2]^=s[2],t[3]^=s[3]}return t},s.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)},s.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,s=16*r,i=new Array(s),o=0;o>>1,s=new Array(r);s[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(s[2*i],s[i]=[]),i>>=1;for(i=2;i{var n=r(276);function s(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3900),r(6370),r(7619),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var s=f({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},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 s=f({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return s.start(t),s},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 new 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],s=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[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],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],f=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,v=0;v>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27);var A=r[(E&=-15)>>>28]|n[E>>>24&15]|s[E>>>20&15]|i[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],I=l[(S&=-15)>>>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=65535&(I>>>16^A),m[w++]=A^t,m[w++]=I^t<<16}}return m}(t),this._init=!0}},s("DES-ECB",n.cipher.modes.ecb),s("DES-CBC",n.cipher.modes.cbc),s("DES-CFB",n.cipher.modes.cfb),s("DES-OFB",n.cipher.modes.ofb),s("DES-CTR",n.cipher.modes.ctr),s("3DES-ECB",n.cipher.modes.ecb),s("3DES-CBC",n.cipher.modes.cbc),s("3DES-CFB",n.cipher.modes.cfb),s("3DES-OFB",n.cipher.modes.ofb),s("3DES-CTR",n.cipher.modes.ctr);var i=[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],c=[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],l=[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 s,p,f=32===e.length?3:9;s=3===f?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(p=252645135&(g>>>4^y))<<4,g^=(p=65535&(g>>>16^(y^=p)))<<16,g^=p=858993459&((y^=p)>>>2^g),g^=p=16711935&((y^=p<<2)>>>8^g),g=(g^=(p=1431655765&(g>>>1^(y^=p<<8)))<<1)<<1|g>>>31,y=(y^=p)<<1|y>>>31;for(var m=0;m>>4|y<<28)^e[v+1];p=g,g=y,y=p^(o[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|d[63&E]|i[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|h[63&S])}p=g,g=y,y=p}y=y>>>1|y<<31,y^=p=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(p=16711935&(y>>>8^(g^=p<<1)))<<8,y^=(p=858993459&(y>>>2^(g^=p)))<<2,y^=p=65535&((g^=p)>>>16^y),y^=p=252645135&((g^=p<<16)>>>4^y),g^=p<<4,r[0]=g,r[1]=y}function f(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),s=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var i=null;r instanceof n.util.ByteBuffer&&(i=r,r={}),(r=r||{}).output=i,r.iv=e,s.call(t,r)},t}},276:e=>{e.exports={options:{usePureJavaScript:!1}}},1696:(e,t,r)=>{var n=r(276);r(8106),r(7619),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,s=null,i={start:function(i,o){if(null!==i)if("string"==typeof i){if(!((i=i.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+i+'"');t=n.md.algorithms[i].create()}else t=i;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 c=0;ct.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),s=n.util.createBuffer(),l=o.length(),c=0;c{var n,s=r(276);function i(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 o(){return new i(null)}function a(e,t,r,n,s,i){for(var o=16383&t,a=t>>14;--i>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*o;s=((c=o*c+((16383&u)<<14)+r.data[n]+s)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return s}e.exports=s.jsbn=s.jsbn||{},s.jsbn.BigInteger=i,"undefined"==typeof navigator?(i.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(var o=32767&t,a=t>>15;--i>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*o;s=((c=o*c+((32767&u)<<15)+r.data[n]+(1073741823&s))>>>30)+(u>>>15)+a*l+(s>>>30),r.data[n++]=1073741823&c}return s},n=30):"Netscape"!=navigator.appName?(i.prototype.am=function(e,t,r,n,s,i){for(;--i>=0;){var o=t*this.data[e++]+r.data[n]+s;s=Math.floor(o/67108864),r.data[n++]=67108863&o}return s},n=26):(i.prototype.am=a,n=28),i.prototype.DB=n,i.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function A(e){return e}function I(e){this.r2=o(),this.q3=o(),i.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(i.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},i.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},i.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},i.prototype.fromString=function(e,t){var r;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)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==r?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-o):this.data[this.t-1]|=a<=this.DB&&(o-=this.DB))}8==r&&128&e[0]&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},i.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},i.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>s|a,a=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},i.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,s=this.DB-n,i=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=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()},i.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),s=r.t;for(t.t=s+n.t;--s>=0;)t.data[s]=0;for(s=0;s=0;)e.data[r]=0;for(r=0;r=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()},i.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var s=this.abs();if(s.t0?(n.lShiftTo(u,a),s.lShiftTo(u,r)):(n.copyTo(a),s.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var p=d*(1<1?a.data[h-2]>>this.F2:0),g=this.FV/p,y=(1<=0&&(r.data[r.t++]=1,r.subTo(v,r)),i.ONE.dlShiftTo(h,v),v.subTo(a,a);a.t=0;){var E=r.data[--b]==d?this.DM:Math.floor(r.data[b]*g+(r.data[b-1]+m)*y);if((r.data[b]+=a.am(0,E,r,w,0,h))0&&r.rShiftTo(u,r),c<0&&i.ZERO.subTo(r,r)}}},i.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(!(1&e))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},i.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},i.prototype.exp=function(e,t){if(e>4294967295||e<1)return i.ONE;var r=o(),n=o(),s=t.convert(this),a=f(e)-1;for(s.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,s,r);else{var c=r;r=n,n=c}return t.revert(r)},i.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;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 r,n=(1<0)for(a>a)>0&&(s=!0,i=h(r));o>=0;)a>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(s=!0),s&&(i+=h(r));return s?i:"0"},i.prototype.negate=function(){var e=o();return i.ZERO.subTo(this,e),e},i.prototype.abs=function(){return this.s<0?this.negate():this},i.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},i.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+f(this.data[this.t-1]^this.s&this.DM)},i.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(i.ZERO)>0&&e.subTo(t,t),t},i.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},i.ZERO=p(0),i.ONE=p(1),_.prototype.convert=A,_.prototype.revert=A,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},I.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},I.prototype.revert=function(e){return e},I.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);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},I.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},I.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var k=[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],R=(1<<26)/k[k.length-1];i.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},i.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),s=o(),i=o(),a="";for(this.divRemTo(n,s,i);s.signum()>0;)a=(r+i.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,i);return i.intValue().toString(e)+a},i.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),s=!1,o=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),s&&i.ZERO.subTo(this,this)},i.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(i.ONE.shiftLeft(e-1),b,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(i.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),t.nextBytes(n),s>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=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()},i.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},i.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]}},i.prototype.multiplyLowerTo=function(e,t,r){var n,s=Math.min(this.t+e.t,t);for(r.s=0,r.t=s;s>0;)r.data[--s]=0;for(n=r.t-this.t;s=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)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},i.prototype.millerRabin=function(e){var t=this.subtract(i.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,s=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(s,this);if(0!=c.compareTo(i.ONE)&&0!=c.compareTo(t)){for(var l=1;l++>24},i.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},i.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},i.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,s=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[s++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(t[s++]=r);return t},i.prototype.equals=function(e){return 0==this.compareTo(e)},i.prototype.min=function(e){return this.compareTo(e)<0?this:e},i.prototype.max=function(e){return this.compareTo(e)>0?this:e},i.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},i.prototype.or=function(e){var t=o();return this.bitwiseTo(e,b,t),t},i.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,w,t),t},i.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,v,t),t},i.prototype.not=function(){for(var e=o(),t=0;t=this.t?0!=this.s:!!(this.data[t]&1<1){var h=o();for(n.sqrTo(a[1],h);c<=u;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,m,b=e.t-1,w=!0,v=o();for(s=f(e.data[b])-1;b>=0;){for(s>=l?d=e.data[b]>>s-l&u:(d=(e.data[b]&(1<0&&(d|=e.data[b-1]>>this.DB+s-l)),c=r;!(1&d);)d>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),w)a[d].copyTo(i),w=!1;else{for(;c>1;)n.sqrTo(i,v),n.sqrTo(v,i),c-=2;c>0?n.sqrTo(i,v):(m=i,i=v,v=m),n.mulTo(v,a[d],i)}for(;b>=0&&!(e.data[b]&1<=0?(r.subTo(n,r),t&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(i.ONE)?i.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},i.prototype.pow=function(e){return this.exp(e,new _)},i.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var s=t.getLowestSetBit(),i=r.getLowestSetBit();if(i<0)return t;for(s0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(s=t.getLowestSetBit())>0&&t.rShiftTo(s,t),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r},i.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=k[k.length-1]){for(t=0;t{var n=r(276);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},6418:(e,t,r)=>{var n=r(276);n.pki=n.pki||{};var s=e.exports=n.pki.oids=n.oids=n.oids||{};function i(e,t){s[e]=t,s[t]=e}function o(e,t){s[e]=t}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")},2698:(e,t,r)=>{var n=r(276);if(r(9504),r(2746),r(9095),r(8106),r(6418),r(3254),r(2385),r(9356),r(5124),r(5805),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:i.Class.UNIVERSAL,type:i.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[i.derToOid(e)])){var r=new 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=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new 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 s,c,l,u=n.random.getBytesSync(r.saltSize),h=r.count,d=i.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var f,g,y;switch(r.algorithm){case"aes128":s=16,f=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":s=24,f=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":s=32,f=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":s=8,f=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),b=p(m),w=n.pkcs5.pbkdf2(t,u,h,s,b),v=n.random.getBytesSync(f);(_=y(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,s){var a=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,e),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,t.getBytes())]);return"hmacWithSHA1"!==s&&a.value.push(i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(o.oids[s]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.NULL,!1,"")])),a}(u,d,s,m);c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBES2).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(g).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,v)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;s=24;var _,A=new n.util.ByteBuffer(u);w=o.pbe.generatePkcs12Key(t,A,1,h,s),v=o.pbe.generatePkcs12Key(t,A,2,h,s),(_=n.des.createEncryptionCipher(w)).start(v),_.update(i.toDer(e)),_.finish(),l=_.output.getBytes(),c=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,u),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,d.getBytes())])])}return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[c,i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,l)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,s={},a=[];if(!i.validate(e,c,s,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=i.derToOid(s.encryptionOid),h=o.pbe.getCipher(u,s.encryptionParams,t),d=n.util.createBuffer(s.encryptedData);return h.update(d),h.finish()&&(r=i.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:i.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=new 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 new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return i.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var s=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return s=o.encryptPrivateKeyInfo(s,t,r),o.encryptedPrivateKeyToPem(s)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));d.start(c),d.update(i.toDer(o.privateKeyToAsn1(e))),d.finish();var p={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(p)},o.decryptRsaPrivateKey=function(e,t){var r=null,s=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==s.type&&"PRIVATE KEY"!==s.type&&"RSA PRIVATE KEY"!==s.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(s.procType&&"ENCRYPTED"===s.procType.type){var a,c;switch(s.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+s.dekInfo.algorithm+'".')).algorithm=s.dekInfo.algorithm,l}var u=n.util.hexToBytes(s.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(h.start(u),h.update(n.util.createBuffer(s.body)),!h.finish())return r;r=h.output.getBytes()}else r=s.body;return null!==(r="ENCRYPTED PRIVATE KEY"===s.type?o.decryptPrivateKeyInfo(i.fromDer(r),t):i.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,s,i,o){var a,c;if(null==o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var l=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!=e){for(c=0;c=0;c--)C>>=8,C+=I.at(c)+T.at(c),T.setAt(c,255&C);R.putBuffer(T)}v=R,h.putBuffer(_)}return h.truncate(h.length()-i),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=new 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 s,a={},c=[];if(!i.validate(t,l,a,c))throw(s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,s;if((e=i.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,s.supportedOids=["pkcs5PBKDF2"],s;if((e=i.derToOid(a.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)throw(s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s;var u,h,p=a.kdfSalt,f=n.util.createBuffer(a.kdfIterationCount);switch(f=f.getInt(f.length()<<3),o.oids[e]){case"aes128-CBC":u=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,h=n.des.createDecryptionCipher;break;case"desCBC":u=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),y=n.pkcs5.pbkdf2(r,p,f,u,g),m=a.encIv,b=h(y);return b.start(m),b},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var s={},a=[];if(!i.validate(t,u,s,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,h,p=n.util.createBuffer(s.salt),f=n.util.createBuffer(s.iterations);switch(f=f.getInt(f.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=d(s.prfOid),m=o.pbe.generatePkcs12Key(r,p,1,f,c,y);return y.start(),h(m,o.pbe.generatePkcs12Key(r,p,2,f,l,y))},o.pbe.opensslDeriveBytes=function(e,t,r,s){if(null==s){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');s=n.md.md5.create()}null===t&&(t="");for(var i=[h(s,e+t)],o=16,a=1;o{var n=r(276);r(1696),r(8106),r(7619);var s,i=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(s=r(310)),e.exports=n.pbkdf2=i.pbkdf2=function(e,t,r,i,o,a){if("function"==typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&s.pbkdf2&&(null===o||"object"!=typeof o)&&(s.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!=typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===s.pbkdf2Sync.length?s.pbkdf2(e,t,r,i,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):s.pbkdf2(e,t,r,i,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===s.pbkdf2Sync.length?s.pbkdf2Sync(e,t,r,i).toString("binary"):s.pbkdf2Sync(e,t,r,i,o).toString("binary");if(null==o&&(o="sha1"),"string"==typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(i>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(i/c),h=i-(u-1)*c,d=n.hmac.create();d.start(o,e);var p,f,g,y="";if(!a){for(var m=1;m<=u;++m){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes();for(var b=2;b<=r;++b)d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f;y+=mu)return a(null,y);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),p=g=d.digest().getBytes(),b=2,v()}function v(){if(b<=r)return d.start(null,null),d.update(g),f=d.digest().getBytes(),p=n.util.xorBytes(p,f,c),g=f,++b,n.util.setImmediate(v);y+=m{var n=r(276);r(7619);var s=e.exports=n.pem=n.pem||{};function i(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},s=0;s65&&-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),i=s-o-1,o=-1,++s}else" "!==t[s]&&"\t"!==t[s]&&","!==t[s]||(o=s);return t}function o(e){return e.replace(/^\s+/,"")}s.encode=function(e,t){t=t||{};var r,s="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(s+=i(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(s+=i(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),s+=i(r)),e.headers)for(var o=0;o{var n=r(276);r(7619),r(9356),r(1598);var s=e.exports=n.pkcs1=n.pkcs1||{};function i(e,t,r){r||(r=n.md.sha1.create());for(var s="",i=Math.ceil(t/r.digestLength),o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),s+=r.digest().getBytes()}return s.substring(0,t)}s.encode_rsa_oaep=function(e,t,r){var s,o,a,c;"string"==typeof r?(s=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(s=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;s||(s=""),a.update(s,"raw");for(var h=a.digest(),d="",p=u-t.length,f=0;f{var n=r(276);r(7619),r(3736),r(9356),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,s=[6,4,2,4,2,4,6,2],i=new r(null);i.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,s){"function"==typeof t&&(s=t,t={});var i=(t=t||{}).algorithm||"PRIMEINC";"string"==typeof i&&(i={name:i}),i.options=i.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;re&&(o=l(e,t));var p=o.toString(16);s.target.postMessage({hex:p,workLoad:u}),o.dAddOffset(h,0)}}}p()}(e,t,s,i):a(e,t,s,i)}(e,c,i.options,s);throw new Error("Invalid prime generation algorithm: "+i.name)}}function a(e,t,r,n){var s=l(e,t),i=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(s.bitLength());"millerRabinTests"in r&&(i=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(s,e,t,0,i,o,n)}function c(e,t,r,i,o,a,u){var h=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(s[i++%8],0)}while(a<0||+new Date-h{var n=r(276);r(7619);var s=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(s=r(310)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,i=new Array(32),o=0;o<32;++o)i[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){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 s=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(s),t.generated=0}function l(e){var t=null,r=n.util.globalScope,s=r.crypto||r.msCrypto;s&&s.getRandomValues&&(t=function(e){return s.getRandomValues(e)});var i=n.util.createBuffer();if(t)for(;i.length()>16)))<<16,d=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31)),c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),i.putByte(255&h);return i.getBytes(e)}return t.pools=i,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var s=t.plugin.cipher,i=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(l.length()>=e)return r(null,l.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var d=s(t.key,t.seed);t.generated+=d.length,l.putBytes(d),t.key=o(s(t.key,i(t.seed))),t.seed=a(s(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,s=t.plugin.increment,i=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=i(r(t.key,s(t.seed))),t.seed=o(r(t.key,t.seed))}return c.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>s&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}},9356:(e,t,r)=>{var n=r(276);r(9504),r(172),r(3878),r(7619),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},s=new Array(4),i=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=new Array(4))[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=new Array(4))[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,s,!1),i.putInt32(s[0]),i.putInt32(s[1]),i.putInt32(s[2]),i.putInt32(s[3]),i.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){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)},5124:(e,t,r)=>{var n=r(276);r(7619);var s=[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],i=[1,2,3,5],o=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};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,i=e,o=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=o;r<128;r++)i.putByte(s[i.at(r-1)+i.at(r-o)&255]);for(i.setAt(128-c,s[i.at(128-c)&l]),r=127-c;r>=0;r--)i.setAt(r,s[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var s,c,l,u,h=!1,d=null,p=null,f=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(s=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=o(e[l],i[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(s=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],i[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=d.getInt16Le();null!==f&&(r?n^=f.getInt16Le():f.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var s=0;s=8;)y([[5,s],[1,c],[6,s],[1,c],[5,s]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,m.update()),!r&&(t=0===d.length()))if(e)t=e(8,p,!r);else{var s=p.length(),i=p.at(s-1);i>s?t=!1:p.truncate(i)}return t}}};n.rc2.startEncrypting=function(e,t,r){var s=n.rc2.createEncryptionCipher(e,128);return s.start(t,r),s},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var s=n.rc2.createDecryptionCipher(e,128);return s.start(t,r),s},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5805:(e,t,r)=>{var n=r(276);if(r(2746),r(3736),r(6418),r(7501),r(268),r(9356),r(7619),void 0===s)var s=n.jsbn.BigInteger;var i=n.util.isNodejs?r(310):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[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){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);i.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),i.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 s.value.push(i),s.value.push(a),o.toDer(s).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var i;t.dP||(t.dP=t.d.mod(t.p.subtract(s.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(s.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{i=new s(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(i.compareTo(t.n)>=0||!i.gcd(t.n).equals(s.ONE));for(var o=(e=e.multiply(i.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);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c.multiply(i.modInverse(t.n)).mod(t.n)};function m(e,t,r){var s=n.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}s.putByte(0),s.putByte(r);var a,c=i-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l0;){var u=0,h=n.random.getBytes(c);for(l=0;l1;){if(255!==o.getByte()){--o.read;break}++l}else if(2===c)for(l=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++l}if(0!==o.getByte()||l!==i-3-o.length())throw new 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))&&(255!==r.charCodeAt(0)||128&~r.charCodeAt(1))?r:r.substr(1)}function v(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function E(e){return n.util.isNodejs&&"function"==typeof i[e]}function S(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 _(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),s=0;s0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,i){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new s(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),!1!==i?b(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var i,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(i.eInt),i},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new s(null);r.fromInt(30);for(var n,i=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||uh?e.pqState=0:e.num.isProbablePrime(v(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[i++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(s.ONE).gcd(e.e).compareTo(s.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)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(s.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 p=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,l){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(l=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(l=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,l=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(l=r,r=void 0):(l=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(l){if(E("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return l(e);l(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(S("generateKey")&&S("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){l(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));l(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(_("generateKey")&&_("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"]);return 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=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));l(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){l(e)}},void(u.onerror=function(e){l(e)})}}else if(E("generateKeyPairSync")){var h=i.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(h.privateKey),publicKey:c.publicKeyFromPem(h.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!l)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;!function(e,t,r){"function"==typeof t&&(r=t,t={});var i={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?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,i,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var i=e.p;e.p=e.q,e.q=i}if(0!==e.p.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.p=null,void o();if(0!==e.q.subtract(s.ONE).gcd(e.e).compareTo(s.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(s.ONE),e.q1=e.q.subtract(s.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(s.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.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:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(i.prng=t.prng),o()}(d,r,l)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,s){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,s)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return c.rsa.encrypt(i,r,!0)},verify:function(e,t,s,i){"string"==typeof s?s=s.toUpperCase():void 0===s&&(s="RSASSA-PKCS1-V1_5"),void 0===i&&(i={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in i||(i._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===s?s={verify:function(e,t){t=b(t,r,!0);var s=o.fromDer(t,{parseAllBytes:i._parseAllDigestBytes}),a={},c=[];if(!o.validate(s,f,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,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"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new 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"!==s&&"NULL"!==s&&null!==s||(s={verify:function(e,t){return e===b(t,r,!0)}});var a=c.rsa.decrypt(t,r,!0,!1);return s.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,s,i,o,a,l){var u={n:e,e:t,d:r,p:s,q:i,dP:o,dQ:a,qInv:l,decrypt:function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var s=c.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))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(s,u,!1)},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 c.rsa.encrypt(n,u,r)}};return u},c.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(c.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())])},c.privateKeyFromAsn1=function(e){var t,r,i,a,l,d,p,f,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),i=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=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(),c.setRsaPrivateKey(new s(t,16),new s(r,16),new s(i,16),new s(a,16),new s(l,16),new s(d,16),new s(p,16),new s(f,16))},c.privateKeyToAsn1=c.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))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,p,t,r)){var i,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(i=new Error("Cannot read public key. Unknown OID.")).oid=a,i;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(i=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,i;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new s(l,16),new s(u,16))},c.publicKeyToAsn1=c.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(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.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))])}},1598:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),s={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i>>0,c>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=c[1],c[1]=c[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(i),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=c>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);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},s};var i=null,o=!1;function a(e,t,r){for(var n,s,i,o,a,c,l,u=r.length();u>=64;){for(s=e.h0,i=e.h1,o=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(a^i&(o^a))+c+1518500249+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+1859775393+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i&o|a&(i^o))+c+2400959708+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(s<<5|s>>>27)+(i^o^a)+c+3395469782+n,c=a,a=o,o=(i<<30|i>>>2)>>>0,i=s,s=n;e.h0=e.h0+s|0,e.h1=e.h1+i|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},172:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=s,s.create=function(){o||(i=String.fromCharCode(128),i+=n.util.fillString(String.fromCharCode(0),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=new Array(64),s={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,i=0;i>>0,a>>>0];for(var l=s.fullMessageLength.length-1;l>=0;--l)s.fullMessageLength[l]+=a[1],a[1]=a[0]+(s.fullMessageLength[l]/4294967296>>>0),s.fullMessageLength[l]=s.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(i),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,l=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize&s.blockLength-1;o.putBytes(i.substr(0,s.blockLength-l));for(var u=8*s.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=a>>>0;o.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};c(d,r,o);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},s};var i=null,o=!1,a=null;function c(e,t,r){for(var n,s,i,o,c,l,u,h,d,p,f,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,s=((s=t[c-15])>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,t[c]=n+t[c-7]+s+t[c-16]|0;for(l=e.h0,u=e.h1,h=e.h2,d=e.h3,p=e.h4,f=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)i=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),o=l&u|h&(l^u),n=y+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(g^p&(f^g))+a[c]+t[c],y=g,g=f,f=p,p=d+n>>>0,d=h,h=u,u=l,l=n+(s=i+o)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+p|0,e.h5=e.h5+f|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},2313:(e,t,r)=>{var n=r(276);r(8106),r(7619);var s=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=s;var i=n.sha384=n.sha512.sha384=n.sha512.sha384||{};i.create=function(){return s.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=i,n.sha512.sha256=n.sha512.sha256||{create:function(){return s.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 s.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,s.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[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]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["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 l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,s=n.util.createBuffer(),i=new Array(80),h=0;h<80;++h)i[h]=new Array(2);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,start:function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,i=0;i>>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 s.putBytes(e),u(r,i,s),(s.read>2048||0===s.length())&&s.compact(),p},p.digest=function(){var t=n.util.createBuffer();t.putBytes(s.bytes());var a,c=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;t.putBytes(o.substr(0,p.blockLength-c));for(var l=8*p.fullMessageLength[0],h=0;h>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var d=new Array(r.length);for(h=0;h=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((B=(N=t[P-2])[0])>>>19|(D=N[1])<<13)^(D>>>29|B<<3)^B>>>6)>>>0,s=((B<<13|D>>>19)^(D<<3|B>>>29)^(B<<26|D>>>6))>>>0,i=(((B=(L=t[P-15])[0])>>>1|(D=L[1])<<31)^(B>>>8|D<<24)^B>>>7)>>>0,o=((B<<31|D>>>1)^(B<<24|D>>>8)^(B<<25|D>>>7))>>>0,x=t[P-7],O=t[P-16],D=s+x[1]+o+O[1],t[P][0]=n+x[0]+i+O[0]+(D/4294967296>>>0)>>>0,t[P][1]=D>>>0;for(f=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],b=e[2][0],w=e[2][1],v=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],A=e[5][0],I=e[5][1],k=e[6][0],R=e[6][1],T=e[7][0],C=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,h=(k^S&(A^k))>>>0,a=((f>>>28|g<<4)^(g>>>2|f<<30)^(g>>>7|f<<25))>>>0,l=((f<<4|g>>>28)^(g<<30|f>>>2)^(g<<25|f>>>7))>>>0,d=(f&y|b&(f^y))>>>0,p=(g&m|w&(g^m))>>>0,D=C+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((R^_&(I^R))>>>0)+c[P][1]+t[P][1],n=T+u+h+c[P][0]+t[P][0]+(D/4294967296>>>0)>>>0,s=D>>>0,i=a+d+((D=l+p)/4294967296>>>0)>>>0,o=D>>>0,T=k,C=R,k=A,R=I,A=S,I=_,S=v+n+((D=E+s)/4294967296>>>0)>>>0,_=D>>>0,v=b,E=w,b=y,w=m,y=f,m=g,f=n+i+((D=s+o)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+f+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+m,e[1][0]=e[1][0]+y+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+w,e[2][0]=e[2][0]+b+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+E,e[3][0]=e[3][0]+v+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+_,e[4][0]=e[4][0]+S+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+I,e[5][0]=e[5][0]+A+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+R,e[6][0]=e[6][0]+k+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+C,e[7][0]=e[7][0]+T+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},7619:(e,t,r)=>{var n=r(276),s=r(4058),i=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)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;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&s.setAttribute("a",n=!n))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?global:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=a,i.ByteStringBuffer=a,i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.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},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.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))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.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))},i.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.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},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.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},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.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},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=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},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.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},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},i.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},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.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},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var n="",s="",i="",o=0,a=0;r>0;--r,++o)s=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=i,i="",a=0),i+=String.fromCharCode(s),++a;return n+i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[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],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,n,s,i="",o="",a=0;a>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,s,i="",o=0;o>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==s&&(i+=String.fromCharCode((3&n)<<6|s)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:s.encode,decode:s.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,i=0;i>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|s>>6),i+=isNaN(s)?"=":c.charAt(63&s)),t&&i.length>t&&(o+=i.substr(0,t)+"\r\n",i=i.substr(t));return o+i},i.binary.base64.decode=function(e,t,r){var n,s,i,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c>4,64!==i&&(a[u++]=(15&s)<<4|i>>2,64!==o&&(a[u++]=(3&i)<<6|o));return t?u-r:a.subarray(0,u)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,u,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,u,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var s=r=r||0,o=0;o0&&i.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":s");break;case"%":i.push("%");break;default:i.push("<%"+a+"?>")}}return i.push(e.substring(o)),i.join("")},i.formatNumber=function(e,t,r,n){var s=e,i=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=s<0?"-":"",l=parseInt(s=Math.abs(+s||0).toFixed(i),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(i?o+Math.abs(s-l).toFixed(i).slice(2):"")},i.formatSize=function(e){return e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&s.sts.st&&a.st{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,s=r(5643),i=r(3262);function o(e,t,r,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof s?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":i=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=i.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=i.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===s.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==s.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==s.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=i.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(i.compareFieldsById),c=0;c>>0,8|s.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==s.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?o(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?o(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),s=r(361),i=r(3262);function o(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var s=r(8923),i=r(3262);function o(e,t,r,s,i,o){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=s,this.comments=i||{},this.valuesOptions=o,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var s,i=r(5643),o=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,i,l,u){if(a.isObject(s)?(u=i,l=s,s=i=void 0):a.isObject(i)&&(u=l,l=i,i=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==s&&!c.test(s=s.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==i&&!a.isString(i))throw TypeError("extend must be a string");"proto3_optional"===s&&(s="optional"),this.rule=s&&"optional"!==s?s:void 0,this.type=r,this.id=t,this.extend=i||void 0,this.required="required"===s,this.optional=!this.required,this.repeated="repeated"===s,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof s?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof i&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof i)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof s&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(s,i){a.decorateType(s.constructor).add(new l(i,e,t,r,{default:n}))}},l._configure=function(e){s=e}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4394:(e,t,r)=>{"use strict";var n=t;function s(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=s,s()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=o;var n=r(1344);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var s=r(361),i=r(3262);function o(e,t,r,s,o,a){if(n.call(this,e,t,s,void 0,void 0,o,a),!i.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===s.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},o.d=function(e,t,r){return"function"==typeof r?r=i.decorateType(r).name:r&&"object"==typeof r&&(r=i.decorateEnum(r).name),function(n,s){i.decorateType(n.constructor).add(new o(s,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Method";var s=r(3262);function i(e,t,r,i,o,a,c,l,u){if(s.isObject(o)?(c=o,o=a=void 0):s.isObject(a)&&(c=a,a=void 0),void 0!==t&&!s.isString(t))throw TypeError("type must be a string");if(!s.isString(r))throw TypeError("requestType must be a string");if(!s.isString(i))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}i.fromJSON=function(e,t){return new i(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},i.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var s,i,o,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var s=0;s{"use strict";e.exports=i,i.className="ReflectionObject";var n,s=r(3262);function i(e,t){if(!s.isString(e))throw TypeError("name must be a string");if(t&&!s.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(i.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),i.prototype.toJSON=function(){throw Error()},i.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},i.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},i.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},i.prototype.getOption=function(e){if(this.options)return this.options[e]},i.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},i.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var i=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(i){var o=i[e];s.setProperty(o,r,t)}else(i={})[e]=s.setProperty({},r,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},i.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var s=r(1344),i=r(3262);function o(e,t,r,s){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=s}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},o.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=A,A.filename=null,A.defaults={keepCase:!1};var n=r(527),s=r(5330),i=r(7882),o=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,_=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function A(e,t,r){t instanceof s||(r=t,t=new s),r||(r=A.defaults);var I,k,R,T,C,P=r.preferTrailingComment||!1,B=n(e,r.alternateCommentMode||!1),D=B.next,N=B.push,x=B.peek,L=B.skip,O=B.cmnt,M=!0,U=!1,K=t,F=r.keepCase?function(e){return e}:p.camelCase;function V(e,t,r){var n=A.filename;return r||(A.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+B.line+")")}function q(){var e,t=[];do{if('"'!==(e=D())&&"'"!==e)throw V(e);t.push(D()),L(e),e=x()}while('"'===e||"'"===e);return t.join("")}function H(e){var t=D();switch(t){case"'":case'"':return N(t),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;switch("-"===e.charAt(0)&&(r=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(b.test(e))return r*parseInt(e,8);if(v.test(e))return r*parseFloat(e);throw V(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw V(t,"value")}}function j(e,t){var r,n;do{!t||'"'!==(r=x())&&"'"!==r?e.push([n=$(D()),L("to",!0)?$(D()):n]):e.push(q())}while(L(",",!0));var s={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)}))}function $(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw V(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw V(e,"id")}function z(){if(void 0!==I)throw V("package");if(I=D(),!S.test(I))throw V(I,"name");K=K.define(I),L(";")}function G(){var e,t=x();switch(t){case"weak":e=R||(R=[]),D();break;case"public":D();default:e=k||(k=[])}t=q(),L(";"),e.push(t)}function W(){if(L("="),T=q(),!(U="proto3"===T)&&"proto2"!==T)throw V(T,"syntax");L(";")}function Y(e,t){switch(t){case"option":return ee(e,t),L(";"),!0;case"message":return J(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=D()))throw V(t,"service name");var r=new u(t);X(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw V(e);!function(e,t){var r=O(),n=t;if(!E.test(t=D()))throw V(t,"name");var s,i,o,a,c=t;if(L("("),L("stream",!0)&&(i=!0),!S.test(t=D()))throw V(t);if(s=t,L(")"),L("returns"),L("("),L("stream",!0)&&(a=!0),!S.test(t=D()))throw V(t);o=t,L(")");var l=new h(c,n,s,o,i,a);l.comment=r,X(l,(function(e){if("option"!==e)throw V(e);ee(l,e),L(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=D()))throw V(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":Q(e,t,r);break;case"optional":Q(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw V(t);N(t),Q(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=B.line;if(e&&("string"!=typeof e.comment&&(e.comment=O()),e.filename=A.filename),L("{",!0)){for(var s;"}"!==(s=D());)t(s);L(";",!0)}else r&&r(),L(";"),e&&("string"!=typeof e.comment||P)&&(e.comment=O(n)||e.comment)}function J(e,t){if(!E.test(t=D()))throw V(t,"type name");var r=new i(t);X(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){L("<");var t=D();if(void 0===d.mapKey[t])throw V(t,"type");L(",");var r=D();if(!S.test(r))throw V(r,"type");L(">");var n=D();if(!E.test(n))throw V(n,"name");L("=");var s=new a(F(n),$(D()),t,r);X(s,(function(e){if("option"!==e)throw V(e);ee(s,e),L(";")}),(function(){ne(s)})),e.add(s)}(r);break;case"required":case"repeated":Q(r,e);break;case"optional":Q(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new c(F(t));X(r,(function(e){"option"===e?(ee(r,e),L(";")):(N(e),Q(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":j(r.extensions||(r.extensions=[]));break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:if(!U||!S.test(e))throw V(e);N(e),Q(r,"optional")}})),e.add(r)}function Q(e,t,r){var n=D();if("group"!==n){for(;n.endsWith(".")||x().startsWith(".");)n+=D();if(!S.test(n))throw V(n,"type");var s=D();if(!E.test(s))throw V(s,"name");s=F(s),L("=");var a=new o(s,$(D()),n,t,r);if(X(a,(function(e){if("option"!==e)throw V(e);ee(a,e),L(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+s);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);U||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=D();if(!E.test(r))throw V(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),L("=");var s=$(D()),a=new i(r);a.group=!0;var c=new o(n,s,r,t);c.filename=A.filename,X(a,(function(e){switch(e){case"option":ee(a,e),L(";");break;case"required":case"repeated":Q(a,e);break;case"optional":Q(a,U?"proto3_optional":"optional");break;case"message":J(a,e);break;case"enum":Z(a,e);break;default:throw V(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=D()))throw V(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),L(";");break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw V(t,"name");L("=");var r=$(D(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(n,(function(e){if("option"!==e)throw V(e);ee(n,e),L(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=L("(",!0);if(!S.test(t=D()))throw V(t,"name");var n,s=t,i=s;r&&(L(")"),i=s="("+s+")",t=x(),_.test(t)&&(n=t.slice(1),s+=t,D())),L("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,i,te(e,s),n)}function te(e,t){if(L("{",!0)){for(var r={};!L("}",!0);){if(!E.test(C=D()))throw V(C,"name");if(null===C)throw V(C,"end of input");var n,s=C;if(L(":",!0),"{"===x())n=te(e,t+"."+C);else if("["===x()){var i;if(n=[],L("[",!0)){do{i=H(!0),n.push(i)}while(L(",",!0));L("]"),void 0!==i&&re(e,t+"."+C,i)}}else n=H(!0),re(e,t+"."+C,n);var o=r[s];o&&(n=[].concat(o).concat(n)),r[s]=n,L(",",!0),L(";",!0)}return r}var a=H(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(L("[",!0)){do{ee(e,"option")}while(L(",",!0));L("]")}return e}for(;null!==(C=D());)switch(C){case"package":if(!M)throw V(C);z();break;case"import":if(!M)throw V(C);G();break;case"syntax":if(!M)throw V(C);W();break;case"option":ee(K,C),L(";");break;default:if(Y(K,C)){M=!1;continue}throw V(C)}return A.filename=null,{package:I,imports:k,weakImports:R,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),i=s.LongBits,o=s.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return s.Buffer?function(e){return(c.create=function(e){return s.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(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}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;if(t=0,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 a(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")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new i(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=s.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(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},c._configure=function(e){n=e,c.create=h(),n._configure();var t=s.Long?"toLong":"toNumber";s.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3158:(e,t,r)=>{"use strict";e.exports=i;var n=r(6237);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(e){n.call(this,e)}i._configure=function(){s.Buffer&&(i.prototype._slice=s.Buffer.prototype.slice)},i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},i._configure()},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var s,i,o,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var s=this;if(!n)return u.asPromise(e,s,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){i.filename=e;var n,o=i(t,s,r),h=0;if(o.imports)for(;h-1))if(s.files.push(e),e in o)a?h(e,o[e]):(++f,setTimeout((function(){--f,h(e,o[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,s.fetch(e,(function(r,i){--f,n&&(r?t?f||c(null,s):c(r):h(e,i))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-1&&this.deferred.splice(t,1)}}else if(e instanceof c)p.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(s.prototype=Object.create(n.EventEmitter.prototype)).constructor=s,s.prototype.rpcCall=function e(t,r,s,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,s,i);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){o(e)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},s.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var s=r(8811),i=r(3262),o=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),i=0;i{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,s=/^ *[*/]+ */,i=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(o),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var s=t.exec(e);if(!s)throw m("string");return l=t.lastIndex,_(y),y=null,u(s[1])}();var s,i,o,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(o=b(l));)if("\n"===o&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw m("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,s=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,s=!0}else{if("*"!==(o=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===o&&++d,++l===h)throw m("comment");i=o,o=b(l)}while("*"!==i||"/"!==o);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var A=l;if(t.lastIndex=0,!t.test(b(A++)))for(;A{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var s=r(5643),i=r(1457),o=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),y=r(744),m=r(6434);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,s=r(3262),i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,s,i=e.exports=r(3610),o=r(4529);i.codegen=r(8561),i.fetch=r(5212),i.path=r(9207),i.fs=i.inquire("fs"),i.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[s]=e(t[s]||{},r,n);else{var i=t[s];i&&(n=[].concat(i).concat(n)),t[s]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=s.zero=new s(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var o=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var 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 s(r,n)},s.from=function(e){if("number"==typeof e)return s.fromNumber(e);if(n.isString(e)){if(!n.Long)return s.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new s(e.low>>>0,e.high>>>0):i},s.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},s.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;s.fromHash=function(e){return e===o?i:new s((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},s.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},s.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},s.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},s.prototype.length=function(){var 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}},3610:function(e,t,r){"use strict";var n=t;function s(e,t,r){for(var n=Object.keys(t),s=0;s0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=s,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=i,n.ProtocolError=i("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=function(e){var t=s.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n{"use strict";var n=t,s=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var i=this.lookup(n);i&&(e=i.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var o=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),o["@type"]=n,o}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),i=s.LongBits,o=s.base64,a=s.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return s.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;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 y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,i.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=i.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=i.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var m=s.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(p,1,0);if(s.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return 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 c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},818:(e,t,r)=>{"use strict";e.exports=i;var n=r(3449);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(){n.call(this)}function o(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}i._configure=function(){i.alloc=s._Buffer_allocUnsafe,i.writeBytesBuffer=s.Buffer&&s.Buffer.prototype instanceof Uint8Array&&"set"===s.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},i._configure()},152:(e,t)=>{"use strict";class r{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 new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let e=0;e{},310:()=>{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>Ee});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>Se,base16upper:()=>_e});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>Ae});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>Te});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>Ce,base32hex:()=>Ne,base32hexpad:()=>Le,base32hexpadupper:()=>Oe,base32hexupper:()=>xe,base32pad:()=>Be,base32padupper:()=>De,base32upper:()=>Pe,base32z:()=>Me});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base36:()=>Ue,base36upper:()=>Ke});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base58btc:()=>Fe,base58flickr:()=>Ve});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>qe,base64pad:()=>He,base64url:()=>je,base64urlpad:()=>$e});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>ze});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Ge});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Je,decode:()=>Ze,encode:()=>Qe,name:()=>Xe});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>tt,decode:()=>nt,encode:()=>rt,name:()=>et});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>kt});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>Pt,sha512:()=>Bt});var f={};__webpack_require__.r(f),__webpack_require__.d(f,{DO:()=>Co,OG:()=>qo,My:()=>Bo,Ph:()=>Oo,lX:()=>Mo,Id:()=>Vo,fg:()=>$o,qj:()=>Fo,aT:()=>Lo,aY:()=>To,lq:()=>Uo,z:()=>Ko,Q5:()=>Go});var g={};__webpack_require__.r(g),__webpack_require__.d(g,{Ed25519PrivateKey:()=>dc,Ed25519PublicKey:()=>hc,generateKeyPair:()=>gc,generateKeyPairFromSeed:()=>yc,unmarshalEd25519PrivateKey:()=>pc,unmarshalEd25519PublicKey:()=>fc});var y={};__webpack_require__.r(y),__webpack_require__.d(y,{MAX_KEY_SIZE:()=>Ac,RsaPrivateKey:()=>kc,RsaPublicKey:()=>Ic,fromJwk:()=>Cc,generateKeyPair:()=>Pc,unmarshalRsaPrivateKey:()=>Rc,unmarshalRsaPublicKey:()=>Tc});var m={};__webpack_require__.r(m),__webpack_require__.d(m,{Secp256k1PrivateKey:()=>Wc,Secp256k1PublicKey:()=>Gc,generateKeyPair:()=>Jc,unmarshalSecp256k1PrivateKey:()=>Yc,unmarshalSecp256k1PublicKey:()=>Xc});var b={};__webpack_require__.r(b),__webpack_require__.d(b,{Ed25519PrivateKey:()=>ah,Ed25519PublicKey:()=>oh,generateKeyPair:()=>uh,generateKeyPairFromSeed:()=>hh,unmarshalEd25519PrivateKey:()=>ch,unmarshalEd25519PublicKey:()=>lh});var w={};__webpack_require__.r(w),__webpack_require__.d(w,{MAX_RSA_KEY_SIZE:()=>Rp,RsaPrivateKey:()=>Cp,RsaPublicKey:()=>Tp,fromJwk:()=>Dp,generateKeyPair:()=>Np,unmarshalRsaPrivateKey:()=>Pp,unmarshalRsaPublicKey:()=>Bp});var v={};__webpack_require__.r(v),__webpack_require__.d(v,{Secp256k1PrivateKey:()=>Op,Secp256k1PublicKey:()=>Lp,generateKeyPair:()=>Kp,unmarshalSecp256k1PrivateKey:()=>Mp,unmarshalSecp256k1PublicKey:()=>Up});var E={};__webpack_require__.r(E),__webpack_require__.d(E,{Ed25519PrivateKey:()=>Py,Ed25519PublicKey:()=>Cy,generateKeyPair:()=>Ny,generateKeyPairFromSeed:()=>xy,unmarshalEd25519PrivateKey:()=>By,unmarshalEd25519PublicKey:()=>Dy});var S={};__webpack_require__.r(S),__webpack_require__.d(S,{MAX_RSA_KEY_SIZE:()=>qy,RsaPrivateKey:()=>jy,RsaPublicKey:()=>Hy,fromJwk:()=>Gy,generateKeyPair:()=>Wy,unmarshalRsaPrivateKey:()=>$y,unmarshalRsaPublicKey:()=>zy});var _={};__webpack_require__.r(_),__webpack_require__.d(_,{Secp256k1PrivateKey:()=>Jy,Secp256k1PublicKey:()=>Xy,generateKeyPair:()=>em,unmarshalSecp256k1PrivateKey:()=>Qy,unmarshalSecp256k1PublicKey:()=>Zy});var A={};__webpack_require__.r(A),__webpack_require__.d(A,{Ed25519PrivateKey:()=>Pm,Ed25519PublicKey:()=>Cm,generateKeyPair:()=>Nm,generateKeyPairFromSeed:()=>xm,unmarshalEd25519PrivateKey:()=>Bm,unmarshalEd25519PublicKey:()=>Dm});var I={};__webpack_require__.r(I),__webpack_require__.d(I,{MAX_RSA_KEY_SIZE:()=>Hm,RsaPrivateKey:()=>$m,RsaPublicKey:()=>jm,fromJwk:()=>Wm,generateKeyPair:()=>Ym,unmarshalRsaPrivateKey:()=>zm,unmarshalRsaPublicKey:()=>Gm});var k={};__webpack_require__.r(k),__webpack_require__.d(k,{Secp256k1PrivateKey:()=>Qm,Secp256k1PublicKey:()=>Jm,generateKeyPair:()=>tb,unmarshalSecp256k1PrivateKey:()=>Zm,unmarshalSecp256k1PublicKey:()=>eb});var R={};__webpack_require__.r(R),__webpack_require__.d(R,{Ed25519PrivateKey:()=>Sb,Ed25519PublicKey:()=>Eb,generateKeyPair:()=>Ib,generateKeyPairFromSeed:()=>kb,unmarshalEd25519PrivateKey:()=>_b,unmarshalEd25519PublicKey:()=>Ab});var T={};__webpack_require__.r(T),__webpack_require__.d(T,{MAX_RSA_KEY_SIZE:()=>Lb,RsaPrivateKey:()=>Mb,RsaPublicKey:()=>Ob,fromJwk:()=>Fb,generateKeyPair:()=>Vb,unmarshalRsaPrivateKey:()=>Ub,unmarshalRsaPublicKey:()=>Kb});var C={};__webpack_require__.r(C),__webpack_require__.d(C,{Secp256k1PrivateKey:()=>jb,Secp256k1PublicKey:()=>Hb,generateKeyPair:()=>Gb,unmarshalSecp256k1PrivateKey:()=>$b,unmarshalSecp256k1PublicKey:()=>zb});var P={};__webpack_require__.r(P),__webpack_require__.d(P,{Ed25519PrivateKey:()=>y_,Ed25519PublicKey:()=>g_,generateKeyPair:()=>w_,generateKeyPairFromSeed:()=>v_,unmarshalEd25519PrivateKey:()=>m_,unmarshalEd25519PublicKey:()=>b_});var B={};__webpack_require__.r(B),__webpack_require__.d(B,{MAX_RSA_KEY_SIZE:()=>C_,RsaPrivateKey:()=>B_,RsaPublicKey:()=>P_,fromJwk:()=>x_,generateKeyPair:()=>L_,unmarshalRsaPrivateKey:()=>D_,unmarshalRsaPublicKey:()=>N_});var D={};function N(e=0){return new Uint8Array(e)}function x(e=0){return new Uint8Array(e)}__webpack_require__.r(D),__webpack_require__.d(D,{Secp256k1PrivateKey:()=>U_,Secp256k1PublicKey:()=>M_,generateKeyPair:()=>V_,unmarshalSecp256k1PrivateKey:()=>K_,unmarshalSecp256k1PublicKey:()=>F_});const L=Math.pow(2,7),O=Math.pow(2,14),M=Math.pow(2,21),U=Math.pow(2,28),K=Math.pow(2,35),F=Math.pow(2,42),V=Math.pow(2,49),q=128,H=127;function j(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $(e,t,r=0){switch(j(e)){case 8:t[r++]=255&e|q,e/=128;case 7:t[r++]=255&e|q,e/=128;case 6:t[r++]=255&e|q,e/=128;case 5:t[r++]=255&e|q,e/=128;case 4:t[r++]=255&e|q,e>>>=7;case 3:t[r++]=255&e|q,e>>>=7;case 2:t[r++]=255&e|q,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function z(e,t){let r=e[t],n=0;if(n+=r&H,r>>=7;case 3:t.set(r++,255&e|q),e>>>=7;case 2:t.set(r++,255&e|q),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function W(e,t=0){return e instanceof Uint8Array?z(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&H,r>>31>0){const e=1+~this.lo>>>0;let 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){const e=1+~this.lo>>>0;let 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(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const 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 se;if(ere)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>ie&&(n=0n,++r>ie&&(r=0n))),new ne(Number(n),Number(r))}static fromNumber(e){if(0===e)return se;const 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 ne(r,n)}static from(e){return"number"==typeof e?ne.fromNumber(e):"bigint"==typeof e?ne.fromBigInt(e):"string"==typeof e?ne.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ne(e.low>>>0,e.high>>>0):se}}const se=new ne(0,0);se.toBigInt=function(){return 0n},se.zzEncode=se.zzDecode=function(){return this},se.length=function(){return 1};const ie=4294967296n;function oe(e,t,r){const n=r;let s,i;for(let n=0;n>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function ae(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ce(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class le{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)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(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,ae(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw ae(this,4);return ce(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ae(this,4);return 0|ce(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,X[0]=t[r],X[1]=t[r+1],X[2]=t[r+2],X[3]=t[r+3],Y[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ae(this,4);const e=(t=this.buf,r=this.pos,Z[0]=t[r],Z[1]=t[r+1],Z[2]=t[r+2],Z[3]=t[r+3],Z[4]=t[r+4],Z[5]=t[r+5],Z[6]=t[r+6],Z[7]=t[r+7],Q[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw ae(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t191&&i<224?s[o++]=(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,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw ae(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw ae(this)}while(128&this.buf[this.pos++]);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(){const e=new ne(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw ae(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}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;if(t=0,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 ae(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 ae(this,8);const e=ce(this.buf,this.pos+=4),t=ce(this.buf,this.pos+=4);return new ne(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=z(this.buf,this.pos);return this.pos+=j(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 ue(e,t,r){const n=function(e){return new le(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function he(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 new Error("Unknown type, must be binary type")}new Uint8Array(0);const de=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)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 new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);fhe(s(e))})}function ve({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return be({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<function(e,t,r,n){const s={};for(let e=0;e=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}(t,n,r,e)})}const Ee=we({prefix:"9",name:"base10",alphabet:"0123456789"}),Se=ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_e=ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ae=ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Ie=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ke=Ie.reduce(((e,t,r)=>(e[r]=t,e)),[]),Re=Ie.reduce(((e,t,r)=>(e[t.codePointAt(0)]=r,e)),[]),Te=be({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+ke[t]),"")},decode:function(e){const t=[];for(const r of e){const e=Re[r.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${r}`);t.push(e)}return new Uint8Array(t)}}),Ce=ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pe=ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Be=ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),De=ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ne=ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xe=ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Le=ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Oe=ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Me=ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ue=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ke=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Fe=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ve=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),qe=ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),He=ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),je=ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$e=ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),ze=ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Ge=be({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),We=new TextEncoder,Ye=new TextDecoder,Xe="json",Je=512;function Qe(e){return We.encode(JSON.stringify(e))}function Ze(e){return JSON.parse(Ye.decode(e))}const et="raw",tt=85;function rt(e){return he(e)}function nt(e){return he(e)}var st=128,it=-128,ot=Math.pow(2,31),at=128,ct=127,lt=Math.pow(2,7),ut=Math.pow(2,14),ht=Math.pow(2,21),dt=Math.pow(2,28),pt=Math.pow(2,35),ft=Math.pow(2,42),gt=Math.pow(2,49),yt=Math.pow(2,56),mt=Math.pow(2,63);const bt={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=ot;)r[n++]=255&t|st,t/=128;for(;t⁢)r[n++]=255&t|st,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&ct)<=at);return e.bytes=o-r,s},encodingLength:function(e){return eSt(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ct(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const Pt=Rt({name:"sha2-256",code:18,encode:Ct("SHA-256")}),Bt=Rt({name:"sha2-512",code:19,encode:Ct("SHA-512")});function Dt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,xt(e),t??Fe.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,xt(e),t??Ce.encoder)}const Nt=new WeakMap;function xt(e){const t=Nt.get(e);if(null==t){const t=new Map;return Nt.set(e,t),t}return t}class Lt{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:{const{code:e,multihash:t}=this;if(e!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Lt.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:{const{code:e,digest:t}=this.multihash,r=St(e,t);return Lt.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 Lt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{const[r,n]=wt(e.subarray(t));return t+=n,r};let n=r(),s=Ot;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Fe;return[Fe.prefix,r.decode(`${Fe.prefix}${e}`)]}case Fe.prefix:{const r=t??Fe;return[Fe.prefix,r.decode(e)]}case Ce.prefix:{const r=t??Ce;return[Ce.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),s=Lt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return xt(s).set(r,e),s}}const Ot=112,Mt=18;function Ut(e,t,r){const n=Et(e),s=n+Et(t),i=new Uint8Array(s+r.byteLength);return vt(e,i,0),vt(t,i,n),i.set(r,s),i}const Kt=Symbol.for("@ipld/js-cid/CID"),Ft={...l,...r,...c,...e,...t,...s,...i,...o,...a,...n};function Vt(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const qt=Vt("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ht=Vt("ascii","a",(e=>{let t="a";for(let r=0;r{const t=x((e=e.substring(1)).length);for(let r=0;r4096)return x(e);n+e>t&&(r=x(t),n=0);const s=r.subarray(n,n+=e);return 7&n&&(n=1+(7|n)),s}}();class Xt{len;head;tail;states;constructor(){this.len=0,this.head=new zt(Gt,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new zt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Zt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(er,10,ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ne.fromBigInt(e);return this._push(er,t.length(),t)}uint64Number(e){return this._push($,j(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){const t=ne.fromBigInt(e).zzEncode();return this._push(er,t.length(),t)}sint64Number(e){const t=ne.fromNumber(e).zzEncode();return this._push(er,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jt,1,e?1:0)}fixed32(e){return this._push(tr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ne.fromBigInt(e);return this._push(tr,4,t.lo)._push(tr,4,t.hi)}fixed64Number(e){const t=ne.fromNumber(e);return this._push(tr,4,t.lo)._push(tr,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(J,4,e)}double(e){return this._push(ee,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Jt,1,0):this.uint32(t)._push(rr,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Zt extends zt{next;constructor(e,t){super(Qt,e,t),this.next=void 0}}function er(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 tr(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 rr(e,t,r){t.set(e,r)}function nr(e,t,r){t.set(e,r)}function sr(e,t,r){e.length<40?oe(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set($t(e),r)}function ir(e,t){const r=new Xt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var or,ar,cr,lr,ur,hr,dr,pr,fr,gr,yr,mr,br,wr,vr,Er,Sr,_r,Ar,Ir,kr,Rr,Tr,Cr,Pr,Br,Dr,Nr,xr,Lr,Or,Mr,Ur;function Kr(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Fr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Kr("enum",or.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Vr(e,t){return Kr("message",or.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Xt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(nr,t,e),this},Xt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(sr,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(or||(or={}));class qr extends Error{code;constructor(e,t,r){super(e,r),this.code=t}}function Hr(e){return Boolean(e)}function jr(e){const 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}function $r(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),ar.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=ar.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(cr||(cr={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),r),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),pr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");n.messages.push(pr.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),lr.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),ur.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=lr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=ur.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),dr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=dr.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(fr||(fr={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new qr('decode error - map field "contentTopics" had too many elements',"ERR_MAX_LENGTH");i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),wr.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.wakuMessage=wr.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),br.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=br.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Ar.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Ar.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(vr||(vr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={isSuccess:!1},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Er||(Er={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),vr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),Er.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=vr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=Er.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Sr||(Sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(_r||(_r={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),_r.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=_r.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ar||(Ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={digest:N(0),receiverTime:0n,senderTime:0n,pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ir||(Ir={})),function(e){let t,r,n;!function(e){e.BACKWARD="BACKWARD",e.FORWARD="FORWARD"}(t=e.Direction||(e.Direction={})),function(e){e[e.BACKWARD=0]="BACKWARD",e[e.FORWARD=1]="FORWARD"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.Direction||(e.Direction={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{!1!==n.lengthDelimited&&r.fork(),null!=t.pageSize&&(r.uint32(8),r.uint64(t.pageSize)),null!=t.cursor&&(r.uint32(18),Ir.codec().encode(t.cursor,r)),null!=t.direction&&(r.uint32(24),e.Direction.codec().encode(t.direction,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.pageSize=t.uint64();break;case 2:s.cursor=Ir.codec().decode(t,t.uint32(),{limits:n.limits?.cursor});break;case 3:s.direction=e.Direction.codec().decode(t);break;default:t.skipType(7&r)}}return s}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(kr||(kr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Rr||(Rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),null!=e.contentFilters)for(const r of e.contentFilters)t.uint32(26),Rr.codec().encode(r,t);null!=e.pagingInfo&&(t.uint32(34),kr.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={})=>{const n={contentFilters:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 2:n.pubsubTopic=e.string();break;case 3:if(null!=r.limits?.contentFilters&&n.contentFilters.length===r.limits.contentFilters)throw new qr('decode error - map field "contentFilters" had too many elements',"ERR_MAX_LENGTH");n.contentFilters.push(Rr.codec().decode(e,e.uint32(),{limits:r.limits?.contentFilters$}));break;case 4:n.pagingInfo=kr.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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Tr||(Tr={})),function(e){let t,r,n;!function(e){e.NONE="NONE",e.INVALID_CURSOR="INVALID_CURSOR",e.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",e.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE"}(t=e.HistoryError||(e.HistoryError={})),function(e){e[e.NONE=0]="NONE",e[e.INVALID_CURSOR=1]="INVALID_CURSOR",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE"}(r||(r={})),function(e){e.codec=()=>Fr(r)}(t=e.HistoryError||(e.HistoryError={})),e.codec=()=>(null==n&&(n=Vr(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.messages)for(const e of t.messages)n.uint32(18),Dr.codec().encode(e,n);null!=t.pagingInfo&&(n.uint32(26),kr.codec().encode(t.pagingInfo,n)),null!=t.error&&0!==r[t.error]&&(n.uint32(32),e.HistoryError.codec().encode(t.error,n)),!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={messages:[],error:t.NONE},o=null==n?r.len:r.pos+n;for(;r.pos>>3){case 2:if(null!=s.limits?.messages&&i.messages.length===s.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");i.messages.push(Dr.codec().decode(r,r.uint32(),{limits:s.limits?.messages$}));break;case 3:i.pagingInfo=kr.codec().decode(r,r.uint32(),{limits:s.limits?.pagingInfo});break;case 4:i.error=e.HistoryError.codec().decode(r);break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Cr||(Cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Tr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(26),Cr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.query=Tr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 3:n.response=Cr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Pr||(Pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={proof:N(0),merkleRoot:N(0),epoch:N(0),shareX:N(0),shareY:N(0),nullifier:N(0),rlnIdentifier:N(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Br||(Br={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Br.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:N(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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=Br.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),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Dr||(Dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Nr||(Nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(xr||(xr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Nr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new qr('decode error - map field "peerInfos" had too many elements',"ERR_MAX_LENGTH");n.peerInfos.push(Nr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Lr||(Lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),xr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),Lr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.query=xr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=Lr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Or||(Or={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Mr||(Mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ur||(Ur={}));function zr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Gr(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Wr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(e.outputLen),zr(e.blockLen)}function Yr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Xr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Jr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Qr=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Zr=async()=>{};async function en(e,t,r){let n=Date.now();for(let s=0;s=0&&ee().update(rn(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function cn(e=32){if(Xr&&"function"==typeof Xr.getRandomValues)return Xr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}const ln=(e,t,r)=>e&t^e&r^t&r;class un extends sn{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=Jr(this.buffer)}update(e){Yr(this);const{view:t,buffer:r,blockLen:n}=this,s=(e=rn(e)).length;for(let i=0;in-i&&(this.process(r,0),i=0);for(let e=i;e>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=Jr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,s=Qr(r,17)^Qr(r,19)^r>>>10;pn[e]=s+pn[e-7]+n+pn[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Qr(o,6)^Qr(o,11)^Qr(o,25))+((u=o)&a^~u&c)+hn[e]+pn[e]|0,h=(Qr(r,2)^Qr(r,13)^Qr(r,22))+ln(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){pn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const gn=an((()=>new fn));var yn,mn,bn,wn,vn,En;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(yn||(yn={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.REMOTE_PEER_FAULT="Remote peer fault",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout"}(mn||(mn={})),function(e){e.BACKWARD="backward",e.FORWARD="forward"}(bn||(bn={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(wn||(wn={})),function(e){e.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",e.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",e.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",e.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"}(vn||(vn={})),function(e){e.CONNECTION_STATUS="waku:connection"}(En||(En={}));const Sn="/waku/2/default-waku/proto",_n=1;function An(e,t="utf8"){const r=jt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function In(e){return"string"==typeof e?$t(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}const kn=e=>An(e,"base16"),Rn=e=>An(e,"utf8"),Tn=e=>$t(e,"utf8");function Cn(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}const Pn=e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??_n}/${e.shard}`},Bn=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>Ln(t,e.clusterId)))));if("shards"in e){if(void 0===e.shards)throw new Error("Invalid shard");return Array.from(new Set(e.shards.map((t=>`/waku/2/rs/${e.clusterId??_n}/${t}`))))}if("application"in e&&"version"in e)return[Ln(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},Dn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function Nn(e,t){if(!t.includes(e))throw new 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 xn(e,t=8){const{application:r,version:n}=function(e){const 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(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),s=gn(Cn([Tn(r),Tn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}function Ln(e,t=_n,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${xn(e,r)}`}function On(e,t){return"string"==typeof t?t:void 0!==t?.shard?Pn(t):Ln(e,t?.clusterId??_n)}const Mn=e=>{const t=e.clusterId??_n,r="shards"in e?e.shards:[],n="contentTopics"in e?e.contentTopics:[],[s,i]="application"in e&&"version"in e?[e.application,e.version]:[void 0,void 0],o=r&&r.length>0,a=n&&n.length>0,c=s&&i;if(o)return{shardingParams:{clusterId:t,shards:r},shardInfo:{clusterId:t,shards:r},pubsubTopics:Bn({clusterId:t,shards:r})};if(a){const e=Array.from(new Set(n.map((e=>Ln(e,t))))),r=Array.from(new Set(n.map((e=>xn(e)))));return{shardingParams:{clusterId:t,contentTopics:n},shardInfo:{clusterId:t,shards:r},pubsubTopics:e}}if(c){const e=Ln(`/${s}/${i}/default/default`,t);return{shardingParams:{clusterId:t,application:s,version:i},shardInfo:{clusterId:t,shards:[Dn(e).shard]},pubsubTopics:[e]}}throw new Error("Missing minimum required configuration options for static sharding or autosharding.")},Un=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},Kn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function Jn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=x(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Qn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!ts(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!ts(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=es(this.bufs,e);return t.buf[t.index]}set(e,t){const r=es(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Jn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Jn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new rs;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s=a)continue;const c=e>=o&&eo&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(ts(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=x(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=x(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof rs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;te+t.byteLength),0)),r.length=t,r}}function ns(e){return null!=e[Symbol.asyncIterator]}const ss=e=>{const t=j(e),r=x(t);return G(e,r),ss.bytes=t,r};function is(e,t){const r=(t=t??{}).lengthEncoder??ss;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return ns(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}ss.bytes=0,is.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??ss;return new rs(r(e.byteLength),e)};var os,as=__webpack_require__(6310);!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(os||(os={}));const cs=e=>{const t=W(e);return cs.bytes=j(t),t};function ls(e,t){const r=new rs;let n=os.LENGTH,s=-1;const i=t?.lengthDecoder??cs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===os.LENGTH)try{if(s=i(r),s<0)throw as(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw as(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=os.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw as(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw e}if(n===os.DATA){if(r.byteLength0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw as(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}function us(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}cs.bytes=0,ls.fromReader=(e,t)=>{let r=1;return ls(async function*(){for(;;)try{const{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}}(),{...t??{},onLength:e=>{r=e}})};class hs{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const 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 ds{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new hs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class ps extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function fs(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new ds,a=us();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new ds,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=us()}))}},return:()=>(o=new ds,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new ps)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const 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)}const gs=function(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(){for(const e of t)yield*e}():async function*(){const t=fs({objectMode:!0});Promise.resolve().then((async()=>{try{await Promise.all(e.map((async e=>{for await(const r of e)t.push(r)}))),t.end()}catch(e){t.end(e)}})),yield*t}()};function ys(e,...t){if(null==e)throw new Error("Empty pipeline");if(vs(e)){const t=e;e=()=>t.source}else if(ws(e)||bs(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&vs(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e{let t;for(;e.length>0;)t=e.shift()(t);return t},bs=e=>null!=e?.[Symbol.asyncIterator],ws=e=>null!=e?.[Symbol.iterator],vs=e=>null!=e&&null!=e.sink&&null!=e.source,Es=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=fs({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(bs(s))n=async function*(){yield*s,t.end()};else{if(!ws(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return gs(t,n())}return e.source};class Ss{multicodec;getConnections;addEventListener;streamPool;log;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new qn(`stream-manager:${e}`),this.streamPool=new Map,this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);if(!r)return this.createStream(e);this.streamPool.delete(t),this.prepareStream(e);try{const e=await r;if(e&&"closed"!==e.status)return e}catch(e){this.log.warn(`Failed to get stream for ${t} -- `,e),this.log.warn("Attempting to create a new stream for the peer")}return this.createStream(e)}async createStream(e,t=0){const r=function(e){if(!e.length)return;if(1===e.length)return e[0];let t;return e.forEach((e=>{"open"===e.status&&(t?e.timeline.open>t.timeline.open&&(t=e):t=e)})),t}(this.getConnections(e.id));if(!r)throw new Error("Failed to get a connection to the peer");try{return await r.newStream(this.multicodec)}catch(r){if(t<3){const r=1e3*Math.pow(2,t);return await new Promise((e=>setTimeout(e,r))),this.createStream(e,t+1)}throw new Error(`Failed to create a new stream for ${e.id.toString()} -- `+r)}}prepareStream(e){const t=new Promise((e=>setTimeout(e,5e3))),r=Promise.race([this.createStream(e),t.then((()=>{throw new Error("Connection timeout")}))]).catch((t=>{this.log.error(`Failed to prepare a new stream for ${e.id.toString()} -- `,t)}));this.streamPool.set(e.id.toString(),r)}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;if(t.protocols.includes(this.multicodec))if(this.isConnectedTo(t.id))this.log.info(`Preemptively opening a stream to ${t.id.toString()}`),this.prepareStream(t);else{const e=t.id.toString();this.streamPool.delete(e),this.log.info(`Removed pending stream for disconnected peer ${e}`)}};isConnectedTo(e){return this.getConnections(e).some((e=>"open"===e.status))}}class _s{multicodec;components;log;pubsubTopics;options;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n,s){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.options=s,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new Ss(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 async function(e,t){const r=[];return await e.forEach((e=>{for(let n=0;nthis.components.connectionManager.getConnections(e.id).length>0))}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:1,numPeers:0}){const r=function(e,t,r){let n=e.filter((e=>e.tags.has(wn.BOOTSTRAP))).slice(0,r);t>0&&t!e.tags.has(wn.BOOTSTRAP)));if(0===t)return[...n,...s];const i=[...n];for(;i.length0;){const e=Math.floor(Math.random()*s.length),t=s.splice(e,1)[0];i.push(t)}return i}(await async function(e,t,r,n){const s=e.filter((e=>"open"===e.status)).map((async e=>{const s=await t.get(e.remotePeer);if(r.some((e=>s.protocols.includes(e)))){if(!n)return s;{const e=s.metadata.get("shardInfo"),t=e&&Un(e);if(t&&n.clusterId===t.clusterId)return s}}return null}));return(await Promise.all(s)).filter((e=>null!==e))}(this.components.connectionManager.getConnections(),this.peerStore,[this.multicodec],this.options?.shardInfo?Mn(this.options.shardInfo).shardInfo:void 0),e,t),n=await async function(e,t){return 0===t.length?[]:(await Promise.all(t.map((async t=>{try{const r=(await e.get(t.id)).metadata.get("ping");return r?{peer:t,ping:Number(Rn(r))}:{peer:t,ping:1/0}}catch(e){return{peer:t,ping:1/0}}})))).filter((e=>null!==e)).sort(((e,t)=>e.ping-t.ping)).map((e=>e.peer))}(this.peerStore,r);return 0===n.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),n.length{Ns.error("Failed to register ",xs,e)}))}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Ns.info(`Received message from ${n.toString()}`);try{ys(r,ls,(async e=>{for await(const t of e){const e=Ps.decode(t.slice()),{pubsubTopic:r,wakuMessage:n}=e;if(!n)return void Ns.error("Received empty message");if(!r)return void Ns.error("Pubsub topic missing from push message");await this.handleIncomingMessage(r,n)}})).then((()=>{Ns.info("Receiving pipe closed.")}),(e=>{Ns.error("Error with receiving pipe",e)}))}catch(e){Ns.error("Error decoding message",e)}}async subscribe(e,t,r){const n=await this.getStream(t),s=Bs.createSubscribeRequest(e,r);let i;try{i=await ys([s.encode()],is,n,ls,(async e=>await Xn(e)))}catch(e){return Ns.error("Failed to send subscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}const{statusCode:o,requestId:a,statusDesc:c}=Ds.decode(i[0].slice());return o<200||o>=300?(Ns.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:mn.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return Ns.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id}}}const s=Bs.createUnsubscribeRequest(e,r);try{await ys([s.encode()],is,n.sink)}catch(e){return Ns.error("Failed to send unsubscribe request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=Bs.createUnsubscribeAllRequest(e),s=await ys([n.encode()],is,r,ls,(async e=>await Xn(e)));if(!s||!s.length)return{failure:{error:mn.REMOTE_PEER_FAULT,peerId:t.id},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ds.decode(s[0].slice());return i<200||i>=300?(Ns.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:mn.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t;try{t=await this.getStream(e)}catch(t){return Ns.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}}}const r=Bs.createSubscriberPingRequest();let n;try{n=await ys([r.encode()],is,t,ls,(async e=>await Xn(e)))}catch(t){return Ns.error("Failed to send ping request",t),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:e.id}};const{statusCode:s,requestId:i,statusDesc:o}=Ds.decode(n[0].slice());return s<200||s>=300?(Ns.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}}class Os{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Os({requestId:Cs(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=Sr.decode(e);return new Os(t)}encode(){return Sr.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Ms=new qn("light-push");class Us extends _s{constructor(e,t){super("/vac/waku/lightpush/2.0.0-beta1",e.components,Ms,t.pubsubTopics,t)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Ms.error("Failed to send waku light push: payload is empty"),{query:null,error:mn.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Ms.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:mn.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:Os.createRequest(r,e.pubsubTopic),error:null}:(Ms.error("Failed to encode to protoMessage, aborting push"),{query:null,error:mn.ENCODE_FAILED})}catch(e){return Ms.error("Failed to prepare push message",e),{query:null,error:mn.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:s}=await this.preparePushMessage(e,t);if(s||!n)return{success:null,failure:{error:s,peerId:r.id}};let i,o;try{i=await this.getStream(r)}catch(e){return Ms.error("Failed to get stream",e),{success:null,failure:{error:mn.NO_STREAM_AVAILABLE,peerId:r.id}}}try{o=await ys([n.encode()],is,i,ls,(async e=>await Xn(e)))}catch(e){return Ms.error("Failed to send waku light push request",e),{success:null,failure:{error:mn.GENERIC_FAIL,peerId:r.id}}}const a=new rs;let c;o.forEach((e=>{a.append(e)}));try{c=Os.decode(a).response}catch(e){return Ms.error("Failed to decode push reply",e),{success:null,failure:{error:mn.DECODE_FAILED,peerId:r.id}}}return c?c.isSuccess?{success:r.id,failure:null}:(Ms.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:mn.REMOTE_PEER_REJECTED,peerId:r.id}}):(Ms.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:mn.REMOTE_PEER_FAULT,peerId:r.id}})}}const Ks={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Fs=BigInt(1e6);var Vs;!function(e){e.BACKWARD="backward",e.FORWARD="forward"}(Vs||(Vs={}));class qs{proto;constructor(e){this.proto=e}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){const t=e.contentTopics.map((e=>({contentTopic:e}))),r=function(e){switch(e){case Vs.BACKWARD:return kr.Direction.BACKWARD;case Vs.FORWARD:return kr.Direction.FORWARD;default:return kr.Direction.BACKWARD}}(e.pageDirection),n={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:r};let s,i;return e.startTime&&(s=BigInt(e.startTime.valueOf())*Fs),e.endTime&&(i=BigInt(e.endTime.valueOf())*Fs),new qs({requestId:Cs(),query:{pubsubTopic:e.pubsubTopic,contentFilters:t,pagingInfo:n,startTime:s,endTime:i},response:void 0})}decode(e){const t=Pr.decode(e);return new qs(t)}encode(){return Pr.encode(this.proto)}}var Hs=Cr.HistoryError;const js=new qn("store");class $s extends _s{constructor(e,t){super("/vac/waku/store/2.0.0-beta4",e.components,js,t.pubsubTopics,t)}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.cursor;for(;;){e.cursor=n;const s=qs.createQuery(e);let i;try{i=await this.getStream(r)}catch(e){js.error("Failed to get stream",e);break}const o=await ys([s.encode()],is,i,ls,(async e=>await Xn(e))),a=new rs;o.forEach((e=>{a.append(e)}));const c=s.decode(a);if(!c.response){js.warn("Stopping pagination due to store `response` field missing");break}const l=c.response;if(l.error&&l.error!==Hs.NONE)throw"History response contains an Error: "+l.error;if(!l.messages||!l.messages.length){js.warn("Stopping pagination due to store `response.messages` field missing or empty");break}js.error(`${l.messages.length} messages retrieved from store`),yield l.messages.map((r=>{const n=r.contentTopic;if(void 0!==n){const i=t.get(n);if(i)return i.fromProtoObj(e.pubsubTopic,(s=r,{...Ks,...s}))}var s;return Promise.resolve(void 0)}));const u=l.pagingInfo?.cursor;if(void 0===u){js.warn("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");break}n=u;const h=l.pagingInfo?.pageSize,d=s.query?.pagingInfo?.pageSize;if(h&&d&&hvoid 0===globalThis.DOMException?new Gs(e):new DOMException(e),Ys=e=>{const t=void 0===e.reason?Ws("This operation was aborted."):e.reason;return t instanceof Error?t:Ws(t)};function Xs(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=t;let o;const a=new Promise(((a,c)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&c(Ys(e)),e.addEventListener("abort",(()=>{c(Ys(e))}))}if(r===Number.POSITIVE_INFINITY)return void e.then(a,c);const l=new zs;o=i.setTimeout.call(void 0,(()=>{if(n)try{a(n())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?c(s):(l.message=s??`Promise timed out after ${r} milliseconds`,c(l))}),r),(async()=>{try{a(await e)}catch(e){c(e)}})()})).finally((()=>{a.clear()}));return a.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},a}const Js=e=>{const t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Qs(e,t,r){"function"==typeof r&&(r={filter:r});const n=function(e,t,r){let n;const s=new Promise(((s,i)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r}).count>=0)||r.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(r.count))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const o=[t].flat(),a=[],{addListener:c,removeListener:l}=Js(e),u=(...e)=>{const t=r.multiArgs?e:e[0];r.filter&&!r.filter(t)||(a.push(t),r.count===a.length&&(n(),s(a)))},h=e=>{n(),i(e)};n=()=>{for(const e of o)l(e,u);for(const e of r.rejectionEvents)l(e,h)};for(const e of o)c(e,u);for(const e of r.rejectionEvents)c(e,h);r.signal&&r.signal.addEventListener("abort",(()=>{h(r.signal.reason)}),{once:!0}),r.resolveImmediately&&s(a)}));if(s.cancel=n,"number"==typeof r.timeout){const e=Xs(s,{milliseconds:r.timeout});return e.cancel=n,e}return s}(e,t,r={...r,count:1,resolveImmediately:!1}),s=n.then((e=>e[0]));return s.cancel=n.cancel,s}const Zs=new qn("wait-for-remote-peer");async function ei(e,t,r){if(t=t??function(e){const t=[];return e.relay&&t.push(yn.Relay),e.filter&&t.push(yn.Filter),e.store&&t.push(yn.Store),e.lightPush&&t.push(yn.LightPush),t}(e),!e.isStarted())return Promise.reject("Waku node is not started");const n=[];if(t.includes(yn.Relay)){if(!e.relay)throw new Error("Cannot wait for Relay peer: protocol not mounted");n.push(async function(e){let t=e.getMeshPeers();const r=e.pubsubTopics;for(const n of r)for(;0==t.length;)await Qs(e.gossipSub,"gossipsub:heartbeat"),t=e.getMeshPeers(n)}(e.relay))}if(t.includes(yn.Store)){if(!e.store)throw new Error("Cannot wait for Store peer: protocol not mounted");n.push(ti(e.store.protocol,e.libp2p.services.metadata))}if(t.includes(yn.LightPush)){if(!e.lightPush)throw new Error("Cannot wait for LightPush peer: protocol not mounted");n.push(ti(e.lightPush.protocol,e.libp2p.services.metadata))}if(t.includes(yn.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");n.push(ti(e.filter.protocol,e.libp2p.services.metadata))}r?await async function(e,t,r){await Promise.race([e,ri(t,"Timed out waiting for a remote peer.")])}(Promise.all(n),r):await Promise.all(n)}async function ti(e,t){const r=e.multicodec,n=await e.connectedPeers();if(n.length){if(!t)return void Zs.info(`${r} peer found: `,n[0].id.toString());try{return void await Promise.any(n.map((e=>t.confirmOrAttemptHandshake(e.id))))}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)}}Zs.info(`Waiting for ${r} peer`),await new Promise((n=>{const s=i=>{i.detail?.protocols?.includes(r)&&(t?t.confirmOrAttemptHandshake(i.detail.peerId).then((()=>{e.removeLibp2pEventListener("peer:identify",s),n()})).catch((e=>{"ERR_CONNECTION_BEING_CLOSED"===e.code&&Zs.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`),Zs.error(`Error waiting for handshake confirmation: ${e}`)})):(e.removeLibp2pEventListener("peer:identify",s),n()))};e.addLibp2pEventListener("peer:identify",s)}))}const ri=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(t)),e)));class ni extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const 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){const t=super.dispatchEvent(e);let 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 ii(e,t))}}class si extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}}const ii=globalThis.CustomEvent??si,oi=new qn("keep-alive");class ai{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);const{pingKeepAlive:n,relayKeepAlive:s}=this.options,i=e.toString();if(0!==n){const s=setInterval((()=>{(async()=>{let s;try{try{s=await t.ping(e),oi.info(`Ping succeeded (${i})`,s)}catch(e){return void oi.error(`Ping failed for peer (${i}).\n Next ping will be attempted in ${n} seconds.\n `)}try{await r.merge(e,{metadata:{ping:Tn(s.toString())}})}catch(e){oi.error("Failed to update ping",e)}}catch(e){oi.error(`Ping failed (${i})`,e)}})()}),1e3*n);this.pingKeepAliveTimers.set(i,s)}const o=this.relay;if(o&&0!==s){const t=this.scheduleRelayPings(o,s,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const 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(const 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){const n=[];for(const s of e.pubsubTopics){if(!e.getMeshPeers(s).includes(r))continue;const i=Gn({pubsubTopicShardInfo:Dn(s),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),o=setInterval((()=>{oi.info("Sending Waku Relay ping message"),e.send(i,{payload:new Uint8Array([1])}).catch((e=>oi.error("Failed to send relay ping",e)))}),1e3*t);n.push(o)}return n}}const ci=new qn("connection-manager");class li extends ni{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 ii(En.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new ii(En.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,s,i){let o=li.instances.get(e);return o||(o=new li(t,r,n,s,i),li.instances.set(e,o)),o}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],s=[],i=[],o=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(wn.BOOTSTRAP)?r.push(t):e.includes(wn.PEER_EXCHANGE)?n.push(t):e.includes(wn.LOCAL)&&s.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(wn.BOOTSTRAP)?i.push(t):r.includes(wn.PEER_EXCHANGE)?o.push(t):r.includes(wn.LOCAL)&&a.push(t)}return{DISCOVERED:{[wn.BOOTSTRAP]:r,[wn.PEER_EXCHANGE]:n,[wn.LOCAL]:s},CONNECTED:{[wn.BOOTSTRAP]:i,[wn.PEER_EXCHANGE]:o,[wn.LOCAL]:a}}}constructor(e,t,r,n,s){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...s},this.keepAliveManager=new ai(t,n),this.run().then((()=>ci.info("Connection Manager is now running"))).catch((e=>ci.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>ci.error("Unexpected error while dialing peer store peers",e)))}async dialPeerStorePeers(){const e=await this.libp2p.peerStore.all(),t=[];for(const 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){ci.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{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1);break}catch(r){r instanceof AggregateError?ci.error(`Error dialing peer ${e.toString()} - ${r.errors}`):ci.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{const t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?ci.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):ci.warn("No errors array found for AggregateError"):r=t.message,ci.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 new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),ci.info(`Dropped connection with peer ${e.toString()}`)}catch(t){ci.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{ci.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){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):this.dialPeer(e).catch((t=>{ci.error(`Error dialing peer ${e.toString()} : ${t}`)})))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){ci.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{ci.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t,this.libp2p.services.ping,this.libp2p.peerStore),(await this.getTagNamesForPeer(t)).includes(wn.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(wn.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new ii(vn.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new ii(vn.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.toggleOnline()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.toggleOffline()})()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return ci.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return ci.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(ci.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(ci.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){return!(await this.getTagNamesForPeer(e)).some((e=>e===wn.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===wn.BOOTSTRAP)))).lengththis.configuredPubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return Un(r)}}const ui=new qn("metadata"),hi="/vac/waku/metadata/1.0.0";class di extends _s{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(hi,t.components,ui,Bn(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(hi,(e=>{this.onRequest(e)}))}async onRequest(e){try{const{stream:t,connection:r}=e,n=Ur.encode(this.shardInfo),s=await ys([n],is,t,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){ui.error("Error handling metadata request",e)}}async query(e){const t=Mr.encode(this.shardInfo),r=await this.peerStore.get(e);if(!r)return{shardInfo:null,error:mn.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(i){return ui.error("Failed to get stream",i),{shardInfo:null,error:mn.NO_STREAM_AVAILABLE}}const s=await ys([t],is,n,ls,(async e=>await Xn(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);return i?{shardInfo:null,error:i}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){const t=new rs;e.forEach((e=>{t.append(e)}));const r=Ur.decode(t);return r?{shardInfo:r,error:null}:(ui.error("Error decoding metadata response"),{shardInfo:null,error:mn.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:Kn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function pi(e){return t=>new di(e,t)}class fi 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 gi(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new fi(r?.errorMessage,r?.errorCode));let n;const s=new fi(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class yi{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=us(),this.haveNext=us()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=us(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=us(),await gi(this.readNext.promise,t?.signal,t)}}class mi extends Error{code;constructor(e,t){super(e),this.code=t}}class bi extends mi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}}class wi extends Error{code;constructor(e,t){super(e),this.code=t}}function vi(e,t={}){const r=function(e,t){const r=new yi;e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const 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]());const s=new rs,i={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const i=new Promise(((e,n)=>{r=()=>{n(new bi("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),i]);return!0===e?new rs:t}for(;s.byteLength{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}};return i}(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=j(t.maxDataLength));const n=t?.lengthDecoder??W,s=t?.lengthEncoder??G;return{read:async e=>{let s=-1;const i=new rs;for(;;){i.append(await r.read(1,e));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new wi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new wi("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(s,e)},write:async(e,t)=>{await r.write(new rs(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new rs(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Ei(){const e=us();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Si=65535,_i=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS),Ai=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));function Ii(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function ki(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function Ri(e){if("string"==typeof e)e=ki(e);else{if(!Ii(e))throw new Error("expected Uint8Array, got "+typeof e);e=e.slice()}return e}function Ti(e,t){if(!Ii(e))throw new Error("Uint8Array expected");if("number"==typeof t&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}const Ci=(e,t)=>(Object.assign(t,e),t);function Pi(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function Bi(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`wrong positive integer: ${e}`)}function Di(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ni(e,...t){if(null==(r=e)||"object"!=typeof r||!(r instanceof Uint8Array||"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function xi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Li=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Oi{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,Ti(e=Ri(e),32);const t=Li(e,0),r=Li(e,2),n=Li(e,4),s=Li(e,6),i=Li(e,8),o=Li(e,10),a=Li(e,12),c=Li(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Li(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],y=Li(e,t+0),m=Li(e,t+2),b=Li(e,t+4),w=Li(e,t+6),v=Li(e,t+8),E=Li(e,t+10),S=Li(e,t+12),_=Li(e,t+14);let A=s[0]+(8191&y),I=s[1]+(8191&(y>>>13|m<<3)),k=s[2]+(8191&(m>>>10|b<<6)),R=s[3]+(8191&(b>>>7|w<<9)),T=s[4]+(8191&(w>>>4|v<<12)),C=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),B=s[7]+(8191&(E>>>11|S<<5)),D=s[8]+(8191&(S>>>8|_<<8)),N=s[9]+(_>>>5|n),x=0,L=x+A*o+I*(5*g)+k*(5*f)+R*(5*p)+T*(5*d);x=L>>>13,L&=8191,L+=C*(5*h)+P*(5*u)+B*(5*l)+D*(5*c)+N*(5*a),x+=L>>>13,L&=8191;let O=x+A*a+I*o+k*(5*g)+R*(5*f)+T*(5*p);x=O>>>13,O&=8191,O+=C*(5*d)+P*(5*h)+B*(5*u)+D*(5*l)+N*(5*c),x+=O>>>13,O&=8191;let M=x+A*c+I*a+k*o+R*(5*g)+T*(5*f);x=M>>>13,M&=8191,M+=C*(5*p)+P*(5*d)+B*(5*h)+D*(5*u)+N*(5*l),x+=M>>>13,M&=8191;let U=x+A*l+I*c+k*a+R*o+T*(5*g);x=U>>>13,U&=8191,U+=C*(5*f)+P*(5*p)+B*(5*d)+D*(5*h)+N*(5*u),x+=U>>>13,U&=8191;let K=x+A*u+I*l+k*c+R*a+T*o;x=K>>>13,K&=8191,K+=C*(5*g)+P*(5*f)+B*(5*p)+D*(5*d)+N*(5*h),x+=K>>>13,K&=8191;let F=x+A*h+I*u+k*l+R*c+T*a;x=F>>>13,F&=8191,F+=C*o+P*(5*g)+B*(5*f)+D*(5*p)+N*(5*d),x+=F>>>13,F&=8191;let V=x+A*d+I*h+k*u+R*l+T*c;x=V>>>13,V&=8191,V+=C*a+P*o+B*(5*g)+D*(5*f)+N*(5*p),x+=V>>>13,V&=8191;let q=x+A*p+I*d+k*h+R*u+T*l;x=q>>>13,q&=8191,q+=C*c+P*a+B*o+D*(5*g)+N*(5*f),x+=q>>>13,q&=8191;let H=x+A*f+I*p+k*d+R*h+T*u;x=H>>>13,H&=8191,H+=C*l+P*c+B*a+D*o+N*(5*g),x+=H>>>13,H&=8191;let j=x+A*g+I*f+k*p+R*d+T*h;x=j>>>13,j&=8191,j+=C*u+P*l+B*c+D*a+N*o,x+=j>>>13,j&=8191,x=(x<<2)+x|0,x=x+L|0,L=8191&x,x>>>=13,O+=x,s[0]=L,s[1]=O,s[2]=M,s[3]=U,s[4]=K,s[5]=F,s[6]=V,s[7]=q,s[8]=H,s[9]=j}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let 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 s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i}update(e){xi(this);const{buffer:t,blockLen:r}=this,n=(e=Ri(e)).length;for(let s=0;s>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const Mi=function(e){const t=(t,r)=>e(r).update(Ri(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new Oi(e))),Ui=ki("expand 16-byte k"),Ki=ki("expand 32-byte k"),Fi=Ai(Ui),Vi=Ai(Ki);function qi(e,t){return e<>>32-t}function Hi(e){return e.byteOffset%4==0}const ji=2**32-1,$i=new Uint32Array;function zi(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(void 0!==t&&("object"!=typeof t||(r=t,"[object Object]"!==Object.prototype.toString.call(r)||r.constructor!==Object)))throw new Error("options must be object or undefined");var r;return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Bi(s),Bi(o),Di(i),Di(r),(t,a,c,l,u=0)=>{Ni(t),Ni(a),Ni(c);const h=c.length;if(l||(l=new Uint8Array(h)),Ni(l),Bi(u),u<0||u>=ji)throw new Error("arx: counter overflow");if(l.length=ji)throw new Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t0;)d.pop().fill(0);return l}}function Gi(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,_=a,A=c,I=l,k=u,R=h,T=d,C=p,P=f,B=g,D=y,N=m,x=b,L=w,O=v,M=E;for(let e=0;e{e.update(t);const r=t.length%16;r&&e.update(Xi.subarray(r))},Qi=new Uint8Array(32);function Zi(e,t,r,n,s){const i=e(t,r,Qi),o=Mi.create(i);s&&Ji(o,s),Ji(o,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;Pi(c,0,BigInt(s?s.length:0),!0),Pi(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return i.fill(0),u}const eo=e=>(t,r,n)=>(Ti(t,32),Ti(r),{encrypt:(s,i)=>{const o=s.length,a=o+16;i?Ti(i,a):i=new Uint8Array(a),e(t,r,s,i,1);const c=Zi(e,t,r,i.subarray(0,-16),n);return i.set(c,o),i},decrypt:(s,i)=>{const o=s.length,a=o-16;if(o<16)throw new Error("encrypted data must be at least 16 bytes");i?Ti(i,a):i=new Uint8Array(a);const c=s.subarray(0,-16);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n>no&ro)}:{h:0|Number(e>>no&ro),l:0|Number(e&ro)}}const io=function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let s=0;se>>>r,ao=(e,t,r)=>e<<32-r|t>>>r,co=(e,t,r)=>e>>>r|t<<32-r,lo=(e,t,r)=>e<<32-r|t>>>r,uo=(e,t,r)=>e<<64-r|t>>>r-32,ho=(e,t,r)=>e>>>r-32|t<<64-r,po=function(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}},fo=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),go=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,yo=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),mo=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,bo=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,wo=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),[vo,Eo]=(()=>io(["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)))))(),So=new Uint32Array(80),_o=new Uint32Array(80);class Ao extends un{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(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,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|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,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)So[r]=e.getUint32(t),_o[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|So[e-15],r=0|_o[e-15],n=co(t,r,1)^co(t,r,8)^oo(t,r,7),s=lo(t,r,1)^lo(t,r,8)^ao(t,r,7),i=0|So[e-2],o=0|_o[e-2],a=co(i,o,19)^uo(i,o,61)^oo(i,o,6),c=lo(i,o,19)^ho(i,o,61)^ao(i,o,6),l=yo(s,c,_o[e-7],_o[e-16]),u=mo(l,n,a,So[e-7],So[e-16]);So[e]=0|u,_o[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){const t=co(u,h,14)^co(u,h,18)^uo(u,h,41),b=lo(u,h,14)^lo(u,h,18)^ho(u,h,41),w=u&d^~u&f,v=wo(m,b,h&p^~h&g,Eo[e],_o[e]),E=bo(v,y,t,w,vo[e],So[e]),S=0|v,_=co(r,n,28)^uo(r,n,34)^uo(r,n,39),A=lo(r,n,28)^ho(r,n,34)^ho(r,n,39),I=r&s^r&o^s&o,k=n&i^n&a^i&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=po(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const R=fo(S,A,k);r=go(R,E,_,I),n=0|R}({h:r,l:n}=po(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=po(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=po(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l}=po(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=po(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=po(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=po(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=po(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,y,m)}roundClean(){So.fill(0),_o.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)}}const Io=an((()=>new Ao)),ko=(BigInt(0),BigInt(1)),Ro=BigInt(2);function To(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Co(e){if(!To(e))throw new Error("Uint8Array expected")}const Po=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Bo(e){Co(e);let t="";for(let r=0;r=No._0&&e<=No._9?e-No._0:e>=No._A&&e<=No._F?e-(No._A-10):e>=No._a&&e<=No._f?e-(No._a-10):void 0}function Lo(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t(Ro<new Uint8Array(e),jo=e=>Uint8Array.from(e);function $o(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let n=Ho(e),s=Ho(e),i=0;const o=()=>{n.fill(1),s.fill(0),i=0},a=(...e)=>r(s,n,...e),c=(e=Ho())=>{s=a(jo([0]),e),n=a(),0!==e.length&&(s=a(jo([1]),e),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(o(),c(e);!(r=t(l()));)c();return o(),r}}const zo={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||To(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 Go(e,t,r={}){const n=(t,r,n)=>{const s=zo[r];if("function"!=typeof s)throw new Error(`Invalid validator "${r}", expected function`);const i=e[t];if(!(n&&void 0===i||s(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}const Wo=BigInt(0),Yo=BigInt(1),Xo=BigInt(2),Jo=BigInt(3),Qo=BigInt(4),Zo=BigInt(5),ea=BigInt(8);function ta(e,t){const r=e%t;return r>=Wo?r:t+r}function ra(e,t,r){if(r<=Wo||t 0");if(r===Yo)return Wo;let n=Yo;for(;t>Wo;)t&Yo&&(n=n*e%r),e=e*e%r,t>>=Yo;return n}function na(e,t,r){let n=e;for(;t-- >Wo;)n*=n,n%=r;return n}function sa(e,t){if(e===Wo||t<=Wo)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ta(e,t),n=t,s=Wo,i=Yo,o=Yo,a=Wo;for(;r!==Wo;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==Yo)throw new Error("invert: does not exist");return ta(s,t)}BigInt(9),BigInt(16);const ia=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oa(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function aa(e,t,r=!1,n={}){if(e<=Wo)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=oa(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=function(e){if(e%Qo===Jo){const t=(e+Yo)/Qo;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}if(e%ea===Zo){const t=(e-Zo)/ea;return function(e,r){const n=e.mul(r,Xo),s=e.pow(n,t),i=e.mul(r,s),o=e.mul(e.mul(i,Xo),s),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Yo)/Xo;let r,n,s;for(r=e-Yo,n=0;r%Xo===Wo;r/=Xo,n++);for(s=Xo;sta(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return Wo<=t&&te===Wo,isOdd:e=>(e&Yo)===Yo,neg:t=>ta(-t,e),eql:(e,t)=>e===t,sqr:t=>ta(t*t,e),add:(t,r)=>ta(t+r,e),sub:(t,r)=>ta(t-r,e),mul:(t,r)=>ta(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===Wo)return e.ONE;if(r===Yo)return t;let n=e.ONE,s=t;for(;r>Wo;)r&Yo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Yo;return n}(a,e,t),div:(t,r)=>ta(t*sa(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>sa(t,e),sqrt:n.sqrt||(e=>o(a,e)),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n))),e.ONE),s=e.inv(n);return t.reduceRight(((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n))),s),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Ko(e,i):Uo(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return r?Mo(e):Oo(e)}});return Object.freeze(a)}function ca(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function la(e){const t=ca(e);return t+Math.ceil(t/2)}const ua=BigInt(0),ha=BigInt(1);function da(e,t){const r=(e,t)=>{const 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,s=t;for(;r>ua;)r&ha&&(n=n.add(s)),s=s.double(),r>>=ha;return n},precomputeWindow(e,t){const{windows:r,windowSize:s}=n(t),i=[];let o=e,a=o;for(let e=0;e>=d,n>a&&(n-=h,i+=ha);const o=t,p=t+Math.abs(n)-1,f=e%2!=0,g=n<0;0===n?l=l.add(r(f,s[o])):c=c.add(r(g,s[p]))}return{p:c,f:l}},wNAFCached(e,t,r,n){const s=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,s),1!==s&&t.set(e,n(i))),this.wNAF(s,i,r)}}}function pa(e){return function(e){const t=ia.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});Go(e,t)}(e.Fp),Go(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...oa(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const fa=BigInt(0),ga=BigInt(1),ya=BigInt(2),ma=BigInt(8),ba={zip215:!0};function wa(e){const t=function(e){const t=pa(e);return Go(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:s,hash:i,randomBytes:o,nByteLength:a,h:c}=t,l=ya<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:fa}}}),d=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,r)=>{if(t.length||r)throw new Error("Contexts/pre-hash are not supported");return e}),f=e=>"bigint"==typeof e&&faf(e)&&f(t)&&ee===fa||g(e,l);function m(e,t){if(g(e,t))return e;throw new Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function b(e){return e===fa?e:m(e,n)}const w=new Map;function v(e){if(!(e instanceof E))throw new Error("ExtendedPoint expected")}class E{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!y(e))throw new Error("x required");if(!y(t))throw new Error("y required");if(!y(r))throw new Error("z required");if(!y(n))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};if(!y(t)||!y(r))throw new Error("invalid affine point");return new E(t,r,ga,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(E.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,w.delete(this)}assertValidity(){const{a:e,d:r}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:n,ey:s,ez:i,et:o}=this,a=u(n*n),c=u(s*s),l=u(i*i),h=u(l*l),d=u(a*e);if(u(l*u(d+c))!==u(h+u(r*u(a*c))))throw new Error("bad point: equation left != right (1)");if(u(n*s)!==u(i*o))throw new Error("bad point: equation left != right (2)")}equals(e){v(e);const{ex:t,ey:r,ez:n}=this,{ex:s,ey:i,ez:o}=e,a=u(t*o),c=u(s*n),l=u(r*o),h=u(i*n);return a===c&&l===h}is0(){return this.equals(E.ZERO)}negate(){return new E(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:s}=this,i=u(r*r),o=u(n*n),a=u(ya*u(s*s)),c=u(e*i),l=r+n,h=u(u(l*l)-i-o),d=c+o,p=d-a,f=c-o,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new E(g,y,b,m)}add(e){v(e);const{a:r,d:n}=t,{ex:s,ey:i,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((i-s)*(l+c)),t=u((i+s)*(l-c)),r=u(t-e);if(r===fa)return this.double();const n=u(o*ya*d),p=u(a*ya*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),w=u(f*y),v=u(r*g);return new E(m,b,v,w)}const p=u(s*c),f=u(i*l),g=u(a*n*d),y=u(o*h),m=u((s+i)*(c+l)-p-f),b=y-g,w=y+g,S=u(f-r*p),_=u(m*b),A=u(w*S),I=u(m*S),k=u(b*w);return new E(_,A,k,I)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,w,e,E.normalizeZ)}multiply(e){const{p:t,f:r}=this.wNAF(m(e,n));return E.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=b(e);return t===fa?_:this.equals(_)||t===ga?this:this.equals(S)?this.wNAF(t).p:A.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(e){const{ex:t,ey:n,ez:s}=this,i=this.is0();null==e&&(e=i?ma:r.inv(s));const o=u(t*e),a=u(n*e),c=u(s*e);if(i)return{x:fa,y:ga};if(c!==ga)throw new Error("invZ was invalid");return{x:o,y:a}}clearCofactor(){const{h:e}=t;return e===ga?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:s,a:i}=t,o=r.BYTES,a=(e=Fo("pointHex",e,o)).slice(),c=e[o-1];a[o-1]=-129&c;const d=Mo(a);d===fa||m(d,n?l:r.ORDER);const p=u(d*d),f=u(p-ga),g=u(s*p-i);let{isValid:y,value:b}=h(f,g);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const w=(b&ga)===ga,v=!!(128&c);if(!n&&b===fa&&v)throw new Error("Point.fromHex: x=0 and x_0=1");return v!==w&&(b=u(-b)),E.fromAffine({x:b,y:d})}static fromPrivateKey(e){return R(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ko(t,r.BYTES);return n[n.length-1]|=e&ga?128:0,n}toHex(){return Bo(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,ga,u(t.Gx*t.Gy)),E.ZERO=new E(fa,ga,ga,fa);const{BASE:S,ZERO:_}=E,A=da(E,8*a);function I(e){return ta(e,n)}function k(e){return I(Mo(e))}function R(e){const t=a;e=Fo("private key",e,t);const r=Fo("hashed private key",i(e),2*t),n=d(r.slice(0,t)),s=r.slice(t,2*t),o=k(n),c=S.multiply(o),l=c.toRawBytes();return{head:n,prefix:s,scalar:o,point:c,pointBytes:l}}function T(e=new Uint8Array,...t){const r=Vo(...t);return k(i(p(r,Fo("context",e),!!s)))}const C=ba;return S._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return R(e).pointBytes},sign:function(e,t,n={}){e=Fo("message",e),s&&(e=s(e));const{prefix:i,scalar:o,pointBytes:c}=R(t),l=T(n.context,i,e),u=S.multiply(l).toRawBytes(),h=I(l+T(n.context,u,c,e)*o);return b(h),Fo("result",Vo(u,Ko(h,r.BYTES)),2*a)},verify:function(e,t,n,i=C){const{context:o,zip215:a}=i,c=r.BYTES;e=Fo("signature",e,2*c),t=Fo("message",t),s&&(t=s(t));const l=Mo(e.slice(c,2*c));let u,h,d;try{u=E.fromHex(n,a),h=E.fromHex(e.slice(0,c),a),d=S.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=T(o,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:{getExtendedPublicKey:R,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=E.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}const va=BigInt(0),Ea=BigInt(1);const Sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Aa=(BigInt(0),BigInt(1)),Ia=BigInt(2),ka=BigInt(5),Ra=BigInt(10),Ta=BigInt(20),Ca=BigInt(40),Pa=BigInt(80);function Ba(e){const t=Sa,r=e*e%t*e%t,n=na(r,Ia,t)*r%t,s=na(n,Aa,t)*e%t,i=na(s,ka,t)*s%t,o=na(i,Ra,t)*i%t,a=na(o,Ta,t)*o%t,c=na(a,Ca,t)*a%t,l=na(c,Pa,t)*c%t,u=na(l,Pa,t)*c%t,h=na(u,Ra,t)*i%t;return{pow_p_5_8:na(h,Ia,t)*e%t,b2:r}}function Da(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Na=aa(Sa,void 0,!0),xa=wa({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Io,randomBytes:cn,adjustScalarBytes:Da,uvRatio:function(e,t){const r=Sa,n=ta(t*t*t,r),s=ta(n*n*t,r);let i=ta(e*n*Ba(e*s).pow_p_5_8,r);const o=ta(t*i*i,r),a=i,c=ta(i*_a,r),l=o===e,u=o===ta(-e,r),h=o===ta(-e*_a,r);return l&&(i=a),(u||h)&&(i=c),(ta(i,r)&Yo)===Yo&&(i=ta(-i,r)),{isValid:l||u,value:i}}});const La=(()=>function(e){const t=(Go(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,s=e=>ta(e,n),i=t.montgomeryBits,o=Math.ceil(i/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>ra(e,n-BigInt(2),n));function u(e,t,r){const n=s(e*(t-r));return[t=s(t-n),r=s(r+n)]}function h(e){if("bigint"==typeof e&&va<=e&&e=va;e--){const t=n>>e&Ea;y^=t,a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1],y=t;const r=c+p,i=s(r*r),l=c-p,h=s(l*l),m=i-h,b=f+g,w=s((f-g)*r),v=s(b*l),E=w+v,S=w-v;f=s(E*E),g=s(o*s(S*S)),c=s(i*h),p=s(m*(i+s(d*m)))}a=u(y,c,f),c=a[0],f=a[1],a=u(y,p,g),p=a[0],g=a[1];const m=l(p);return s(c*m)}(r,n);if(f===va)throw new Error("Invalid private or public key received");return p(f)}const g=p(t.Gu);function y(e){return f(e,g)}return{scalarMult:f,scalarMultBase:y,getSharedSecret:(e,t)=>f(e,t),getPublicKey:e=>y(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}}({P:Sa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Sa,{pow_p_5_8:r,b2:n}=Ba(e);return ta(na(r,BigInt(3),t)*n,t)},adjustScalarBytes:Da,randomBytes:cn}))(),Oa=(Na.ORDER+BigInt(3))/BigInt(8);Na.pow(Ia,Oa),Na.sqrt(Na.neg(Na.ONE)),Na.ORDER,BigInt(5),BigInt(8),BigInt(486662),function(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");const r=e.sqrt(t);e.isOdd(r)&&e.neg(r)}(Na,Na.neg(BigInt(486664))),BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Ma extends sn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Wr(e);const r=rn(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew Ma(e,t).update(r).digest();Ua.create=(e,t)=>new Ma(e,t);const Ka=new Uint8Array([0]),Fa=new Uint8Array;const Va={hashSHA256:e=>gn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Ua(e,rn(r),rn(t))}(gn,t,e),n=function(e,t,r,n=32){if(Wr(e),zr(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/e.outputLen);void 0===r&&(r=Fa);const i=new Uint8Array(s*e.outputLen),o=Ua.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t({publicKey:La.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>La.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>to(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>to(n,t,r).decrypt(e.subarray(),s)},qa=e=>{const t=x(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};qa.bytes=2;const Ha=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)};Ha.bytes=2;class ja extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=ja.code}static code="ERR_UNEXPECTED_PEER"}class $a extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=$a.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}__webpack_require__(2746),__webpack_require__(2698);class za extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=za.code,this.type=za.type}static code="ABORT_ERR";static type="aborted"}class Ga extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class Wa extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}Error,Error,Error;const Ya="ERR_TIMEOUT";var Xa=__webpack_require__(276);function Ja(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 new Error("byte array longer than desired length");r=Jn([new Uint8Array(t-r.length),r])}return An(r,"base64url")}function Qa(e){const t=function(e,t){let r=$t(e,"base64urlpad");return r}(e);return new Xa.jsbn.BigInteger(An(t,"base16"),16)}function Za(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}__webpack_require__(7619),__webpack_require__(3736);const ec=32,tc=64,rc=32;function nc(e,t){const r=new Uint8Array(tc);for(let n=0;nFr(cc)}(ac||(ac={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(lc||(lc={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ac.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=ac.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(uc||(uc={}));class hc{_key;constructor(e){this._key=mc(e,ec)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return lc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class dc{_key;_publicKey;constructor(e,t){this._key=mc(e,tc),this._publicKey=mc(t,ec)}sign(e){return function(e,t){const r=e.subarray(0,rc);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new hc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function pc(e){if(e.length>tc){const t=(e=mc(e,tc+ec)).subarray(0,tc),r=e.subarray(tc,e.length);return new dc(t,r)}const t=(e=mc(e,tc)).subarray(0,tc),r=e.subarray(ec);return new dc(t,r)}function fc(e){return e=mc(e,ec),new hc(e)}async function gc(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:nc(e,t),publicKey:t}}();return new dc(e,t)}async function yc(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==rc)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:nc(t,r),publicKey:r}}(e);return new dc(t,r)}function mc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}function bc(e,t){return t.map((t=>Qa(e[t])))}async function wc(e){const t=[await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Ec(e)],r=await vc({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function vc(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([sc.get().subtle.exportKey("jwk",e.privateKey),sc.get().subtle.exportKey("jwk",e.publicKey)])}async function Ec(e){return sc.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 Sc(e,t,r,n){const s=t?function(e){return Xa.pki.setRsaPublicKey(...bc(e,["n","e"]))}(e):function(e){return Xa.pki.setRsaPrivateKey(...bc(e,["n","e","d","p","q","dp","dq","qi"]))}(e);return $t(n(An(r instanceof Uint8Array?r:r.subarray(),"ascii"),s),"ascii")}function _c(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}Object.keys({"P-256":256,"P-384":384,"P-521":521}).join(" / "),__webpack_require__(2313),__webpack_require__(5805);const Ac=8192;class Ic{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return sc.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.publicKeyToAsn1({n:Qa(e.n),e:Qa(e.e)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return lc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}encrypt(e){return Sc(this._key,!0,e,((e,t)=>t.encrypt(e)))}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}}class kc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return function(e){if(isNaN(16))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(16)}()}sign(e){return async function(e,t){const r=await sc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await sc.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ic(this._publicKey)}decrypt(e){return Sc(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=Xa.pki.privateKeyToAsn1({n:Qa(e.n),e:Qa(e.e),d:Qa(e.d),p:Qa(e.p),q:Qa(e.q),dP:Qa(e.dp),dQ:Qa(e.dq),qInv:Qa(e.qi)});return $t(Xa.asn1.toDer(t).getBytes(),"ascii")}(this._key)}get bytes(){return uc.encode({Type:ac.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t){const t=new Xa.util.ByteBuffer(this.marshal()),r=Xa.asn1.fromDer(t),n=Xa.pki.privateKeyFromAsn1(r),s={algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"};return Xa.pki.encryptRsaPrivateKey(n,e,s)}if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Rc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e),d:Ja(r.d),p:Ja(r.p),q:Ja(r.q),dp:Ja(r.dP),dq:Ja(r.dQ),qi:Ja(r.qInv),alg:"RS256"}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await wc(t);return new kc(r.privateKey,r.publicKey)}function Tc(e){const t=function(e){const t=Xa.asn1.fromDer(An(e,"ascii")),r=Xa.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:Ja(r.n),e:Ja(r.e)}}(e);if(_c(t)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ic(t)}async function Cc(e){if(_c(e)>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await wc(e);return new kc(t.privateKey,t.publicKey)}async function Pc(e){if(e>Ac)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await sc.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 vc(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new kc(t.privateKey,t.publicKey)}const{Ph:Bc,aT:Dc}=f,Nc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=Nc;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const 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:Bc(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=Nc,r="string"==typeof e?Dc(e):e;Co(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");const{d:s,l:i}=Nc._parseInt(r.subarray(2)),{d:o,l:a}=Nc._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,r=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},n=t(r(e.s)),s=t(r(e.r)),i=n.length/2,o=s.length/2,a=r(i),c=r(o);return`30${r(o+i+4)}02${c}${s}02${a}${n}`}},xc=BigInt(0),Lc=BigInt(1),Oc=(BigInt(2),BigInt(3));function Mc(e){const t=function(e){const t=pa(e);return Go(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,s=r.BYTES+1,i=2*r.BYTES+1;function o(e){return ta(e,n)}function a(e){return sa(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=pa(e);Go(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:s}=t;if(r){if(!n.eql(s,n.ZERO))throw new 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 new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=t.toBytes||((e,t,n)=>{const s=t.toAffine();return Vo(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),s=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:n,b:s}=t,i=r.sqr(e),o=r.mul(i,e);return r.add(r.add(o,r.mul(e,n)),s)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&xcr.eql(e,r.ZERO);return s(t)&&s(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(s(Fo("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:n}=this.toAffine();if(!r.isValid(e)||!r.isValid(n))throw new Error("bad point: x or y not FE");const s=r.sqr(n),o=i(e);if(!r.eql(s,o))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:n,pz:s}=this,{px:i,py:o,pz:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,s=r.mul(n,Oc),{px:i,py:o,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),p=r.mul(o,o),f=r.mul(a,a),g=r.mul(i,o);return g=r.add(g,g),u=r.mul(i,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(s,f),l=r.add(c,l),c=r.sub(p,l),l=r.add(p,l),l=r.mul(c,l),c=r.mul(g,c),u=r.mul(s,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),l=r.add(l,d),f=r.mul(o,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){u(e);const{px:n,py:s,pz:i}=this,{px:o,py:a,pz:c}=e;let l=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Oc);let y=r.mul(n,o),m=r.mul(s,a),b=r.mul(i,c),w=r.add(n,s),v=r.add(o,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,i);let E=r.add(o,c);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(s,i),l=r.add(a,c),E=r.mul(E,l),l=r.add(m,b),E=r.sub(E,l),p=r.mul(f,v),l=r.mul(g,b),p=r.add(l,p),l=r.sub(m,p),p=r.add(m,p),d=r.mul(l,p),m=r.add(y,y),m=r.add(m,y),b=r.mul(f,b),v=r.mul(g,v),m=r.add(m,b),b=r.sub(y,b),b=r.mul(f,b),v=r.add(v,b),y=r.mul(m,v),d=r.add(d,y),y=r.mul(E,v),l=r.mul(w,l),l=r.sub(l,y),y=r.mul(w,m),p=r.mul(E,p),p=r.add(p,y),new h(l,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,l,e,(e=>{const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}))}multiplyUnsafe(e){const n=h.ZERO;if(e===xc)return n;if(a(e),e===Lc)return this;const{endo:s}=t;if(!s)return p.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=s.splitScalar(e),u=n,d=n,f=this;for(;o>xc||l>xc;)o&Lc&&(u=u.add(f)),l&Lc&&(d=d.add(f)),f=f.double(),o>>=Lc,l>>=Lc;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(r.mul(d.px,s.beta),d.py,d.pz),u.add(d)}multiply(e){a(e);let n,s,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(e,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,o.beta),d.py,d.pz),n=l.add(d),s=u.add(f)}else{const{p:e,f:t}=this.wNAF(i);n=e,s=t}return h.normalizeZ([n,s])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,s=(e,t)=>t!==xc&&t!==Lc&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),i=s(this,t).add(s(e,r));return i.is0()?void 0:i}toAffine(e){const{px:t,py:n,pz:s}=this,i=this.is0();null==e&&(e=i?r.ONE:r.inv(s));const o=r.mul(t,e),a=r.mul(n,e),c=r.mul(s,e);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(c,r.ONE))throw new Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Lc)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===Lc?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),n(h,this,e)}toHex(e=!0){return Bo(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const d=t.nBitLength,p=da(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}({...t,toBytes(e,t,n){const s=t.toAffine(),i=r.toBytes(s.x),o=Vo;return n?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,r.toBytes(s.y))},fromBytes(e){const t=e.length,n=e[0],o=e.subarray(1);if(t!==s||2!==n&&3!==n){if(t===i&&4===n)return{x:r.fromBytes(o.subarray(0,r.BYTES)),y:r.fromBytes(o.subarray(r.BYTES,2*r.BYTES))};throw new Error(`Point of length ${t} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}{const e=Oo(o);if(!(xc<(a=e)&&aBo(Uo(e,t.nByteLength));function p(e){return e>n>>Lc}const f=(e,t,r)=>Oo(e.slice(t,r));class g{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=Fo("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Nc.toSig(Fo("DER",e));return new g(t,r)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s,recovery:i}=this,l=w(Fo("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&i?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=o(-l*f),y=o(s*f),m=c.BASE.multiplyAndAddUnsafe(p,g,y);if(!m)throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Lo(this.toDERHex())}toDERHex(){return Nc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Lo(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const y={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=la(t.n);return function(e,t,r=!1){const n=e.length,s=ca(t),i=la(t);if(n<16||n1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);const o=ta(r?Oo(e):Mo(e),t-Yo)+Yo;return r?Ko(o,s):Uo(o,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){const t=To(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===s||n===i:r?n===2*s||n===2*i:e instanceof c}const b=t.bits2int||function(e){const r=Oo(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return o(b(e))},v=qo(t.nBitLength);function E(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(xc<=e&&ee in s)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:y}=s;null==d&&(d=!0),e=Fo("msgHash",e),f&&(e=Fo("prehashed msgHash",i(e)));const m=w(e),v=l(n),_=[E(v),E(m)];if(null!=y&&!1!==y){const e=!0===y?u(r.BYTES):y;_.push(Fo("extraEntropy",e))}const A=Vo(..._),I=m;return{seed:A,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),s=o(n.x);if(s===xc)return;const i=o(r*o(I+s*v));if(i===xc)return;let l=(n.x===s?0:2)|Number(n.y&Lc),u=i;return d&&p(i)&&(u=function(e){return p(e)?o(-e):e}(i),l^=1),new g(s,u,l)}}}(e,n,s),d=t;return $o(d.hash.outputLen,d.nByteLength,d.hmac)(i,u)},verify:function(e,r,n,s=_){const i=e;if(r=Fo("msgHash",r),n=Fo("publicKey",n),"strict"in s)throw new Error("options.strict was renamed to lowS");const{lowS:l,prehash:u}=s;let h,d;try{if("string"==typeof i||To(i))try{h=g.fromDER(i)}catch(e){if(!(e instanceof Nc.Err))throw e;h=g.fromCompact(i)}else{if("object"!=typeof i||"bigint"!=typeof i.r||"bigint"!=typeof i.s)throw new Error("PARSE");{const{r:e,s:t}=i;h=new g(e,t)}}d=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(l&&h.hasHighS())return!1;u&&(r=t.hash(r));const{r:p,s:f}=h,y=w(r),m=a(f),b=o(y*m),v=o(p*m),E=c.BASE.multiplyAndAddUnsafe(d,b,v)?.toAffine();return!!E&&o(E.x)===p},ProjectivePoint:c,Signature:g,utils:y}}function Uc(e){return{hash:e,hmac:(t,...r)=>Ua(e,t,nn(...r)),randomBytes:cn}}BigInt(4);const Kc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Vc=BigInt(1),qc=BigInt(2),Hc=(e,t)=>(e+t/qc)/t;const jc=aa(Kc,void 0,void 0,{sqrt:function(e){const t=Kc,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=na(u,r,t)*u%t,d=na(h,r,t)*u%t,p=na(d,qc,t)*l%t,f=na(p,s,t)*p%t,g=na(f,i,t)*f%t,y=na(g,a,t)*g%t,m=na(y,c,t)*y%t,b=na(m,a,t)*g%t,w=na(b,r,t)*u%t,v=na(w,o,t)*f%t,E=na(v,n,t)*l%t,S=na(E,qc,t);if(!jc.eql(jc.sqr(S),e))throw new Error("Cannot find square root");return S}}),$c=function(e,t){const r=t=>Mc({...e,...Uc(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:jc,n:Fc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Fc,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Vc*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Hc(i*e,t),c=Hc(-n*e,t);let l=ta(e-a*r-c*s,t),u=ta(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},gn);function zc(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),$c.ProjectivePoint;class Gc{_key;constructor(e){zc(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Za(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return lc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Za(e)?({bytes:t}=await e):t=e.bytes,t}}class Wc{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),zc(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Za(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Gc(this._publicKey)}marshal(){return this._key}get bytes(){return uc.encode({Type:ac.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Za(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return oc(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Yc(e){return new Wc(e)}function Xc(e){return new Gc(e)}async function Jc(){const e=$c.utils.randomPrivateKey();return new Wc(e)}const Qc={rsa:y,ed25519:g,secp256k1:m};function Zc(e){const t=Object.keys(Qc).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const el=Symbol.for("@libp2p/peer-id");function tl(e){return null!=e&&Boolean(e[el])}const rl=Symbol.for("nodejs.util.inspect.custom"),nl=Object.values(Ft).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)),Ft.identity.decoder),sl=114,il=36,ol=37;class al{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()})`}[el]=!0;toString(){return null==this.string&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Lt.createV1(sl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Qn(this.multihash.bytes,e);if("string"==typeof e)return hl(e).equals(this);if(null!=e?.multihash?.bytes)return Qn(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[rl](){return`PeerId(${this.toString()})`}}class cl extends al{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ll extends al{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class ul extends al{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}function hl(e,t){if(t=t??nl,"1"===e.charAt(0)||"Q"===e.charAt(0)){const t=_t(Fe.decode(`z${e}`));return e.startsWith("12D")?new ll({multihash:t}):e.startsWith("16U")?new ul({multihash:t}):new cl({multihash:t})}return dl(nl.decode(e))}function dl(e){try{const t=_t(e);if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:t});if(t.digest.length===ol)return new ul({multihash:t})}if(t.code===Pt.code)return new cl({multihash:t})}catch{return function(e){if(null==e||null==e.multihash||null==e.version||1===e.version&&e.code!==sl)throw new Error("Supplied PeerID CID is invalid");const t=e.multihash;if(t.code===Pt.code)return new cl({multihash:e.multihash});if(t.code===kt.code){if(t.digest.length===il)return new ll({multihash:e.multihash});if(t.digest.length===ol)return new ul({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}(Lt.decode(e))}throw new Error("Supplied PeerID CID is invalid")}async function pl(e,t){return e.length===il?new ll({multihash:St(kt.code,e),privateKey:t}):e.length===ol?new ul({multihash:St(kt.code,e),privateKey:t}):new cl({multihash:await Pt.digest(e),publicKey:e,privateKey:t})}var fl,gl;async function yl(e,t,r){const n=await async function(e,t){if(null==e.privateKey)throw new Error("PrivateKey was missing from PeerId");return(await async function(e){const t=uc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPrivateKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PrivateKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Zc(t.Type??"RSA")}}(e.privateKey)).sign(t)}(e,wl(t));if(null==e.publicKey)throw new Error("PublicKey was missing from local PeerId");return function(e,t,r){return gl.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}(e.publicKey,n,r)}async function ml(e){return pl(e.identityKey)}function bl(e){return gl.decode(e)}function wl(e){const t=$t("noise-libp2p-static-key:");return e instanceof Uint8Array?Jn([t,e],t.length+e.length):(e.prepend(t),e)}async function vl(e,t,r){const n=await pl(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);const s=wl(e);if(null==n.publicKey)throw new Error("PublicKey was missing from PeerId");if(null==t.identitySig)throw new Error("Signature was missing from message");const i=function(e){const t=lc.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case ac.RSA:return Qc.rsa.unmarshalRsaPublicKey(r);case ac.Ed25519:return Qc.ed25519.unmarshalEd25519PublicKey(r);case ac.Secp256k1:return Qc.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Zc(t.Type??"unknown")}}(n.publicKey);if(!await i.verify(s,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function El(e){return!!(e instanceof Uint8Array||ts(e))&&32===e.byteLength}!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(fl||(fl={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),fl.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:N(0),identitySig:N(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=fl.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(gl||(gl={}));class Sl{n;bytes;view;constructor(e=0){this.n=e,this.bytes=N(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 new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}class _l{crypto;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=t}encryptWithAd(e,t,r){const n=this.encrypt(e.k,e.n,t,r);return e.n.increment(),n}decryptWithAd(e,t,r,n){const{plaintext:s,valid:i}=this.decrypt(e.k,e.n,t,r,n);return i&&e.n.increment(),{plaintext:s,valid:i}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return N(32)}isEmptyKey(e){return Qn(this.createEmptyKey(),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,s){t.assertValue();const i=this.crypto.chaCha20Poly1305Decrypt(n,t.getBytes(),r,e,s);return i?{plaintext:i,valid:!0}:{plaintext:N(0),valid:!1}}decryptAndHash(e,t){let r,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{const r=this.crypto.generateX25519SharedKey(e,t);return 32===r.length?r:r.subarray(0,32)}catch(e){const t=e;return this.log.error("error deriving shared key",t),N(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(new rs(e,t))}mixKey(e,t){const[r,n]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(n),e.ck=r}initializeKey(e){return{k:e,n:new Sl}}initializeSymmetric(e){const t=$t(e,"utf-8"),r=this.hashProtocolName(t),n=r,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:n,h:r}}hashProtocolName(e){if(e.length<=32){const t=N(32);return t.set(e),t}return this.getHash(e,N(0))}split(e){const[t,r]=this.crypto.getHKDF(e.ck,N(0));return{cs1:this.initializeKey(t),cs2:this.initializeKey(r)}}writeMessageRegular(e,t){const r=this.encryptWithAd(e,N(0),t);return{ne:this.createEmptyKey(),ns:N(0),ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,N(0),t.ciphertext)}}class Al extends _l{initializeInitiator(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}initializeResponder(e,t,r,n){const s=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(s,e),{ss:s,s:t,rs:r,psk:n,re:N(32)}}writeMessageA(e,t,r){const n=N(0);e.e=void 0!==r?r:this.crypto.generateX25519KeyPair();const s=e.e.publicKey;return this.mixHash(e.ss,s),{ne:s,ns:n,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const n=e.s.publicKey,s=this.encryptAndHash(e.ss,n);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.re)),{ne:r,ns:s,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageC(e,t){const r=e.s.publicKey,n=this.encryptAndHash(e.ss,r);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const s=this.encryptAndHash(e.ss,t),i={ne:this.createEmptyKey(),ns:n,ciphertext:s},{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,messageBuffer:i,cs1:o,cs2:a}}readMessageA(e,t){return El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(El(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);n&&El(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:n&&i}}readMessageC(e,t){const{plaintext:r,valid:n}=this.decryptAndHash(e.ss,t.ns);if(n&&El(r)&&(e.rs=r),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:i}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:o,cs2:a}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:n&&i,cs1:o,cs2:a}}initSession(e,t,r){const n=this.createEmptyKey(),s=N(32);let i;return i=e?this.initializeInitiator(t,r,s,n):this.initializeResponder(t,r,s,n),{hs:i,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){const{h:r,messageBuffer:s,cs1:i,cs2:o}=this.writeMessageC(e.hs,t);n=s,e.h=r,e.cs1=i,e.cs2=o}else{if(!(e.mc>2))throw new Error("Session invalid.");if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");n=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");n=this.writeMessageRegular(e.cs2,t)}}return e.mc++,n}recvMessage(e,t){let r=N(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){const{h:s,plaintext:i,valid:o,cs1:a,cs2:c}=this.readMessageC(e.hs,t);r=i,n=o,e.h=s,e.cs1=a,e.cs2=c}return e.mc++,{plaintext:r,valid:n}}}function Il(e,t){t.enabled&&_i&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${An(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function kl(e,t){t.enabled&&_i&&t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${An(e.subarray(),"hex")}`)}class Rl{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(e,t,r,n,s,i,o,a,c){this.log=e.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=t,this.payload=r,this.prologue=n,this.staticKeypair=i,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new Al(e,s),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&&_i&&(t(`LOCAL_STATIC_PUBLIC_KEY ${An(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${An(e.privateKey,"hex")}`)),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");const e=this.xx.sendMessage(this.session,N(0));await this.connection.write(function(e){return new rs(e.ne,e.ciphertext)}(e)),this.log.trace("Stage 0 - Initiator finished sending first message."),Il(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");const e=function(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:N(0)}}((await this.connection.read()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new $a("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),kl(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");const r=function(e){if(e.length<80)throw new 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:s}=this.xx.recvMessage(this.session,r);if(!s)throw new $a("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),kl(this.session.hs.re,this.log),e=this.session.hs.rs,(t=this.log).enabled&&_i&&t(`REMOTE_STATIC_PUBLIC_KEY ${An(e.subarray(),"hex")}`),this.log.trace("Initiator going to check remote's signature...");try{const e=bl(n);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`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.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ne,e.ns,e.ciphertext)}(e)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Il(this.session.hs.e,this.log)}var e,t}async finish(){if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");const e=this.xx.sendMessage(this.session,this.payload);await this.connection.write(function(e){return new rs(e.ns,e.ciphertext)}(e)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");const e=function(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:N(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 $a("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{const e=bl(t);this.remotePeer=this.remotePeer||await ml(e),await vl(this.session.hs.rs,e,this.remotePeer),this.setRemoteNoiseExtension(e.extensions)}catch(e){throw new ja(`Error occurred while verifying signed payload: ${e.message}`)}}var e,t;e=this.session,(t=this.log).enabled&&_i&&(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${An(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${An(e.cs2.k,"hex")}`)):t("Missing cipher state."))}encrypt(e,t){const r=this.getCS(t);return this.xx.encryptWithAd(r,N(0),e)}decrypt(e,t,r){const n=this.getCS(t,!1);return this.xx.decryptWithAd(n,N(0),e,r)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new $a("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 Tl{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:o}=e;this.components=e,this.crypto=s??Va,this.extensions=n,this.metrics=o?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(o):void 0,this.staticKeys=r?this.crypto.generateX25519KeyPairFromSeed(r):this.crypto.generateX25519KeyPair(),this.prologue=i??N(0)}async secureOutbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!0,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,r){const n=vi(t,{lengthEncoder:qa,lengthDecoder:Ha,maxDataLength:Si}),s=await this.performHandshake({connection:n,isInitiator:!1,localPeer:e,remotePeer:r}),i=await this.createSecureConnection(n,s);return t.source=i.source,t.sink=i.sink,{conn:t,remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){const t=await yl(e.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(e,t)}async performXXHandshake(e,t){const{isInitiator:r,remotePeer:n,connection:s}=e,i=new Rl(this.components,r,t,this.prologue,this.crypto,this.staticKeys,s,n);try{await i.propose(),await i.exchange(),await i.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 i}async createSecureConnection(e,t){const[r,n]=function(){const e=Ei(),t=Ei();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await ys(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i),e.session):e.encrypt(n.sublist(r,i),e.session),t?.encryptedPackets.increment(),yield new rs(qa(s.byteLength),s)}}}(t,this.metrics),s,(e=>ls(e,{lengthDecoder:Ha})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(s=n.length),s-16new Tl(t,e)}const Pl=Symbol.for("@libp2p/peer-discovery"),Bl=45,Dl=15,Nl=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const 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((()=>{const 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 s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;tthis.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]}const 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((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function xl(e){return Boolean(function(e){if(!(e.length>Dl))return Nl.new(e).parseWith((()=>Nl.readIPv4Addr()))}(e))}function Ll(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPv6Addr()))}(e))}function Ol(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Bl))return Nl.new(e).parseWith((()=>Nl.readIPAddr()))}(e))}parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);const Ml=xl,Ul=Ll,Kl=function(e){let t=0;if(e=e.toString().trim(),Ml(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Ul(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n>8&255,s[t++]=255&e}return s}throw new Error("invalid ip address")},Fl=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let s=0;s65536)throw new Error("Port number is not in range(1, 65536)");const s=Yl(n);return Jn([r,s],r.length+s.length)}(t);case 445:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=Ce.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=Yl(n);return Jn([r,s],r.length+s.length)}(t);case 466:return function(e){const t=Wl.decode(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}(t);case 481:return Jl(globalThis.decodeURIComponent(t));default:return $t(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Vl,"ip6zone"],[43,8,"ipcidr"],[53,Vl,"dns",!0],[54,Vl,"dns4",!0],[55,Vl,"dns6",!0],[56,Vl,"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,Vl,"unix",!1,!0],[421,Vl,"ipfs"],[421,Vl,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Vl,"garlic64"],[448,0,"tls"],[449,Vl,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Vl,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Vl,"http-path"],[777,Vl,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(s)}}(...e);Hl[t.code]=t,ql[t.name]=t})),jl("ip4"),jl("ip6"),jl("ipcidr");const Gl=Object.values(Ft).map((e=>e.decoder)),Wl=function(){let e=Gl[0].or(Gl[1]);return Gl.slice(2).forEach((t=>e=e.or(t))),e}();function Yl(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Xl(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Jl(e){const t=$t(e),r=Uint8Array.from(G(t.length));return Jn([r,t],r.length+t.length)}function Ql(e){const t=W(e);if((e=e.slice(j(t))).length!==t)throw new Error("inconsistent lengths");return An(e)}function Zl(e){const t=[],r=[];let n=null,s=0;for(;se.length)throw su("Invalid address Uint8Array: "+An(e,"base16"));t.push([i,l]);const u=$l(i,l);if(r.push([i,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:eu(r),tuples:t,stringTuples:r,path:n}}function eu(e){const t=[];return e.map((e=>{const r=jl(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),nu(t.join("/"))}function tu(e){return Jn(e.map((e=>{const t=jl(e[0]);let r=Uint8Array.from(G(t.code));return e.length>1&&null!=e[1]&&(r=Jn([r,e[1]])),r})))}function ru(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=W(t instanceof Uint8Array?t:Uint8Array.from(t));return e+j(e)}}function nu(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function su(e){return new Error("Error parsing address: "+e)}const iu=Symbol.for("nodejs.util.inspect.custom"),ou=Symbol.for("@multiformats/js-multiaddr/multiaddr"),au=[jl("dns").code,jl("dns4").code,jl("dns6").code,jl("dnsaddr").code];class cu{bytes;#t;#r;#n;#s;[ou]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=Zl(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw new Error(`multiaddr "${e}" must start with a "/"`);t=function(e){const t=[],r=[];let n=null;const s=(e=nu(e)).split("/").slice(1);if(1===s.length&&""===s[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i=s.length)throw su("invalid address: "+e);if(!0===o.path){n=nu(s.slice(i).join("/")),t.push([o.code,zl(o.code,n)]),r.push([o.code,n]);break}const a=zl(o.code,s[i]);t.push([o.code,a]),r.push([o.code,$l(o.code,a)])}return{string:eu(r),bytes:tu(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!uu(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=Zl(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#s=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";const i=jl("tcp"),o=jl("udp"),a=jl("ip4"),c=jl("ip6"),l=jl("dns6"),u=jl("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(s=`%${d??""}`),au.includes(h)&&(t=i.name,n=443,r=`${d??""}${s}`,e=h===l.code?6:4),h!==i.code&&h!==o.code||(t=jl(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=jl(h).name,r=`${d??""}${s}`,e=h===c.code?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}protos(){return this.#r.map((([e])=>Object.assign({},jl(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>jl(e).name))}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new cu(e),new cu(this.toString()+e.toString())}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new cu(r.slice(0,n))}decapsulateCode(e){const t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new cu(tu(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===ql.p2p.code&&e.push([t,r]),t===ql["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?An(Fe.decode(`z${e}`),"base58btc"):An(Lt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#s}equals(e){return Qn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=lu.get(t.name);if(null==r)throw new Ga(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await r(this,e)).map((e=>hu(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){const t=(e??this).protos();return!(2!==t.length||4!==t[0].code&&41!==t[0].code||6!==t[1].code&&273!==t[1].code)}[iu](){return`Multiaddr(${this.#t})`}}const lu=new Map;function uu(e){return Boolean(e?.[ou])}function hu(e){return new cu(e)}const du=Hu("dns4"),pu=Hu("dns6"),fu=Hu("dnsaddr"),gu=qu(Hu("dns"),fu,du,pu),yu=qu(Hu("ip4"),Hu("ip6")),mu=qu(Vu(yu,Hu("tcp")),Vu(gu,Hu("tcp"))),bu=Vu(yu,Hu("udp")),wu=Vu(bu,Hu("utp")),vu=Vu(bu,Hu("quic")),Eu=Vu(bu,Hu("quic-v1")),Su=qu(Vu(mu,Hu("ws")),Vu(gu,Hu("ws"))),_u=qu(Vu(Su,Hu("p2p")),Su),Au=qu(Vu(mu,Hu("wss")),Vu(gu,Hu("wss")),Vu(mu,Hu("tls"),Hu("ws")),Vu(gu,Hu("tls"),Hu("ws"))),Iu=qu(Vu(Au,Hu("p2p")),Au),ku=qu(Vu(mu,Hu("http")),Vu(yu,Hu("http")),Vu(gu,Hu("http"))),Ru=qu(Vu(mu,Hu("https")),Vu(yu,Hu("https")),Vu(gu,Hu("https"))),Tu=Vu(bu,Hu("webrtc-direct"),Hu("certhash")),Cu=qu(Vu(Tu,Hu("p2p")),Tu),Pu=Vu(Eu,Hu("webtransport"),Hu("certhash"),Hu("certhash")),Bu=qu(Vu(Pu,Hu("p2p")),Pu),Du=qu(Vu(_u,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(Iu,Hu("p2p-webrtc-star"),Hu("p2p")),Vu(_u,Hu("p2p-webrtc-star")),Vu(Iu,Hu("p2p-webrtc-star"))),Nu=(qu(Vu(_u,Hu("p2p-websocket-star"),Hu("p2p")),Vu(Iu,Hu("p2p-websocket-star"),Hu("p2p")),Vu(_u,Hu("p2p-websocket-star")),Vu(Iu,Hu("p2p-websocket-star"))),qu(Vu(ku,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(Ru,Hu("p2p-webrtc-direct"),Hu("p2p")),Vu(ku,Hu("p2p-webrtc-direct")),Vu(Ru,Hu("p2p-webrtc-direct")))),xu=qu(Su,Au,ku,Ru,Du,Nu,mu,wu,vu,gu,Cu,Bu),Lu=(qu(Vu(xu,Hu("p2p-stardust"),Hu("p2p")),Vu(xu,Hu("p2p-stardust"))),qu(Vu(xu,Hu("p2p")),Du,Nu,Cu,Bu,Hu("p2p"))),Ou=qu(Vu(Lu,Hu("p2p-circuit"),Lu),Vu(Lu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),Lu),Vu(xu,Hu("p2p-circuit")),Vu(Hu("p2p-circuit"),xu),Hu("p2p-circuit")),Mu=()=>qu(Vu(Ou,Mu),Ou),Uu=Mu(),Ku=qu(Vu(Uu,Lu,Uu),Vu(Lu,Uu),Vu(Uu,Lu),Uu,Lu);function Fu(e){return function(t){let r;try{r=hu(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Vu(...e){function t(t){if(t.length(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Fu(t),partialMatch:t}}function qu(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Fu(t),partialMatch:t}}function Hu(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=hu(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}qu(Vu(Uu,Hu("webrtc"),Hu("p2p")),Vu(Uu,Hu("webrtc")),Vu(xu,Hu("webrtc"),Hu("p2p")),Vu(xu,Hu("webrtc")),Hu("webrtc"));class ju extends ni{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!Ku.matches(e)){this.log.error("Invalid multiaddr");continue}const t=hu(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:hl(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Pl]=this;[Symbol.toStringTag]="@libp2p/bootstrap";isStarted(){return Boolean(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(const 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}}const $u=Uint8Array.from([3,1]);var zu;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.peerId=t.bytes();break;case 2:n.seq=t.uint64();break;case 3:n.addresses.push(e.AddressInfo.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return n}))),r),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(zu||(zu={}));class Gu{static createFromProtobuf=e=>{const t=zu.decode(e),r=dl(t.peerId),n=(t.addresses??[]).map((e=>hu(e.multiaddr))),s=t.seq;return new Gu({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=$u;peerId;multiaddrs;seqNumber;domain=Gu.DOMAIN;codec=Gu.CODEC;marshaled;constructor(e){const{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=zu.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Gu&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const 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 Wu(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const Yu=32,Xu=64,Ju=32;function Qu(e,t){const r=new Uint8Array(Xu);for(let n=0;nFr(nh)}(rh||(rh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(sh||(sh={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),rh.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=rh.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(ih||(ih={}));class oh{_key;constructor(e){this._key=dh(e,Yu)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return sh.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class ah{_key;_publicKey;constructor(e,t){this._key=dh(e,Xu),this._publicKey=dh(t,Yu)}sign(e){return function(e,t){const r=e.subarray(0,Ju);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new oh(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function ch(e){if(e.length>Xu){const t=(e=dh(e,Xu+Yu)).subarray(0,Xu),r=e.subarray(Xu,e.length);return new ah(t,r)}const t=(e=dh(e,Xu)).subarray(0,Xu),r=e.subarray(Yu);return new ah(t,r)}function lh(e){return e=dh(e,Yu),new oh(e)}async function uh(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Qu(e,t),publicKey:t}}();return new ah(e,t)}async function hh(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==Ju)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Qu(t,r),publicKey:r}}(e);return new ah(t,r)}function dh(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function ph(e){const t=[await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await gh(e)],r=await fh({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function fh(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Zu.get().subtle.exportKey("jwk",e.privateKey),Zu.get().subtle.exportKey("jwk",e.publicKey)])}async function gh(e){return Zu.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 yh(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}async function mh(e,t,r,n){const{c:s,dkLen:i,asyncTick:o,DK:a,PRF:c,PRFSalt:l}=function(e,t,r,n){Wr(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!==on.call(t))throw new Error("Options should be object or undefined");return Object.assign({dkLen:32,asyncTick:10},t)}(0,n),{c:i,dkLen:o,asyncTick:a}=s;if(zr(i),zr(o),zr(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=rn(t),l=rn(r),u=new Uint8Array(o),h=Ua.create(e,c),d=h._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n);let u;const h=new Uint8Array(4),d=Jr(h),p=new Uint8Array(c.outputLen);for(let e=1,t=0;t{c._cloneInto(u).update(p).digestInto(p);for(let e=0;e=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function vh(e,t,r=-1){const n=r;let s=e,i=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e=0;e--){const r=Math.pow(2,e*t);o[i-e-1]=Math.floor(s/r),s-=o[i-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function Eh(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),s=new Uint8Array(n);for(const t of e)s.set(t,r),r+=t.length;return s}function Sh(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e=s.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=n.subarray(o,o+i);return 0===a[i-1]&&this.warnings.push("Needlessly long encoded length"),this.length=wh(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const n=vh(this.length,8);if(n.byteLength>127)return this.error="Too big length",Bh;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const s=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e=37&&!1===s.idBlock.isHexOnly)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};a=Vh.EndOfContent;break;case 1:a=Vh.Boolean;break;case 2:a=Vh.Integer;break;case 3:a=Vh.BitString;break;case 4:a=Vh.OctetString;break;case 5:a=Vh.Null;break;case 6:a=Vh.ObjectIdentifier;break;case 10:a=Vh.Enumerated;break;case 12:a=Vh.Utf8String;break;case 13:a=Vh.RelativeObjectIdentifier;break;case 14:a=Vh.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:a=Vh.Sequence;break;case 17:a=Vh.Set;break;case 18:a=Vh.NumericString;break;case 19:a=Vh.PrintableString;break;case 20:a=Vh.TeletexString;break;case 21:a=Vh.VideotexString;break;case 22:a=Vh.IA5String;break;case 23:a=Vh.UTCTime;break;case 24:a=Vh.GeneralizedTime;break;case 25:a=Vh.GraphicString;break;case 26:a=Vh.VisibleString;break;case 27:a=Vh.GeneralString;break;case 28:a=Vh.UniversalString;break;case 29:a=Vh.CharacterString;break;case 30:a=Vh.BmpString;break;case 31:a=Vh.DATE;break;case 32:a=Vh.TimeOfDay;break;case 33:a=Vh.DateTime;break;case 34:a=Vh.Duration;break;default:{const e=s.idBlock.isConstructed?new Vh.Constructed:new Vh.Primitive;e.idBlock=s.idBlock,e.lenBlock=s.lenBlock,e.warnings=s.warnings,s=e}}}else a=s.idBlock.isConstructed?Vh.Constructed:Vh.Primitive;return s=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(s,a),o=s.fromBER(e,t,s.lenBlock.isIndefiniteForm?r:s.lenBlock.length),s.valueBeforeDecodeView=e.subarray(n,n+s.blockLength),{offset:o,result:s}}function Rd(e){if(!e.byteLength){const e=new qh({},Uh);return e.error="Input buffer has zero length",{offset:-1,result:e}}return kd(bh._H.toUint8Array(e).slice(),0,e.byteLength)}zh=Id,Vh.Primitive=zh,Id.NAME="PRIMITIVE";class Td extends Uh{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=bh._H.toUint8Array(e);if(!kh(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let s=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=kd(n,s,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Nh)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Nh?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){const r=t||new Rh;for(let t=0;t` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Gh=Cd,Vh.Constructed=Gh,Cd.NAME="CONSTRUCTED";class Pd extends Uh{fromBER(e,t,r){return t}toBER(e){return Bh}}Pd.override="EndOfContentValueBlock";class Bd extends qh{constructor(e={}){super(e,Pd),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Wh=Bd,Vh.EndOfContent=Wh,Bd.NAME=Nh;class Dd extends qh{constructor(e={}){super(e,Uh),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){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Yh=Dd,Vh.Null=Yh,Dd.NAME="NULL";class Nd extends(Oh(Uh)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=bh._H.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){const n=bh._H.toUint8Array(e);return kh(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,Sh.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Nd.NAME="BooleanValueBlock";class xd extends qh{constructor(e={}){super(e,Nd),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}`}}Xh=xd,Vh.Boolean=Xh,xd.NAME="BOOLEAN";class Ld extends(Oh(Td)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,n=Td.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e0&&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}const s=bh._H.toUint8Array(e);if(!kh(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=i.subarray(1);try{if(e.byteLength){const t=kd(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+r}toBER(e,t){if(this.isConstructed)return Td.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Bh;const 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}}}Md.NAME="BitStringValueBlock";class Ud extends qh{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,s;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(s=r.value)||void 0===s?void 0:s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Md),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 Cd.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function Kd(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),s=new Uint8Array(t);let i=n.slice(0);const o=i.length-1,a=s.slice(0),c=a.length-1;let l=0,u=0;for(let e=c=0;e--,u++)l=1==u=i.length?i=Eh(new Uint8Array([l%10]),i):i[o-u]=l%10;return r[0]>0&&(i=Eh(r,i)),i}function Fd(e){if(e>=Th.length)for(let t=Th.length;t<=e;t++){const e=new Uint8Array([0]);let r=Th[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=Eh(e,r)),Th.push(r)}return Th[e]}function Vd(e,t){let r=0;const n=new Uint8Array(e),s=new Uint8Array(t),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=i[o-u]-a[c-u]-r,1==l<0?(r=1,i[o-u]=l+10):(r=0,i[o-u]=l);if(r>0)for(let e=o-c+1;e>=0;e--,u++){if(l=i[o-u]-r,!(l<0)){r=0,i[o-u]=l;break}r=1,i[o-u]=l+10}return i.slice()}Qh=Ud,Vh.BitString=Qh,Ud.NAME=Lh;class qd extends(Oh(Uh)){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=Sh.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){const e=vh(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let s=vh(t,8,n),i=new Uint8Array(s);if(128&i[0]){const e=s.slice(0),t=new Uint8Array(e);s=new ArrayBuffer(s.byteLength+1),i=new Uint8Array(s);for(let r=0;r1&&(n=i.length+1),this.valueHexView=i.subarray(n-i.length)),s}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const 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]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const 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(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),n=0;const s=this.valueHexView;let i="",o=!1;for(let o=s.byteLength-1;o>=0;o--){t=s[o];for(let s=0;s<8;s++)1&~t||(n===e?(r=Vd(Fd(n),r),i="-"):r=Kd(r,Fd(n))),n++,t>>=1}for(let e=0;e0;){const t=new $d;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){const t=[];for(let r=0;rNumber.MAX_SAFE_INTEGER){Ah();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,s=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r0;){const t=new Wd;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){const r=[];for(let t=0;t4)continue;const i=4-s.length;for(let e=s.length-1;e>=0;e--)r[4*n+e+i]=s[e]}this.valueBlock.value=e}}op.NAME="UniversalStringValueBlock";class ap extends op{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}cd=ap,Vh.UniversalString=cd,ap.NAME="UniversalString";class cp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ld=cp,Vh.NumericString=ld,cp.NAME="NumericString";class lp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}ud=lp,Vh.PrintableString=ud,lp.NAME="PrintableString";class up extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}hd=up,Vh.TeletexString=hd,up.NAME="TeletexString";class hp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}dd=hp,Vh.VideotexString=dd,hp.NAME="VideotexString";class dp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}pd=dp,Vh.IA5String=pd,dp.NAME="IA5String";class pp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}fd=pp,Vh.GraphicString=fd,pp.NAME="GraphicString";class fp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}gd=fp,Vh.VisibleString=gd,fp.NAME="VisibleString";class gp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}yd=gp,Vh.GeneralString=yd,gp.NAME="GeneralString";class yp extends tp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}md=yp,Vh.CharacterString=md,yp.NAME="CharacterString";class mp extends fp{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=50?1900+r: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){const e=new Array(7);return e[0]=_h(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=_h(this.month,2),e[2]=_h(this.day,2),e[3]=_h(this.hour,2),e[4]=_h(this.minute,2),e[5]=_h(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}}}bd=mp,Vh.UTCTime=bd,mp.NAME="UTCTime";class bp extends mp{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="",s="",i=0,o=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new 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 new Error("Wrong input string for conversion");let s=parseInt(r.substring(0,2),10);if(isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*s,4===r.length){if(s=parseInt(r.substring(2,4),10),isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");a=e*s}}}let c=n.indexOf(".");if(-1===c&&(c=n.indexOf(",")),-1!==c){const e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");i=e.valueOf(),s=n.substring(0,c)}else s=n;switch(!0){case 8===s.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*i;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===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(s);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}Ad=_p,Vh.TIME=Ad,_p.NAME="TIME";const Rp=8192;class Tp{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Zu.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return sh.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}}class Cp{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Ap(16)}sign(e){return async function(e,t){const r=await Zu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Zu.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Tp(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(kp($t(e.n,"base64url"))),Hd.fromBigInt(kp($t(e.e,"base64url"))),Hd.fromBigInt(kp($t(e.d,"base64url"))),Hd.fromBigInt(kp($t(e.p,"base64url"))),Hd.fromBigInt(kp($t(e.q,"base64url"))),Hd.fromBigInt(kp($t(e.dp,"base64url"))),Hd.fromBigInt(kp($t(e.dq,"base64url"))),Hd.fromBigInt(kp($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return ih.encode({Type:rh.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Zu.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Ap(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Ap(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Pp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Ip(r[1].toBigInt()),"base64url"),e:An(Ip(r[2].toBigInt()),"base64url"),d:An(Ip(r[3].toBigInt()),"base64url"),p:An(Ip(r[4].toBigInt()),"base64url"),q:An(Ip(r[5].toBigInt()),"base64url"),dp:An(Ip(r[6].toBigInt()),"base64url"),dq:An(Ip(r[7].toBigInt()),"base64url"),qi:An(Ip(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await ph(t);return new Cp(r.privateKey,r.publicKey)}function Bp(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Ip(r[0].toBigInt()),"base64url"),e:An(Ip(r[1].toBigInt()),"base64url")}}(e);if(yh(t)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Tp(t)}async function Dp(e){if(yh(e)>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await ph(e);return new Cp(t.privateKey,t.publicKey)}async function Np(e){if(e>Rp)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Zu.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 fh(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Cp(t.privateKey,t.publicKey)}function xp(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Lp{_key;constructor(e){xp(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(Wu(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return sh.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return Wu(e)?({bytes:t}=await e):t=e.bytes,t}}class Op{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),xp(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(Wu(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Lp(this._publicKey)}marshal(){return this._key}get bytes(){return ih.encode({Type:rh.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return Wu(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return th(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Mp(e){return new Op(e)}function Up(e){return new Lp(e)}async function Kp(){const e=$c.utils.randomPrivateKey();return new Op(e)}const Fp={rsa:w,ed25519:b,secp256k1:v};function Vp(e){const t=Object.keys(Fp).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}var qp;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const 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>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(qp||(qp={}));class Hp{static createFromProtobuf=async e=>{const t=qp.decode(e),r=await pl(t.publicKey);return new Hp({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw new Error("Missing private key");const r=e.domain,n=e.codec,s=e.marshal(),i=jp(r,n,s),o=await async function(e){const t=ih.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPrivateKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PrivateKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Vp(t.Type??"RSA")}}(t.privateKey),a=await o.sign(i.subarray());return new Hp({peerId:t,payloadType:n,payload:s,signature:a})};static openAndCertify=async(e,t)=>{const r=await Hp.createFromProtobuf(e);if(!await r.validate(t))throw new Ga("envelope signature is not valid for the given domain","ERR_SIGNATURE_NOT_VALID");return r};peerId;payloadType;payload;signature;marshaled;constructor(e){const{peerId:t,payloadType:r,payload:n,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=qp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Qn(this.marshal(),e.marshal())}async validate(e){const t=jp(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw new Error("Missing public key");return function(e){const t=sh.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case rh.RSA:return Fp.rsa.unmarshalRsaPublicKey(r);case rh.Ed25519:return Fp.ed25519.unmarshalEd25519PublicKey(r);case rh.Secp256k1:return Fp.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Vp(t.Type??"unknown")}}(this.peerId.publicKey).verify(t.subarray(),this.signature)}}const jp=(e,t,r)=>{const n=$t(e),s=G(n.byteLength),i=G(t.length),o=G(r.length);return new rs(s,n,i,t,o,r)},$p=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),zp=e=>({match:t=>$p((t=>t===e)).match(t),pattern:e}),Gp=()=>({match:e=>$p((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Wp=()=>({match:e=>$p((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),Yp=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{Fe.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Xp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{je.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Jp=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Qp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.lengthe.pattern)).join(", ")})`}),Zp=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function ef(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const tf=Zp(zp("dns4"),Gp()),rf=Zp(zp("dns6"),Gp()),nf=Zp(zp("dnsaddr"),Gp()),sf=Zp(zp("dns"),Gp()),of=(ef(tf),ef(rf),ef(nf),ef(Qp(sf,nf,tf,rf)),Zp(zp("ip4"),$p(xl))),af=Zp(zp("ip6"),$p(Ll)),cf=Qp(of,af),lf=Qp(cf,sf,tf,rf,nf),uf=ef(lf),hf=(ef(of),ef(af),ef(cf),Zp(lf,zp("tcp"),Wp())),df=Zp(lf,zp("udp"),Wp()),pf=(ef(hf),ef(df),Zp(df,zp("quic"))),ff=Zp(df,zp("quic-v1")),gf=Qp(pf,ff),yf=(ef(pf),ef(ff),Qp(lf,hf,df,pf,ff)),mf=Qp(Zp(yf,zp("ws"),Jp(Yp()))),bf=(ef(mf),Qp(Zp(yf,zp("wss"),Jp(Yp())),Zp(yf,zp("tls"),zp("ws"),Jp(Yp())))),wf=(ef(bf),Zp(df,zp("webrtc-direct"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),vf=(ef(wf),Zp(ff,zp("webtransport"),Jp(Xp()),Jp(Xp()),Jp(Yp()))),Ef=(ef(vf),Qp(mf,bf,Zp(hf,Jp(Yp())),Zp(gf,Jp(Yp())),Zp(lf,Jp(Yp())),wf,vf,Yp())),Sf=(ef(Ef),ef(Zp(Ef,zp("p2p-circuit"),Yp())));function _f(e,t){const r=vi(e,t),n={read:async(e,t)=>{const 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}ef(Qp(Zp(Ef,zp("p2p-circuit"),zp("webrtc"),Jp(Yp())),Zp(Ef,zp("webrtc"),Jp(Yp())),zp("webrtc"))),ef(Qp(Zp(lf,zp("tcp"),Wp(),zp("http"),Jp(Yp())),Zp(lf,zp("http"),Jp(Yp())))),ef(Qp(Zp(lf,zp("tcp"),Qp(Zp(zp("443"),zp("http")),Zp(Wp(),zp("https"))),Jp(Yp())),Zp(lf,zp("tls"),zp("http"),Jp(Yp())),Zp(lf,zp("https"),Jp(Yp()))));var Af=__webpack_require__(4866);const If="object"==typeof window&&"object"==typeof document&&9===document.nodeType,kf=Af(),Rf=If&&!kf,Tf=kf&&!If,Cf=kf&&If,Pf=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!kf,Bf="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Df=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product);var Nf;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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(const 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(const 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)=>{const r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Nf||(Nf={}));const xf=8192,Lf="ipfs";class Of{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??Lf}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Lf}/id/push/1.0.0`,this.timeout=t.timeout??6e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxPushIncomingStreams=t.maxPushIncomingStreams??1,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??1,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnTransientConnection=t.runOnTransientConnection??true,this.host={protocolVersion:`${t.protocolPrefix??Lf}/0.1.0`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??true)&&e.events.addEventListener("connection:open",(e=>{const 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}`&&(Pf||Tf?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Rf||Bf||Cf||Df)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:$t(this.host.agentVersion),ProtocolVersion:$t(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){const t=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code))),r=new Gu({peerId:this.peerId,multiaddrs:t}),n=await Hp.seal(r,this.peerId),s=this.registrar.getProtocols(),i=await this.peerStore.get(this.peerId),o=An(i.metadata.get("AgentVersion")??$t(this.host.agentVersion)),a=An(i.metadata.get("ProtocolVersion")??$t(this.host.protocolVersion)),c=e.map((async e=>{let r;const i=AbortSignal.timeout(this.timeout);try{r=await e.newStream(this.identifyPushProtocolStr,{signal:i,runOnTransientConnection:this.runOnTransientConnection});const c=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf);await c.write({listenAddrs:t.map((e=>e.bytes)),signedPeerRecord:n.marshal(),protocols:s,agentVersion:o,protocolVersion:a},{signal:i}),await r.close({signal:i})}catch(e){this.log.error("could not push identify update to peer",e),r?.abort(e)}}));await Promise.all(c)}async push(){if(!this.isStarted())return;const e=[];await Promise.all(this.connectionManager.getConnections().map((async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).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){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});const n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),s=await n.read(t);return await r.close(t),s}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Ga("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const o=await pl(n);if(!e.remotePeer.equals(o))throw new Ga("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new Ga("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return hu(e)}catch{}}(i);return this.log("identify completed for peer %p and protocols %o",o,s),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.#i(e,r)}async _handleIdentify(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=this.peerId.publicKey??new Uint8Array(0),s=await this.peerStore.get(this.peerId),i=this.addressManager.getAddresses().map((e=>e.decapsulateCode(jl("p2p").code)));let o=s.peerRecordEnvelope;if(i.length>0&&null==o){const e=new Gu({peerId:this.peerId,multiaddrs:i});o=(await Hp.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;uf.matches(t.remoteAddr)||(a=void 0);const c=_f(r).pb(Nf);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:o,observedAddr:a,protocols:s.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){const{connection:t,stream:r}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const e={signal:AbortSignal.timeout(this.timeout)},n=_f(r,{maxDataLength:this.maxIdentifyMessageSize??xf}).pb(Nf),s=await n.read(e);await r.close(e),await this.#i(t,s)}catch(e){return this.log.error("received invalid message",e),void r.abort(e)}this.log("handled push from %p",t.remotePeer)}async#i(e,t){if(this.log("received identify from %p",e.remotePeer),null==t)throw new Ga("message was null or undefined","ERR_INVALID_MESSAGE");const r={};if(t.listenAddrs.length>0&&(r.addresses=t.listenAddrs.map((e=>({isCertified:!1,multiaddr:hu(e)})))),t.protocols.length>0&&(r.protocols=t.protocols),null!=t.publicKey&&(r.publicKey=t.publicKey,!(await pl(t.publicKey)).equals(e.remotePeer)))throw new Ga("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let n;if(null!=t.signedPeerRecord){this.log("received signedPeerRecord from %p",e.remotePeer);let s=t.signedPeerRecord;const i=await Hp.openAndCertify(s,Gu.DOMAIN);let o,a=Gu.createFromProtobuf(i.payload);if(!a.peerId.equals(i.peerId))throw new Ga("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(a.peerId))throw new Ga("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{o=await this.peerStore.get(a.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=o&&(r.metadata=o.metadata,null!=o.peerRecordEnvelope)){const e=await Hp.createFromProtobuf(o.peerRecordEnvelope),t=Gu.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=o.peerRecordEnvelope)}r.peerRecordEnvelope=s,r.addresses=a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),n={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,r),await this.peerStore.patch(e.remotePeer,r),null!=t.agentVersion||null!=t.protocolVersion){const r={};null!=t.agentVersion&&(r.AgentVersion=$t(t.agentVersion)),null!=t.protocolVersion&&(r.ProtocolVersion=$t(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,r),await this.peerStore.merge(e.remotePeer,{metadata:r})}const s={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map((e=>hu(e))),observedAddr:null==t.observedAddr?void 0:hu(t.observedAddr),protocols:t.protocols,signedPeerRecord:n,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:s}),s}}function Mf(e={}){return t=>new Of(t,e)}function Uf(e,t){const 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 new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Kf=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Ff=new WeakMap,Vf=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Kf());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Kf())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),Ff.set(u,(()=>{c(i),i=null,o()})),u}}();class qf{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 Hf}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Ga("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const 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 null!=e?.customDuration&&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 Hf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var jf;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(jf||(jf={}));const $f=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),zf=Object.freeze({NEW_STREAM:jf.NEW_STREAM,MESSAGE:jf.MESSAGE_INITIATOR,CLOSE:jf.CLOSE_INITIATOR,RESET:jf.RESET_INITIATOR}),Gf=Object.freeze({MESSAGE:jf.MESSAGE_RECEIVER,CLOSE:jf.CLOSE_RECEIVER,RESET:jf.RESET_RECEIVER}),Wf=1<<20;class Yf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Wf,t=4194304){this._buffer=new rs,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(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const 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}const{id:e,type:r,length:n,offset:s}=this._headerInfo;if(this._buffer.length-sthis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:i,offset:r+s,length:n}}}const Xf=128,Jf=127;function Qf(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&Jf)<=Xf);return{value:n,offset:t=i-t}}const Zf=10240,eg=new class{_pool;_poolOffset;constructor(){this._pool=x(Zf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;G(e.id<<3|e.type,r,n),n+=j(e.id<<3|e.type),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data?(G(0,r,n),n+=j(0)):(G(e.data.length,r,n),n+=j(e.data.length));const s=r.subarray(this._poolOffset,n);Zf-n<100?(this._pool=x(Zf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==jf.NEW_STREAM&&e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function tg(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class rg{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=us(),this.closed=us(),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=fs({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 Ga(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);tg(e)&&await e}const r=()=>{Uf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new rs(r):r;const e=this.sendData(r,t);tg(e)&&(this.sendingData=us(),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 gi(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);const 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 gi(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await gi(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await gi(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");const t=this.sendReset();tg(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;const e=new Ga("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(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class ng extends rg{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?zf:Gf,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:zf.NEW_STREAM,data:new rs($t(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const 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 sg(e){const t={...e,type:`${$f[e.type]} (${e.type})`};return e.type===jf.NEW_STREAM&&(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==jf.MESSAGE_INITIATOR&&e.type!==jf.MESSAGE_RECEIVER||(t.data=An(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class ig{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=fs({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=ys(this._source,(e=>async function*(e){for await(const t of e){const e=new rs;eg.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new qf({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const 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){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Ga("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=Wf}=e;return new ng({id:"initiator"===i?`i${t}`:`r${t}`,streamId:t,name:`${null==r?t:r}`,direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,sg(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Uf(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Yf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const 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)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",sg(e)),e.type===jf.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:jf.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(new Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:An(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,$f[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case jf.MESSAGE_INITIATOR:case jf.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===jf.MESSAGE_INITIATOR?jf.RESET_RECEIVER:jf.RESET_INITIATOR}),new Ga("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case jf.CLOSE_INITIATOR:case jf.CLOSE_RECEIVER:n.remoteCloseWrite();break;case jf.RESET_INITIATOR:case jf.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class og{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new ig(this.components,{...e,...this._init})}}function ag(e={}){return t=>new og(t,e)}const cg="ERR_WRONG_PING_ACK";class lg{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);const{stream:t}=e,r=Date.now();ys(t,t).catch((t=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,t)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=function(e){if(isNaN(32))throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(32)}(),s=await this.components.connectionManager.openConnection(e,t);let i,o=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),o=()=>{i?.abort(new Ga("ping timeout",Ya))},t.signal?.addEventListener("abort",o,{once:!0});const e=await ys([n],i,(async e=>function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e)return t})();for(const t of e)return t}(e))),a=Date.now()-r;if(null==e)throw new Ga(`Did not receive a ping ack after ${a}ms`,cg);if(!Qn(n,e.subarray()))throw new Ga(`Received wrong ping ack after ${a}ms`,cg);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),i?.abort(e),e}finally{t.signal?.removeEventListener("abort",o),null!=i&&await i.close()}}}function ug(e={}){return t=>new lg(t,e)}const hg=Symbol.for("@libp2p/transport");var dg;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(dg||(dg={}));const pg=[jl("tcp").code,jl("dns").code,jl("dnsaddr").code,jl("dns4").code,jl("dns6").code];function fg(e){let t;try{t=jl("sni").code}catch(e){return null}for(const[r,n]of e)if(r===t&&void 0!==n)return n;return null}function gg(e){return e.some((([e,t])=>e===jl("tls").code))}function yg(e,t,r){const n=mg[jl(e).name];if(void 0===n)throw new Error(`Can't interpret protocol ${jl(e).name}`);const s=n(t,r);return e===jl("ip6").code?`[${s}]`:s}const mg={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`tcp://${yg(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`udp://${yg(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)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`https://${n}`;const s=r?"https://":"http://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return yg(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return yg(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=yg(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=gg(t),n=fg(t);if(r&&null!==n)return`wss://${n}`;const s=r?"wss://":"ws://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=yg(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=yg(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${yg(r[0],r[1]??"",t)}/p2p-webrtc-direct`}},bg=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",i)}))},wg=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await bg(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{const t=Object.assign(new Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))});var vg=__webpack_require__(544);function Eg(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Sg=WebSocket,_g={"http:":"ws:","https:":"wss:"};function Ag(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(_g))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new vg.PP((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=$t(e.data)),Eg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Eg(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:wg(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:s,socket:e}})(new Sg(r.toString(),t.websocket),t)}const Ig=421,kg=290;function Rg(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return Iu.matches(t)}))}class Tg{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[hg]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s={log:n,async sink(t){try{await e.sink(async function*(){for await(const 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={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const i=()=>{const{host:e,port:t}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Ga("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",i);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",i),s.timeline.close=Date.now()}},abort(t){const{host:r,port:i}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,i,t),e.destroy(),s.timeline.close=Date.now()}};return e.socket.addEventListener("close",(()=>{null==s.timeline.close&&(s.timeline.close=Date.now())}),{once:!0}),s}(await this._connect(e,t),e,{logger:this.logger});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){if(!0===t?.signal?.aborted)throw new za;const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=us(),s=Ag(function(e,t){const r=hu(e).stringTuples(),n=r.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");const s=jl(n[0]),i=mg[s.name];if(null==i)throw new Error(`No interpreter found for ${s.name}`);let o=i(n[1]??"",r);return pg.includes(n[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===n[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}(e),this.init);if(s.socket.addEventListener("error",(()=>{const t=new Ga(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),n.reject(t)})),null==t.signal)return await Promise.race([s.connected(),n.promise]),this.log("connected %s",e),s;let i;const o=new Promise(((e,r)=>{i=()=>{r(new za),s.close().catch((e=>{this.log.error("error closing raw socket",e)}))},!0!==t?.signal?.aborted?t?.signal?.addEventListener("abort",i):i()}));try{await Promise.race([o,n.promise,s.connected()])}finally{null!=i&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}(this.logger,this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Rf||Bf?Rg(e):function(e){return e.filter((e=>{if(e.protoCodes().includes(kg))return!1;const t=e.decapsulateCode(Ig);return _u.matches(t)||Iu.matches(t)}))}(e)}dialFilter(e){return this.listenFilter(e)}}function Cg(e={}){return t=>new Tg(t,e)}const Pg="StrictSign",Bg="StrictNoSign";var Dg;!function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"}(Dg||(Dg={}));const Ng="/floodsub/1.0.0",xg="/meshsub/1.0.0",Lg="/meshsub/1.1.0",Og=5e3,Mg={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var Ug,Kg,Fg,Vg,qg,Hg,jg,$g,zg,Gg,Wg,Yg;!function(e){let t,r,n,s,i,o,a,c,l;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.subscribe=e.bool();break;case 2:n.topic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(t=e.SubOpts||(e.SubOpts={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={topic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(r=e.Message||(e.Message={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.ihave)for(const n of t.ihave)r.uint32(10),e.ControlIHave.codec().encode(n,r);if(null!=t.iwant)for(const n of t.iwant)r.uint32(18),e.ControlIWant.codec().encode(n,r);if(null!=t.graft)for(const n of t.graft)r.uint32(26),e.ControlGraft.codec().encode(n,r);if(null!=t.prune)for(const n of t.prune)r.uint32(34),e.ControlPrune.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={ihave:[],iwant:[],graft:[],prune:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:if(null!=n.limits?.ihave&&s.ihave.length===n.limits.ihave)throw new qr('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");s.ihave.push(e.ControlIHave.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.iwant&&s.iwant.length===n.limits.iwant)throw new qr('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");s.iwant.push(e.ControlIWant.codec().decode(t,t.uint32()));break;case 3:if(null!=n.limits?.graft&&s.graft.length===n.limits.graft)throw new qr('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");s.graft.push(e.ControlGraft.codec().decode(t,t.uint32()));break;case 4:if(null!=n.limits?.prune&&s.prune.length===n.limits.prune)throw new qr('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");s.prune.push(e.ControlPrune.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(n=e.ControlMessage||(e.ControlMessage={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(18),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.topicID=e.string();break;case 2:if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('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}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(s=e.ControlIHave||(e.ControlIHave={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageIDs)for(const r of e.messageIDs)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messageIDs&&n.messageIDs.length===r.limits.messageIDs)throw new qr('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");n.messageIDs.push(e.bytes())}else e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(i=e.ControlIWant||(e.ControlIWant={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.topicID=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(o=e.ControlGraft||(e.ControlGraft={})),function(t){let r;t.codec=()=>(null==r&&(r=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.topicID&&(r.uint32(10),r.string(t.topicID)),null!=t.peers)for(const n of t.peers)r.uint32(18),e.PeerInfo.codec().encode(n,r);null!=t.backoff&&(r.uint32(24),r.uint64Number(t.backoff)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peers:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.topicID=t.string();break;case 2:if(null!=n.limits?.peers&&s.peers.length===n.limits.peers)throw new qr('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");s.peers.push(e.PeerInfo.codec().decode(t,t.uint32()));break;case 3:s.backoff=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),r),t.encode=e=>ir(e,t.codec()),t.decode=(e,r)=>ue(e,t.codec(),r)}(a=e.ControlPrune||(e.ControlPrune={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.peerID=e.bytes();break;case 2:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(c=e.PeerInfo||(e.PeerInfo={})),e.codec=()=>(null==l&&(l=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscriptions)for(const n of t.subscriptions)r.uint32(10),e.SubOpts.codec().encode(n,r);if(null!=t.messages)for(const n of t.messages)r.uint32(18),e.Message.codec().encode(n,r);null!=t.control&&(r.uint32(26),e.ControlMessage.codec().encode(t.control,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscriptions:[],messages:[]},i=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:if(null!=n.limits?.subscriptions&&s.subscriptions.length===n.limits.subscriptions)throw new qr('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");s.subscriptions.push(e.SubOpts.codec().decode(t,t.uint32()));break;case 2:if(null!=n.limits?.messages&&s.messages.length===n.limits.messages)throw new qr('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");s.messages.push(e.Message.codec().decode(t,t.uint32()));break;case 3:s.control=e.ControlMessage.codec().decode(t,t.uint32());break;default:t.skipType(7&r)}}return s}))),l),e.encode=t=>ir(t,e.codec()),e.decode=(t,r)=>ue(t,e.codec(),r)}(Ug||(Ug={}));class Xg{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let e=0;e{const 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){const t=this.msgs.get(e);if(null==t)return null;t.validated||this.notValidatedCount--;const{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach((e=>{const 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){const t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function Jg(e){switch(e){case Dg.Ignore:return Vg.Ignore;case Dg.Reject:return Vg.Reject;default:throw new Error("Unreachable")}}!function(e){e.StrictSign="StrictSign",e.StrictNoSign="StrictNoSign"}(Kg||(Kg={})),function(e){e[e.Signing=0]="Signing",e[e.Anonymous=1]="Anonymous"}(Fg||(Fg={})),function(e){e.Error="error",e.Ignore="ignore",e.Reject="reject",e.Blacklisted="blacklisted"}(Vg||(Vg={})),function(e){e.InvalidSignature="invalid_signature",e.InvalidSeqno="invalid_seqno",e.InvalidPeerId="invalid_peerid",e.SignaturePresent="signature_present",e.SeqnoPresent="seqno_present",e.FromPresent="from_present",e.TransformFailed="transform_failed"}(qg||(qg={})),function(e){e.duplicate="duplicate",e.invalid="invalid",e.valid="valid"}(Hg||(Hg={})),function(e){e.forward="forward",e.publish="publish"}(jg||(jg={})),function(e){e.Fanout="fanout",e.Random="random",e.Subscribed="subscribed",e.Outbound="outbound",e.NotEnough="not_enough",e.Opportunistic="opportunistic"}($g||($g={})),function(e){e.Dc="disconnected",e.BadScore="bad_score",e.Prune="prune",e.Excess="excess"}(zg||(zg={})),function(e){e.GraftBackoff="graft_backoff",e.BrokenPromise="broken_promise",e.MessageDeficit="message_deficit",e.IPColocation="IP_colocation"}(Gg||(Gg={})),function(e){e.LowScore="low_score",e.MaxIhave="max_ihave",e.MaxIasked="max_iasked"}(Wg||(Wg={})),function(e){e.graylist="graylist",e.publish="publish",e.gossip="gossip",e.mesh="mesh"}(Yg||(Yg={}));const Qg="ERR_INVALID_PEER_SCORE_PARAMS",Zg={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},ey={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};function ty(e={}){return{...Zg,...e,topics:null!=e.topics?Object.entries(e.topics).reduce(((e,[t,r])=>(e[t]=function(e={}){return{...ey,...e}}(r),e)),{}):{}}}function ry(e){if(e.topicWeight<0)throw new Ga("invalid topic weight; must be >= 0",Qg);if(0===e.timeInMeshQuantum)throw new Ga("invalid TimeInMeshQuantum; must be non zero",Qg);if(e.timeInMeshWeight<0)throw new Ga("invalid TimeInMeshWeight; must be positive (or 0 to disable)",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new Ga("invalid TimeInMeshQuantum; must be positive",Qg);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new Ga("invalid TimeInMeshCap; must be positive",Qg);if(e.firstMessageDeliveriesWeight<0)throw new Ga("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",Qg);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new Ga("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new Ga("invalid FirstMessageDeliveriesCap; must be positive",Qg);if(e.meshMessageDeliveriesWeight>0)throw new Ga("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new Ga("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new Ga("invalid MeshMessageDeliveriesCap; must be positive",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new Ga("invalid MeshMessageDeliveriesThreshold; must be positive",Qg);if(e.meshMessageDeliveriesWindow<0)throw new Ga("invalid MeshMessageDeliveriesWindow; must be non-negative",Qg);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new Ga("invalid MeshMessageDeliveriesActivation; must be at least 1s",Qg);if(e.meshFailurePenaltyWeight>0)throw new Ga("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new Ga("invalid MeshFailurePenaltyDecay; must be between 0 and 1",Qg);if(e.invalidMessageDeliveriesWeight>0)throw new Ga("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",Qg);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new Ga("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",Qg)}const ny={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function sy(e={}){return{...ny,...e}}function iy(e,t,r=(()=>!0)){const n=new Set;if(t<=0)return n;for(const s of e){if(n.size>=t)break;r(s)&&(n.add(s),e.delete(s))}return n}class oy 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 ay(e,t,r,n){let s=0;Object.entries(t.topics).forEach((([e,t])=>{const n=r.topics[e];if(void 0===n)return;let i=0;if(t.inMesh){let e=t.meshTime/n.timeInMeshQuantum;e>n.timeInMeshCap&&(e=n.timeInMeshCap),i+=e*n.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>n.firstMessageDeliveriesCap&&(o=n.firstMessageDeliveriesCap),i+=o*n.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&s>r.topicScoreCap&&(s=r.topicScoreCap);const i=r.appSpecificScore(e);if(s+=i*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),i=null!=t?t.size:0;if(i>r.IPColocationFactorThreshold){const e=i-r.IPColocationFactorThreshold;s+=e*e*r.IPColocationFactorWeight}})),t.behaviourPenalty>r.behaviourPenaltyThreshold){const e=t.behaviourPenalty-r.behaviourPenaltyThreshold;s+=e*e*r.behaviourPenaltyWeight}return s}var cy,ly=__webpack_require__(2153);!function(e){e[e.unknown=0]="unknown",e[e.valid=1]="valid",e[e.invalid=2]="invalid",e[e.ignored=3]="ignored"}(cy||(cy={}));class uy{records;queue;constructor(){this.records=new Map,this.queue=new ly}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:cy.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);const r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){const e=Date.now();let t=this.queue.peekFront();for(;null!=t&&t.expirenew Set));scoreCache=new Map;deliveryRecords=new uy;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,function(e){for(const[t,r]of Object.entries(e.topics))try{ry(r)}catch(e){throw new Ga(`invalid score parameters for topic ${t}: ${e.message}`,Qg)}if(e.topicScoreCap<0)throw new Ga("invalid topic score cap; must be positive (or 0 for no cap)",Qg);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new Ga("missing application specific score function",Qg);if(e.IPColocationFactorWeight>0)throw new Ga("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",Qg);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new Ga("invalid IPColocationFactorThreshold; must be at least 1",Qg);if(e.behaviourPenaltyWeight>0)throw new Ga("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",Qg);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new Ga("invalid BehaviourPenaltyDecay; must be between 0 and 1",Qg);if(e.decayInterval<1e3)throw new Ga("invalid DecayInterval; must be at least 1s",Qg);if(e.decayToZero<=0||e.decayToZero>=1)throw new Ga("invalid DecayToZero; must be between 0 and 1",Qg)}(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??ay,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){null==this._backgroundInterval?(this._backgroundInterval=setInterval((()=>{this.background()}),this.params.decayInterval),this.log("started")):this.log("Peer score already running")}stop(){null!=this._backgroundInterval?(clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")):this.log("Peer score already stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map((([e,t])=>[e,t])))}messageFirstSeenTimestampMs(e){const t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){const e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach(((r,n)=>{r.connected?(Object.entries(r.topics).forEach((([r,n])=>{const s=this.params.topics[r];void 0!==s&&(n.firstMessageDeliveries*=s.firstMessageDeliveriesDecay,n.firstMessageDeliveriess.meshMessageDeliveriesActivation&&(n.meshMessageDeliveriesActive=!0)))})),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenaltyr.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n))}))}score(e){this.metrics?.scoreFnCalls.inc();const t=this.peerStats.get(e);if(null==t)return 0;const r=Date.now(),n=this.scoreCache.get(e);if(null!=n&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();const s=this.computeScore(e,t,this.params,this.peerIPs),i=r+this.scoreCacheValidityMs;return null!=n?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-n.score)),n.score=s,n.cacheUntil=i):this.scoreCache.set(e,{score:s,cacheUntil:i}),s}addPenalty(e,t,r){const n=this.peerStats.get(e);null!=n&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){const t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){const r=this.peerStats.get(e);null!=r&&r.knownIPs.delete(t);const n=this.peerIPs.get(t);null!=n&&(n.delete(e),0===n.size&&this.peerIPs.delete(t))}removePeer(e){const t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0)return this.removeIPsForPeer(e,t.knownIPs),void this.peerStats.delete(e);Object.entries(t.topics).forEach((([e,t])=>{t.firstMessageDeliveries=0;const r=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries{t!==e.toString()&&this.markDuplicateMessageDelivery(t,r)}))):this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-n.firstSeenTsMs,cy[n.status])}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Vg.Error:return void this.markInvalidMessageDelivery(e,r);case Vg.Blacklisted:return}const s=this.deliveryRecords.ensureRecord(t);if(s.status===cy.unknown){if(n===Vg.Ignore)return s.status=cy.ignored,void s.peers.clear();s.status=cy.invalid,this.markInvalidMessageDelivery(e,r),s.peers.forEach((e=>{this.markInvalidMessageDelivery(e,r)})),s.peers.clear()}else this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeenTsMs,cy[s.status])}duplicateMessage(e,t,r){const n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case cy.unknown:n.peers.add(e);break;case cy.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case cy.invalid:this.markInvalidMessageDelivery(e,r);case cy.ignored:}}markInvalidMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const e=this.getPtopicStats(r,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){const r=this.peerStats.get(e);if(null!=r){const 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){const n=this.peerStats.get(e);if(null!=n){const e=void 0!==r?Date.now():0,s=this.getPtopicStats(n,t);if(null!=s&&s.inMesh){const n=this.params.topics[t];if(void 0!==r){const s=e-r,i=s>n.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,s,i),i)return}const i=n.meshMessageDeliveriesCap;s.meshMessageDeliveries=Math.min(i,s.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(const r of t){const 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}}function dy(e,t,r,n,s){let i=0;const o=new Map;if(Object.entries(t.topics).forEach((([e,t])=>{const n=s.get(e)??"unknown",a=r.topics[e];if(void 0===a)return;let c=o.get(n);null==c&&(c={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(n,c));let l=0,u=0,h=0,d=0,p=0;t.inMesh&&(l+=Math.max(t.meshTime/a.timeInMeshQuantum,a.timeInMeshCap)*a.timeInMeshWeight);let f=t.firstMessageDeliveries;if(f>a.firstMessageDeliveriesCap&&(f=a.firstMessageDeliveriesCap),u+=f*a.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries0&&i>r.topicScoreCap){i=r.topicScoreCap;const e=r.topicScoreCap/i;for(const t of o.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let a=0,c=0,l=0;return a+=r.appSpecificScore(e)*r.appSpecificWeight,t.knownIPs.forEach((e=>{if(r.IPColocationFactorWhitelist.has(e))return;const t=n.get(e),s=null!=t?t.size:0;if(s>r.IPColocationFactorThreshold){const e=s-r.IPColocationFactorThreshold;c+=e*e*r.IPColocationFactorWeight}})),l+=t.behaviourPenalty*t.behaviourPenalty*r.behaviourPenaltyWeight,i+=a+c+l,{byTopic:o,p5w:a,p6w:c,p7w:l,score:i}}class py{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,r){this.rawStream=e,this.pushable=fs(),this.closeController=new AbortController,this.maxBufferSize=r.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),ys(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(is.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 fy{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=ys(this.rawStream,(e=>ls(e,t)))}async close(){this.closeController.abort()}}class gy{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){const r=t[Math.floor(Math.random()*t.length)],n=this.msgIdToStrFn(r);let s=this.promises.get(n);null==s&&(s=new Map,this.promises.set(n,s));const i=Date.now();s.has(e)||(s.set(e,i+this.gossipsubIWantFollowupMs),null!=this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(n)||this.requestMsByMsg.set(n,i)))}getBrokenPromises(){const e=Date.now(),t=new Map;let r=0;return this.promises.forEach(((n,s)=>{n.forEach(((s,i)=>{sFr(ky)}(Iy||(Iy={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ry||(Ry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Iy.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Iy.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Ty||(Ty={}));class Cy{_key;constructor(e){this._key=Ly(e,by)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Ry.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class Py{_key;_publicKey;constructor(e,t){this._key=Ly(e,wy),this._publicKey=Ly(t,by)}sign(e){return function(e,t){const r=e.subarray(0,vy);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function By(e){if(e.length>wy){const t=(e=Ly(e,wy+by)).subarray(0,wy),r=e.subarray(wy,e.length);return new Py(t,r)}const t=(e=Ly(e,wy)).subarray(0,wy),r=e.subarray(by);return new Py(t,r)}function Dy(e){return e=Ly(e,by),new Cy(e)}async function Ny(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Ey(e,t),publicKey:t}}();return new Py(e,t)}async function xy(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vy)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Ey(t,r),publicKey:r}}(e);return new Py(t,r)}function Ly(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Oy(e){const t=[await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Uy(e)],r=await My({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function My(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sy.get().subtle.exportKey("jwk",e.privateKey),Sy.get().subtle.exportKey("jwk",e.publicKey)])}async function Uy(e){return Sy.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 Ky(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fy(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const qy=8192;class Hy{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sy.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ry.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}}class jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return yy(16)}sign(e){return async function(e,t){const r=await Sy.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sy.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Hy(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(Vy($t(e.n,"base64url"))),Hd.fromBigInt(Vy($t(e.e,"base64url"))),Hd.fromBigInt(Vy($t(e.d,"base64url"))),Hd.fromBigInt(Vy($t(e.p,"base64url"))),Hd.fromBigInt(Vy($t(e.q,"base64url"))),Hd.fromBigInt(Vy($t(e.dp,"base64url"))),Hd.fromBigInt(Vy($t(e.dq,"base64url"))),Hd.fromBigInt(Vy($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Ty.encode({Type:Iy.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sy.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=yy(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=yy(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function $y(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Fy(r[1].toBigInt()),"base64url"),e:An(Fy(r[2].toBigInt()),"base64url"),d:An(Fy(r[3].toBigInt()),"base64url"),p:An(Fy(r[4].toBigInt()),"base64url"),q:An(Fy(r[5].toBigInt()),"base64url"),dp:An(Fy(r[6].toBigInt()),"base64url"),dq:An(Fy(r[7].toBigInt()),"base64url"),qi:An(Fy(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Oy(t);return new jy(r.privateKey,r.publicKey)}function zy(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Fy(r[0].toBigInt()),"base64url"),e:An(Fy(r[1].toBigInt()),"base64url")}}(e);if(Ky(t)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Hy(t)}async function Gy(e){if(Ky(e)>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Oy(e);return new jy(t.privateKey,t.publicKey)}async function Wy(e){if(e>qy)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sy.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 My(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new jy(t.privateKey,t.publicKey)}function Yy(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Xy{_key;constructor(e){Yy(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(my(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Ry.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return my(e)?({bytes:t}=await e):t=e.bytes,t}}class Jy{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Yy(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(my(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Xy(this._publicKey)}marshal(){return this._key}get bytes(){return Ty.encode({Type:Iy.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return my(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Ay(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Qy(e){return new Jy(e)}function Zy(e){return new Xy(e)}async function em(){const e=$c.utils.randomPrivateKey();return new Jy(e)}const tm={rsa:S,ed25519:E,secp256k1:_};function rm(e){const t=Object.keys(tm).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function nm(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return tm[e];throw rm(e)}function sm(e){const t=Ry.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPublicKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PublicKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw rm(t.Type??"unknown")}}const im=$t("libp2p-pubsub:");function om(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 am(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function cm(e){return An(e,"base64")}function lm(e){if(e.length<=1)return e;for(let t=0;t{const r=$t(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})(e.from.toBytes(),e.sequenceNumber)}async function hm(e){return Pt.encode(e.data)}var dm,pm;!function(e){e[e.ip4=4]="ip4",e[e.ip6=41]="ip6"}(dm||(dm={}));class fm{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(){const e=Date.now();for(const[t,r]of this.entries.entries()){if(!(r.validUntilMs=Date.now()?t.value:void 0}clear(){this.entries.clear()}}!function(e){e[e.started=0]="started",e[e.stopped=1]="stopped"}(pm||(pm={}));class gm extends ni{globalSignaturePolicy;multicodecs=[Lg,xg];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=fs({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=Lg;opts;decodeRpcLimits;metrics;status={code:pm.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();const 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:ty(t.scoreParams),scoreThresholds:sy(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Mg,this.globalSignaturePolicy=r.globalSignaturePolicy??Pg,r.fallbackToFloodsub&&this.multicodecs.push(Ng),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 fm({validityMs:r.seenTTL}),this.publishedMessageIds=new fm({validityMs:r.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Pg:this.msgIdFn=um;break;case Bg:this.msgIdFn=hm;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new fm({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??cm,this.mcache=t.messageCache??new Xg(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");const e=Math.max(...Object.values(r.scoreParams.topics).map((e=>e.meshMessageDeliveriesWindow)),1e3),n=function(e,t,r){return{protocolsEnabled:e.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:e.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:e.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:e.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:e.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:e.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:e.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:e.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:e.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:e.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:e.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:e.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:e.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:e.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:e.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:e.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:e.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:e.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:e.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:e.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:e.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:e.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:e.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:e.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:e.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:e.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:e.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:e.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:e.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:e.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:e.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:e.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:e.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:e.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:e.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:e.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:e.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:e.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:e.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:e.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:e.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:e.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:e.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:e.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:e.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:e.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:e.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:e.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:e.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:e.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:e.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:e.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:e.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:e.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*r.maxMeshMessageDeliveriesWindowSec,.5*r.maxMeshMessageDeliveriesWindowSec,Number(r.maxMeshMessageDeliveriesWindowSec),2*r.maxMeshMessageDeliveriesWindowSec,4*r.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:e.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:e.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:e.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:e.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:e.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:e.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:e.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:e.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:e.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:e.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:e.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*r.behaviourPenaltyThreshold,.5*r.behaviourPenaltyThreshold,Number(r.behaviourPenaltyThreshold),2*r.behaviourPenaltyThreshold,4*r.behaviourPenaltyThreshold]}),ihaveRcvIgnored:e.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:e.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:e.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:e.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:e.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:e.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:e.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:e.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:e.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:e.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:e.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:e.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*r.gossipPromiseExpireSec,Number(r.gossipPromiseExpireSec),2*r.gossipPromiseExpireSec,4*r.gossipPromiseExpireSec]}),iwantPromiseUntracked:e.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:e.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:e.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:e.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:e.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:e.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:e.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:t,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){const n=this.toTopic(e);switch(t){case $g.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:n},r);break;case $g.Random:this.meshPeerInclusionEventsRandom.inc({topic:n},r);break;case $g.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:n},r);break;case $g.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:n},r);break;case $g.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:n},r);break;case $g.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:n},r);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:n},r)}},onRemoveFromMesh(e,t,r){const n=this.toTopic(e);switch(t){case zg.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:n},r);break;case zg.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:n},r);break;case zg.Prune:this.meshPeerChurnEventsPrune.inc({topic:n},r);break;case zg.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){const r=this.toTopic(e.message.topic);switch(t){case Dg.Accept:this.acceptedMessagesTotal.inc({topic:r});break;case Dg.Ignore:this.ignoredMessagesTotal.inc({topic:r});break;case Dg.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){const n=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:n},t),this.ihaveRcvNotSeenMsgids.inc({topic:n},r)},onIwantRcv(e,t){for(const[t,r]of e){const e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},r)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){const r=this.toTopic(e);this.msgForwardCount.inc({topic:r},1),this.msgForwardPeers.inc({topic:r},t)},onPublishMsg(e,t,r,n,s){const i=this.toTopic(e);this.msgPublishCount.inc({topic:i},1),this.msgPublishBytes.inc({topic:i},r*n),this.msgPublishPeersByTopic.inc({topic:i},r),this.directPeersPublishedTotal.inc({topic:i},t.direct),this.floodsubPeersPublishedTotal.inc({topic:i},t.floodsub),this.meshPeersPublishedTotal.inc({topic:i},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:i},t.fanout),this.msgPublishTime.observe({topic:i},s/1e3)},onMsgRecvPreValidation(e){const t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){const t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){const r=this.toTopic(e);switch(t){case Hg.duplicate:this.prevalidationDuplicateTotal.inc({topic:r});break;case Hg.invalid:this.prevalidationInvalidTotal.inc({topic:r});break;case Hg.valid:this.prevalidationValidTotal.inc({topic:r});break;default:this.prevalidationUnknownTotal.inc({topic:r})}},onMsgRecvInvalid(e,t){const r=this.toTopic(e),n=t.reason===Vg.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:n},1),this.msgReceivedInvalidByTopic.inc({topic:r},1)},onDuplicateMsgDelivery(e,t,r){const n=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:n},t/1e3),r&&this.duplicateMsgLateDelivery.inc({topic:n},1)},onPublishDuplicateMsg(e){const 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){const t=e.control.ihave?.length??0,r=e.control.iwant?.length??0,n=e.control.graft?.length??0,s=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),r>0&&this.rpcSentIWant.inc(r),n>0&&this.rpcSentGraft.inc(n),s>0&&this.rpcSentPrune.inc(s),(t>0||r>0||n>0||s>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let r=0,n=0,s=0,i=0;for(const o of e)o>=t.graylistThreshold&&r++,o>=t.publishThreshold&&n++,o>=t.gossipThreshold&&s++,o>=0&&i++;this.peersByScoreThreshold.set({threshold:Yg.graylist},r),this.peersByScoreThreshold.set({threshold:Yg.publish},n),this.peersByScoreThreshold.set({threshold:Yg.gossip},s),this.peersByScoreThreshold.set({threshold:Yg.mesh},i),this.score.set(e)},registerScoreWeights(e){for(const[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){const r=new Map;e.forEach(((e,t)=>{const n=this.topicStrToLabel.get(t)??"unknown";let s=r.get(n);null==s&&(s=new Set,r.set(n,s)),e.forEach((e=>s?.add(e)))}));for(const[e,n]of r){const r=[];n.forEach((e=>{r.push(t.get(e)??0)})),this.scorePerMesh.set({topic:e},r)}}}}(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3});n.mcacheSize.addCollect((()=>{this.onScrapeMetrics(n)}));for(const e of this.multicodecs)n.protocolsEnabled.set({protocol:e},1);this.metrics=n}else this.metrics=null;this.gossipTracer=new gy(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new hy(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=>hl(e)))}isStarted(){return this.status.code===pm.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await async function(e,t){switch(e){case Pg:{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");const e=await async function(e){const t=Ty.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Iy.RSA:return tm.rsa.unmarshalRsaPrivateKey(r);case Iy.Ed25519:return tm.ed25519.unmarshalEd25519PrivateKey(r);case Iy.Secp256k1:return tm.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw rm(t.Type??"RSA")}}(t.privateKey);return{type:Fg.Signing,author:t,key:t.publicKey,privateKey:e}}case Bg:return{type:Fg.Anonymous};default:throw new Error(`Unknown signature policy "${e}"`)}}(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=fs({objectMode:!0}),ys(this.outboundInflightQueue,(async e=>{for await(const{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})})));const 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}))));const 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:pm.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!==pm.started)return;const{registrarTopologyIds:e}=this.status;this.status={code:pm.stopped};const t=this.components.registrar;await Promise.all(this.multicodecs.map((async e=>t.unhandle(e)))),e.forEach((e=>{t.unregister(e)})),this.outboundInflightQueue.end();const r=[];for(const e of this.streamsOutbound.values())r.push(e.close());this.streamsOutbound.clear();for(const e of 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;const 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;const r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{const n=new py(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);const s=n.protocol;s===Ng&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:s},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;const r=e.toString();if(!this.peers.has(r))return;const 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);const s=new fy(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,s),this.pipePeerReadStream(e,s.source).catch((e=>{this.log(e)}))}addPeer(e,t,r){const n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.add(n),this.score.addPeer(n);const s=function(e){for(const t of e.tuples())switch(t[0]){case dm.ip4:case dm.ip6:return $l(t[0],t[1])}return null}(r);null!==s?this.score.addIP(n,s):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){const t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);const r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);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);for(const e of this.topics.values())e.delete(t);for(const[e,r]of this.mesh)r.delete(t)&&this.metrics?.onRemoveFromMesh(e,zg.Dc,1);for(const 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===pm.started}getMeshPeers(e){const t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){const t=this.topics.get(e);return(null!=t?Array.from(t):[]).map((e=>hl(e)))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ys(t,(async t=>{for await(const r of t)try{const t=r.subarray(),n=Ug.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()))return this.log("received message from unacceptable peer %p",e),void this.metrics?.rpcRecvNotAccepted.inc();const r=null!=t.subscriptions?t.subscriptions.length:0,n=null!=t.messages?t.messages.length:0;let s=0,i=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(s=t.control.ihave.length),null!=t.control.iwant&&(i=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 ${s} iwant ${i} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){const r=[];t.subscriptions.forEach((t=>{const n=t.topic,s=!0===t.subscribe;if(null!=n){if(null!=this.allowedTopics&&!this.allowedTopics.has(n))return;this.handleReceivedSubscription(e,n,s),r.push({topic:n,subscribe:s})}})),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:r}})}for(const r of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(r.topic))continue;const 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);const r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);const n=r.code;switch(n){case Hg.duplicate:return this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),void this.mcache.observeDuplicate(r.msgIdStr,e.toString());case Hg.invalid:if(null!=r.msgIdStr){const 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);return void this.metrics?.onMsgRecvInvalid(t.topic,r);case Hg.valid: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)&&(this.components.peerId.equals(e)&&!this.opts.emitSelf||(super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new ii("message",{detail:r.msg})))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){const r=this.fastMsgIdFn?.(t),n=void 0!==r?this.fastMsgIdCache?.get(r):void 0;if(null!=n)return{code:Hg.duplicate,msgIdStr:n};const s=await async function(e,t){switch(e){case Bg:return null!=t.signature?{valid:!1,error:qg.SignaturePresent}:null!=t.seqno?{valid:!1,error:qg.SeqnoPresent}:null!=t.key?{valid:!1,error:qg.FromPresent}:{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case Pg:{if(null==t.seqno)return{valid:!1,error:qg.InvalidSeqno};if(8!==t.seqno.length)return{valid:!1,error:qg.InvalidSeqno};if(null==t.signature)return{valid:!1,error:qg.InvalidSignature};if(null==t.from)return{valid:!1,error:qg.InvalidPeerId};let e,s;try{e=dl(t.from)}catch(e){return{valid:!1,error:qg.InvalidPeerId}}if(null!=t.key){if(s=sm(t.key),void 0!==e.publicKey&&!Qn(s.bytes,e.publicKey))return{valid:!1,error:qg.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:qg.InvalidPeerId};s=sm(e.publicKey)}const i={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},o=Jn([im,Ug.Message.encode(i)]);return await s.verify(o,t.signature)?{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${An(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??(r=s,nm(n=(n??"rsa").toLowerCase()),r.bytes)}}:{valid:!1,error:qg.InvalidSignature}}default:throw new Error("Unreachable")}var r,n}(this.globalSignaturePolicy,t);if(!s.valid)return{code:Hg.invalid,reason:Vg.Error,error:s.error};const i=s.message;try{null!=this.dataTransform&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:Hg.invalid,reason:Vg.Error,error:qg.TransformFailed}}const o=await this.msgIdFn(i),a=this.msgIdToStrFn(o),c={msgId:o,msgIdStr:a};if(void 0!==r&&null!=this.fastMsgIdCache&&this.fastMsgIdCache.put(r,a)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(a))return{code:Hg.duplicate,msgIdStr:a};this.seenCache.put(a);const l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,i)}catch(e){const r=e.code;"ERR_TOPIC_VALIDATOR_IGNORE"===r&&(t=Dg.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===r?Dg.Reject:Dg.Ignore}if(t!==Dg.Accept)return{code:Hg.invalid,reason:Jg(t),msgIdStr:a}}return{code:Hg.valid,messageId:c,msg:i}}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;const r=null!=t.ihave?this.handleIHave(e,t.ihave):[],n=null!=t.iwant?this.handleIWant(e,t.iwant):[],s=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===s.length)return;const i=this.sendRpc(e,om(n,{iwant:r,prune:s})),o=r[0]?.messageIDs;null!=o&&(i?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;const t=Date.now(),r=this.acceptFromWhitelist.get(e);if(null!=r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;const 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[];const r=this.score.score(e);if(r10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIhave}),[];const s=this.iasked.get(e)??0;if(s>=Og)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Wg.MaxIasked}),[];const i=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=>{const t=this.msgIdToStrFn(e);this.seenCache.has(t)||(i.set(t,e),r++)})),this.metrics?.onIhaveRcv(e,t.length,r)})),0===i.size)return[];let o=i.size;o+s>Og&&(o=Og-s),this.log("IHAVE: Asking for %d out of %d messages from %s",o,i.size,e);let a=Array.from(i.values());return lm(a),a=a.slice(0,o),this.iasked.set(e,s+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];const r=this.score.score(e);if(r{t?.forEach((t=>{const r=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(r,e);null!=o?(s.set(o.msg.topic,1+(s.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):n.set(r,o.msg)):i++}))})),this.metrics?.onIwantRcv(s,i),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){const r=[],n=this.score.score(e),s=Date.now();let i=this.opts.doPX;return t.forEach((({topicID:t})=>{if(null==t)return;const o=this.mesh.get(t);if(null==o)return void(i=!1);if(o.has(e))return;if(this.direct.has(e))return this.log("GRAFT: ignoring request from direct peer %s",e),r.push(t),void(i=!1);const a=this.backoff.get(t)?.get(e);if("number"==typeof a&&s=this.opts.Dhi&&!this.outbound.get(e)?(r.push(t),void this.addBackoff(e,t)):(this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),void this.metrics?.onAddToMesh(t,$g.Subscribed,1))})),0===r.length?[]:Promise.all(r.map((async t=>this.makePrune(e,t,i,!1))))}async handlePrune(e,t){const r=this.score.score(e);for(const{topicID:n,backoff:s,peers:i}of t){if(null==n)continue;const 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,zg.Prune,1)),"number"==typeof s&&s>0?this.doAddBackoff(e,n,1e3*s):this.addBackoff(e,n),null!=i&&i.length>0){if(r{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Gg.BrokenPromise)}))}clearBackoff(){if(this.heartbeatTicks%15!=0)return;const e=Date.now();this.backoff.forEach(((t,r)=>{t.forEach(((r,n)=>{r+1*this.opts.heartbeatInterval{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&&(lm(e),e=e.slice(0,this.opts.prunePeers));const t=[];await Promise.all(e.map((async e=>{if(null==e.peerID)return;const r=dl(e.peerID),n=r.toString();if(!this.peers.has(n))if(null!=e.signedPeerRecord)try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,r))return void this.log("bogus peer record obtained through px: could not add peer record to address book");t.push(n)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}else t.push(n)}))),0!==t.length&&await Promise.all(t.map((async e=>this.connect(e))))}async connect(e){this.log("Initiating connection with %s",e);const t=hl(e),r=await this.components.connectionManager.openConnection(t);for(const e of this.multicodecs)for(const n of this.components.registrar.getTopologies(e))n.onConnect?.(t,r)}subscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==pm.started)throw new Error("Pubsub is not started");const t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==pm.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);const 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,$g.Fanout,t.size)),t.size!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==r||!r.has(e)))).forEach((e=>{t.add(e)})),this.metrics?.onAddToMesh(e,$g.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!==pm.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);const 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){const n=new Set,s=this.topics.get(e);null!=s&&(this.direct.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&n.add(e)})),this.floodsubPeers.forEach((e=>{s.has(e)&&t!==e&&!r?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&n.add(e)})));const i=this.mesh.get(e);return null!=i&&i.size>0&&i.forEach((e=>{t===e||r?.has(e)||n.add(e)})),n}selectPeersToPublish(e){const 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++)}));const s=this.mesh.get(e);if(null!=s&&s.size>0)s.forEach((e=>{t.add(e),r.mesh++}));else{const n=this.fanout.get(e);if(null!=n&&n.size>0)n.forEach((e=>{t.add(e),r.fanout++}));else{const 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);const s=this.selectPeersToForward(t.topic,r,n);s.forEach((e=>{this.sendRpc(e,om([t]))})),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,r){const n=Date.now(),s=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");const{raw:i,msg:o}=await async function(e,t,r,n){switch(e.type){case Fg.Signing:{const s={from:e.author.toBytes(),data:n,seqno:yy(8),topic:t,signature:void 0,key:void 0},i=Jn([im,Ug.Message.encode(s)]);return s.signature=await e.privateKey.sign(i),s.key=e.key,{raw:s,msg:{type:"signed",from:e.author,data:r,sequenceNumber:BigInt(`0x${An(s.seqno,"base16")}`),topic:t,signature:s.signature,key:s.key}}}case Fg.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 new Error("Unreachable")}}(this.publishConfig,e,t,s),a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),l=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(l)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}const{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(c),this.mcache.put({msgId:a,msgIdStr:c},i,!0),this.publishedMessageIds.put(c);const f=r?.batchPublish??this.opts.batchPublish,g=om([i]);if(f)this.sendRpcInBatch(u,g);else for(const e of u)this.sendRpc(e,g)||u.delete(e);const y=Date.now()-n;return this.metrics?.onPublishMsg(e,h,u.size,null!=i.data?i.data.length:0,y),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new ii("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:o}})),super.dispatchEvent(new ii("message",{detail:o}))),{recipients:Array.from(u.values()).map((e=>hl(e)))}}sendRpcInBatch(e,t){const r=Ug.encode(t),n=is.single(r);for(const s of e){const i=this.streamsOutbound.get(s);if(null!=i){try{i.pushPrefixed(n)}catch(t){e.delete(s),this.log.error(`Cannot send rpc to ${s}`,t)}this.metrics?.onRpcSent(t,r.length)}else this.log(`Cannot send RPC to ${s} as there is no open stream to it available`),e.delete(s)}}reportMessageValidationResult(e,t,r){let n;if(r===Dg.Accept){if(n=this.mcache.validate(e),null!=n){const{message:r,originatingPeers:s}=n;this.score.deliverMessage(t,e,r.topic),this.forwardMessage(e,n.message,t,s)}}else if(n=this.mcache.remove(e),null!=n){const s=Jg(r),{message:i,originatingPeers:o}=n;this.score.rejectMessage(t,e,i.topic,s);for(const t of o)this.score.rejectMessage(t,e,i.topic,s)}const s=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,s)}sendGraft(e,t){const r=om([],{graft:[{topicID:t}]});this.sendRpc(e,r)}async sendPrune(e,t){const r=om([],{prune:[await this.makePrune(e,t,this.opts.doPX,!0)]});this.sendRpc(e,r)}sendRpc(e,t){const 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;const n=this.control.get(e);null!=n&&(this.piggybackControl(e,t,n),this.control.delete(e));const s=this.gossip.get(e);null!=s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));const i=Ug.encode(t);try{r.push(i)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=n&&this.control.set(e,n),null!=s&&this.gossip.set(e,s),!1}return this.metrics?.onRpcSent(t,i.length),!0}piggybackControl(e,t,r){const n=am(t);for(const t of r.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&n.control.graft.push(t);for(const t of r.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||n.control.prune.push(t)}piggybackGossip(e,t,r){am(t).control.ihave=r}async sendGraftPrune(e,t,r){const n=this.opts.doPX,s=!1;for(const[i,o]of e){const e=o.map((e=>({topicID:e})));let a=[];const c=t.get(i);null!=c&&(a=await Promise.all(c.map((async e=>this.makePrune(i,e,n&&!r.get(i),s)))),t.delete(i)),this.sendRpc(i,om([],{graft:e,prune:a}))}for(const[e,i]of t){const t=await Promise.all(i.map((async t=>this.makePrune(e,t,n&&!r.get(e),s))));this.sendRpc(e,om([],{prune:t}))}}emitGossip(e){const t=this.mcache.getGossipIDs(new Set(e.keys()));for(const[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(0===r.length)return;if(lm(r),r.length>Og&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),0===t.size)return;let n=this.opts.Dlazy;const s=.25*t.size;let i=t;s>n&&(n=s),n>i.size?n=i.size:i=lm(Array.from(i)).slice(0,n),i.forEach((t=>{let n=r;r.length>Og&&(n=lm(n.slice()).slice(0,Og)),this.pushGossip(t,{topicID:e,messageIDs:n})}))}flush(){for(const[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,om([],{ihave:t}));for(const[e,t]of this.control.entries()){this.control.delete(e);const r=om([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);const 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===xg)return{topicID:t,peers:[]};const s=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=s/1e3;if(this.doAddBackoff(e,t,s),!r)return{topicID:t,peers:[],backoff:i};const 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=>{const t=hl(e);let r;try{r=await this.components.peerStore.get(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:t.toBytes(),signedPeerRecord:r?.peerRecordEnvelope}})));return{topicID:t,peers:a,backoff:i}}runHeartbeat=()=>{const e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch((e=>{this.log("Error running heartbeat",e)})).finally((()=>{if(null!=e&&e(),this.status.code===pm.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(){const{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:s,fanoutTTL:i}=this.opts;this.heartbeatTicks++;const o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},c=new Map,l=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();const h=new Map;this.mesh.forEach(((i,o)=>{const d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){const e=lm(Array.from(d)),t=this.backoff.get(o);for(const r of e){const e=this.streamsOutbound.get(r);if(null!=e&&this.multicodecs.includes(e.protocol)&&!i.has(r)&&!this.direct.has(r)){const e=a(r);(null==t||!t.has(r))&&e>=0&&p.add(r),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(r)}}}const g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),i.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);const r=l.get(e);null==r?l.set(e,[o]):r.push(o)},y=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),i.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);const r=c.get(e);null==r?c.set(e,[o]):r.push(o)};if(i.forEach((e=>{const t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,zg.BadScore),u.set(e,!0))})),i.size!0))).forEach((e=>{y(e,$g.NotEnough)}))}var m,b;if(i.size>r){let t=Array.from(i);t.sort(((e,t)=>a(t)-a(e))),t=t.slice(0,n).concat(lm(t.slice(n)));let r=0;if(t.slice(0,e).forEach((e=>{this.outbound.get(e)&&r++})),r{const r=t[e];for(let r=e;r>0;r--)t[r]=t[r-1];t[0]=r};if(r>0){let s=r;for(let r=1;r0;r++)this.outbound.get(t[r])&&(n(r),s--)}let s=e-r;for(let r=e;r0;r++)this.outbound.get(t[r])&&(n(r),s--)}t.slice(e).forEach((e=>{g(e,zg.Excess)}))}if(i.size>=t){let e=0;i.forEach((t=>{this.outbound.get(t)&&e++})),e!0===this.outbound.get(e))).forEach((e=>{y(e,$g.Outbound)}))}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&i.size>1){const e=Array.from(i).sort(((e,t)=>a(e)-a(t))),t=Math.floor(i.size/2),r=a(e[t]);if(ra(e)>r));for(const t of e)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",t,o),y(t,$g.Opportunistic)}}}));const d=Date.now();this.fanoutLastpub.forEach(((e,t)=>{e+i{const n=this.topics.get(r);t.forEach((e=>{(!n?.has(e)||a(e)=this.opts.scoreThresholds.publishThreshold&&i.push(r),e>=this.opts.scoreThresholds.gossipThreshold&&o.add(r)}}}if(t.size{t.add(e),o?.delete(e)}))}})),this.emitGossip(h),await this.sendGraftPrune(c,l,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new ii("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=(()=>!0)){const n=this.topics.get(e);if(null==n)return new Set;let s=[];return n.forEach((e=>{const t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&r(e)&&s.push(e)})),s=lm(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}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;const r=Date.now();e.connectedPeersBackoffSec.reset();for(const n of this.backoff.values()){t+=n.size;for(const[t,s]of n.entries())this.peers.has(t)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);for(const[t,r]of this.topics)e.topicPeersCount.set({topicStr:t},r.size);for(const[t,r]of this.mesh)e.meshPeerCounts.set({topicStr:t},r.size);const n=[],s=new Map;e.behaviourPenalty.reset();for(const t of this.peers.keys()){const r=this.score.score(t);n.push(r),s.set(t,r),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(n,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,s);const i=function(e,t,r,n,s){const i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(const o of e){const e=t.get(o);if(null!=e){const t=dy(o,e,r,n,s);for(const[e,r]of t.byTopic){let t=i.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.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)}i.p5w.push(t.p5w),i.p6w.push(t.p6w),i.p7w.push(t.p7w),i.score.push(t.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(i)}}const ym=["/vac/waku/relay/2.0.0"];function mm(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}new qn("relay"),new qn("relay"),ym[0];const bm=32,wm=64,vm=32;function Em(e,t){const r=new Uint8Array(wm);for(let n=0;nFr(km)}(Im||(Im={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Rm||(Rm={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Im.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Im.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Tm||(Tm={}));class Cm{_key;constructor(e){this._key=Lm(e,bm)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Rm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class Pm{_key;_publicKey;constructor(e,t){this._key=Lm(e,wm),this._publicKey=Lm(t,bm)}sign(e){return function(e,t){const r=e.subarray(0,vm);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Cm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Bm(e){if(e.length>wm){const t=(e=Lm(e,wm+bm)).subarray(0,wm),r=e.subarray(wm,e.length);return new Pm(t,r)}const t=(e=Lm(e,wm)).subarray(0,wm),r=e.subarray(bm);return new Pm(t,r)}function Dm(e){return e=Lm(e,bm),new Cm(e)}async function Nm(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:Em(e,t),publicKey:t}}();return new Pm(e,t)}async function xm(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==vm)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:Em(t,r),publicKey:r}}(e);return new Pm(t,r)}function Lm(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Om(e){const t=[await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Um(e)],r=await Mm({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Mm(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Sm.get().subtle.exportKey("jwk",e.privateKey),Sm.get().subtle.exportKey("jwk",e.publicKey)])}async function Um(e){return Sm.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 Km(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Fm(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Vm(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const Hm=8192;class jm{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Sm.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Rm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}}class $m{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Fm(16)}sign(e){return async function(e,t){const r=await Sm.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Sm.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new jm(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(qm($t(e.n,"base64url"))),Hd.fromBigInt(qm($t(e.e,"base64url"))),Hd.fromBigInt(qm($t(e.d,"base64url"))),Hd.fromBigInt(qm($t(e.p,"base64url"))),Hd.fromBigInt(qm($t(e.q,"base64url"))),Hd.fromBigInt(qm($t(e.dp,"base64url"))),Hd.fromBigInt(qm($t(e.dq,"base64url"))),Hd.fromBigInt(qm($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return Tm.encode({Type:Im.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=Sm.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Fm(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Fm(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function zm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Vm(r[1].toBigInt()),"base64url"),e:An(Vm(r[2].toBigInt()),"base64url"),d:An(Vm(r[3].toBigInt()),"base64url"),p:An(Vm(r[4].toBigInt()),"base64url"),q:An(Vm(r[5].toBigInt()),"base64url"),dp:An(Vm(r[6].toBigInt()),"base64url"),dq:An(Vm(r[7].toBigInt()),"base64url"),qi:An(Vm(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Om(t);return new $m(r.privateKey,r.publicKey)}function Gm(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Vm(r[0].toBigInt()),"base64url"),e:An(Vm(r[1].toBigInt()),"base64url")}}(e);if(Km(t)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new jm(t)}async function Wm(e){if(Km(e)>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Om(e);return new $m(t.privateKey,t.publicKey)}async function Ym(e){if(e>Hm)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Sm.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 Mm(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new $m(t.privateKey,t.publicKey)}function Xm(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Jm{_key;constructor(e){Xm(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(mm(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Rm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return mm(e)?({bytes:t}=await e):t=e.bytes,t}}class Qm{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Xm(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(mm(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Jm(this._publicKey)}marshal(){return this._key}get bytes(){return Tm.encode({Type:Im.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return mm(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return Am(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Zm(e){return new Qm(e)}function eb(e){return new Jm(e)}async function tb(){const e=$c.utils.randomPrivateKey();return new Qm(e)}const rb={rsa:I,ed25519:A,secp256k1:k};function nb(e){const t=Object.keys(rb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}const sb=Symbol.for("@libp2p/content-routing"),ib=Symbol.for("@libp2p/peer-routing");function ob(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Fn.enabled(`${e}:trace`)&&null!=Fn.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Fn(`${e}:trace`)),Object.assign(Fn(e),{error:Fn(`${e}:error`),trace:t})}(e)}}function ab(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}Fn.formatters.b=e=>null==e?"undefined":Fe.baseEncode(e),Fn.formatters.t=e=>null==e?"undefined":Ce.baseEncode(e),Fn.formatters.m=e=>null==e?"undefined":qe.baseEncode(e),Fn.formatters.p=e=>null==e?"undefined":e.toString(),Fn.formatters.c=e=>null==e?"undefined":e.toString(),Fn.formatters.k=e=>null==e?"undefined":e.toString(),Fn.formatters.a=e=>null==e?"undefined":e.toString();class cb{set;constructor(e){if(this.set=new Set,null!=e)for(const 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 ab(this.set.entries(),(e=>{const t=hl(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=hl(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return ab(this.set.values(),(e=>hl(e)))}intersection(e){const t=new cb;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new cb;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new cb;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}function lb(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const ub=32,hb=64,db=32;function pb(e,t){const r=new Uint8Array(hb);for(let n=0;nFr(bb)}(mb||(mb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(wb||(wb={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),mb.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=mb.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(vb||(vb={}));class Eb{_key;constructor(e){this._key=Rb(e,ub)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return wb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Sb{_key;_publicKey;constructor(e,t){this._key=Rb(e,hb),this._publicKey=Rb(t,ub)}sign(e){return function(e,t){const r=e.subarray(0,db);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Eb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function _b(e){if(e.length>hb){const t=(e=Rb(e,hb+ub)).subarray(0,hb),r=e.subarray(hb,e.length);return new Sb(t,r)}const t=(e=Rb(e,hb)).subarray(0,hb),r=e.subarray(ub);return new Sb(t,r)}function Ab(e){return e=Rb(e,ub),new Eb(e)}async function Ib(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:pb(e,t),publicKey:t}}();return new Sb(e,t)}async function kb(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==db)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:pb(t,r),publicKey:r}}(e);return new Sb(t,r)}function Rb(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Tb(e){const t=[await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Pb(e)],r=await Cb({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Cb(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([fb.get().subtle.exportKey("jwk",e.privateKey),fb.get().subtle.exportKey("jwk",e.publicKey)])}async function Pb(e){return fb.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 Bb(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function Db(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function Nb(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const Lb=8192;class Ob{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return fb.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return wb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}}class Mb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Db(16)}sign(e){return async function(e,t){const r=await fb.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await fb.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ob(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(xb($t(e.n,"base64url"))),Hd.fromBigInt(xb($t(e.e,"base64url"))),Hd.fromBigInt(xb($t(e.d,"base64url"))),Hd.fromBigInt(xb($t(e.p,"base64url"))),Hd.fromBigInt(xb($t(e.q,"base64url"))),Hd.fromBigInt(xb($t(e.dp,"base64url"))),Hd.fromBigInt(xb($t(e.dq,"base64url"))),Hd.fromBigInt(xb($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return vb.encode({Type:mb.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=fb.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=Db(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=Db(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function Ub(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(Nb(r[1].toBigInt()),"base64url"),e:An(Nb(r[2].toBigInt()),"base64url"),d:An(Nb(r[3].toBigInt()),"base64url"),p:An(Nb(r[4].toBigInt()),"base64url"),q:An(Nb(r[5].toBigInt()),"base64url"),dp:An(Nb(r[6].toBigInt()),"base64url"),dq:An(Nb(r[7].toBigInt()),"base64url"),qi:An(Nb(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Tb(t);return new Mb(r.privateKey,r.publicKey)}function Kb(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(Nb(r[0].toBigInt()),"base64url"),e:An(Nb(r[1].toBigInt()),"base64url")}}(e);if(Bb(t)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ob(t)}async function Fb(e){if(Bb(e)>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Tb(e);return new Mb(t.privateKey,t.publicKey)}async function Vb(e){if(e>Lb)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await fb.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 Cb(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new Mb(t.privateKey,t.publicKey)}function qb(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class Hb{_key;constructor(e){qb(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(lb(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return wb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return lb(e)?({bytes:t}=await e):t=e.bytes,t}}class jb{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),qb(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(lb(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Hb(this._publicKey)}marshal(){return this._key}get bytes(){return vb.encode({Type:mb.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return lb(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return yb(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function $b(e){return new jb(e)}function zb(e){return new Hb(e)}async function Gb(){const e=$c.utils.randomPrivateKey();return new jb(e)}const Wb={rsa:T,ed25519:R,secp256k1:C};function Yb(e){const t=Object.keys(Wb).join(" / ");return new Ga(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Xb(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return Wb[e];throw Yb(e)}function Jb(e,t){return Xb(t=(t??"rsa").toLowerCase()),e.bytes}const Qb=async()=>{const e=await async function(e,t){return Xb("Ed25519").generateKeyPair(2048)}(),t=await Zb(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)};async function Zb(e){return pl(Jb(e.public),(t=e,Xb(r=(r??"rsa").toLowerCase()),t.bytes));var t,r}async function ew(e){return async function(e,t,r){if(null!=t)return Zb(await async function(e){const t=vb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPrivateKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PrivateKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Yb(t.Type??"RSA")}}(t));if(null!=r)return async function(e){return pl(Jb(e))}(function(e){const t=wb.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case mb.RSA:return Wb.rsa.unmarshalRsaPublicKey(r);case mb.Ed25519:return Wb.ed25519.unmarshalEd25519PublicKey(r);case mb.Secp256k1:return Wb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Yb(t.Type??"unknown")}}(r));return dl(e)}($t(e.id,"base58btc"),null!=e.privKey?$t(e.privKey,"base64pad"):void 0,null!=e.pubKey?$t(e.pubKey,"base64pad"):void 0)}class tw{map;constructor(e){if(this.map=new Map,null!=e)for(const[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 ab(this.map.entries(),(e=>[hl(e[0]),e[1]]))}forEach(e){this.map.forEach(((t,r)=>{e(t,hl(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 ab(this.map.keys(),(e=>hl(e)))}values(){return this.map.values()}get size(){return this.map.size}}var rw=__webpack_require__(228);class nw{#o=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority)return void this.#o.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const r=Math.trunc(s/2);let o=n+r;i=e[o],t.priority-i.priority<=0?(n=++o,s-=r+1):s=r}var i;return n}(this.#o,r);this.#o.splice(n,0,r)}dequeue(){const 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 sw extends rw{#a;#c;#l=0;#u;#h;#d=0;#p;#f;#o;#g;#y=0;#m;#b;#w;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:nw,...e}).intervalCap&&e.intervalCap>=1))throw new 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 new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#a=e.carryoverConcurrencyCount,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#u=e.intervalCap,this.#h=e.interval,this.#o=new e.queueClass,this.#g=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#w=!0===e.throwOnTimeout,this.#b=!1===e.autoStart}get#v(){return this.#c||this.#l{this.#A()}),t)),!0;this.#l=this.#a?this.#y:0}return!1}#_(){if(0===this.#o.size)return this.#p&&clearInterval(this.#p),this.#p=void 0,this.emit("empty"),0===this.#y&&this.emit("idle"),!1;if(!this.#b){const e=!this.#R;if(this.#v&&this.#E){const t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#c||void 0!==this.#p||(this.#p=setInterval((()=>{this.#I()}),this.#h),this.#d=Date.now()+this.#h)}#I(){0===this.#l&&0===this.#y&&this.#p&&(clearInterval(this.#p),this.#p=void 0),this.#l=this.#a?this.#y:0,this.#T()}#T(){for(;this.#_(););}get concurrency(){return this.#m}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#m=e,this.#T()}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.#y++,this.#l++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Xs(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#C(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof zs&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#S()}}),t),this.emit("add"),this.#_()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#b?(this.#b=!1,this.#T(),this):this}pause(){this.#b=!0}clear(){this.#o=new this.#g}async onEmpty(){0!==this.#o.size&&await this.#P("empty")}async onSizeLessThan(e){this.#o.sizethis.#o.size{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#y}get isPaused(){return this.#b}}const iw={},ow=e=>{e.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{ow.dispatchEvent("message",e,t)}))};ow.addEventListener=(e,t)=>{null==iw[e]&&(iw[e]=[]),iw[e].push(t)},ow.removeEventListener=(e,t)=>{null!=iw[e]&&(iw[e]=iw[e].filter((e=>e===t)))},ow.dispatchEvent=function(e,t,r){null!=iw[e]&&iw[e].forEach((e=>e(t,r)))};const aw=ow,cw="lock:worker:request-read",lw="lock:worker:release-read",uw="lock:master:grant-read",hw="lock:worker:request-write",dw="lock:worker:release-write",pw="lock:master:grant-write",fw=(e,t,r,n,s)=>(i,o)=>{if(o.data.type!==r)return;const a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r||null==r.data)return;const s=r.data.type,o=(r.data.name,r.data.identifier);s===n&&o===a.identifier&&(i.removeEventListener("message",t),e())};i.addEventListener("message",t)}))}}}))},gw=(e,t,r,n)=>async()=>{const s=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:s,name:e}),new Promise((t=>{const i=o=>{if(null==o||null==o.data)return;const a=o.data.type,c=o.data.identifier;a===r&&c===s&&(globalThis.removeEventListener("message",i),t((()=>{globalThis.postMessage({type:n,identifier:s,name:e})})))};globalThis.addEventListener("message",i)}))},yw={singleProcess:!1},mw={};let bw;async function ww(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Xs((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const vw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const Ew={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var Sw,_w,Aw;function Iw(e,t){const r=Sw.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new cl(e);if("Ed25519"===e.type)return new ll(e);if("secp256k1"===e.type)return new ul(e);throw new Ga("Not a PeerId","ERR_INVALID_PARAMETERS")}({...e,publicKey:e.publicKey}));const n=new Map,s=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry({multiaddr:hu(e),isCertified:t??!1}))),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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),Aw.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=Aw.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Vr(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),_w.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.addresses.push(_w.codec().decode(t,t.uint32()));break;case 2:n.protocols.push(t.string());break;case 4:n.publicKey=t.bytes();break;case 5:n.peerRecordEnvelope=t.bytes();break;case 6:{const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());n.metadata.set(r.key,r.value);break}case 7:{const r=e.Peer$tagsEntry.codec().decode(t,t.uint32());n.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return n}))),n),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Sw||(Sw={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(_w||(_w={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((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)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(Aw||(Aw={}));const kw="/",Rw=(new TextEncoder).encode(kw),Tw=Rw[0];class Cw{_buf;constructor(e,t){if("string"==typeof e)this._buf=$t(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Tw)throw new Error("Invalid key")}toString(e="utf8"){return An(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Cw(e.join(kw))}static random(){return new Cw(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Cw(e):"function"==typeof e.uint8Array?new Cw(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Rw),this._buf[0]!==Tw){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Tw,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Tw;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;es)return!1}return t.lengthe.namespaces())),[].concat(...t))]);var t}}const Pw="/peers/";function Bw(e){if(!tl(e)||null==e.type)throw new Ga("Invalid PeerId",Ew.ERR_INVALID_PARAMETERS);const t=e.toCID().toString();return new Cw(`${Pw}${t}`)}async function Dw(e,t,r){const n=new Map;for(const s of r){if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=hu(s.multiaddr)),!uu(s.multiaddr))throw new Ga("Multiaddr was invalid",Ew.ERR_INVALID_PARAMETERS);if(!await t(e,s.multiaddr))continue;const r=s.isCertified??!1,i=s.multiaddr.toString(),o=n.get(i);null!=o?s.isCertified=o.isCertified||r:n.set(i,{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 Nw(e,t,r,n){if(null==t)throw new Ga("Invalid PeerData",Ew.ERR_INVALID_PARAMETERS);if(null!=t.publicKey&&null!=e.publicKey&&!Qn(t.publicKey,e.publicKey))throw new Ga("publicKey bytes do not match peer id publicKey bytes",Ew.ERR_INVALID_PARAMETERS);const s=n.existingPeer;if(null!=s&&!e.equals(s.id))throw new Ga("peer id did not match existing peer id",Ew.ERR_INVALID_PARAMETERS);let i=s?.addresses??[],o=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(i=[],null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(a=xw(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lw})),null!=t.tags&&(c=xw(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Ow,map:Mw})),null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&i.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&i.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?a.delete(t):a.set(t,r);a=xw([...a.entries()],{validate:Lw})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(c);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);c=xw([...r.entries()],{validate:Ow,map:Mw})}null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)}const u={addresses:await Dw(e,n.addressFilter??(async()=>!0),i),protocols:[...o.values()].sort(((e,t)=>e.localeCompare(t))),metadata:a,tags:c,publicKey:s?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:l};return"RSA"!==e.type&&delete u.publicKey,u}function xw(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Lw(e,t){if("string"!=typeof e)throw new Ga("Metadata key must be a string",Ew.ERR_INVALID_PARAMETERS);if(!(t instanceof Uint8Array))throw new Ga("Metadata value must be a Uint8Array",Ew.ERR_INVALID_PARAMETERS)}function Ow(e,t){if("string"!=typeof e)throw new Ga("Tag name must be a string",Ew.ERR_INVALID_PARAMETERS);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ga("Tag value must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.value<0||t.value>100)throw new Ga("Tag value must be between 0-100",Ew.ERR_INVALID_PARAMETERS)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ga("Tag ttl must be an integer",Ew.ERR_INVALID_PARAMETERS);if(t.ttl<0)throw new Ga("Tag ttl must be between greater than 0",Ew.ERR_INVALID_PARAMETERS)}}function Mw(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 Uw(e,t,r){const n=e.toString().split("/")[2],s=dl(Ce.decode(n)),i=r.get(s);if(null!=i)return i;const o=Iw(s,t);return r.set(s,o),o}class Kw{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},vw,e);return null==bw&&(bw=(e=>{if(e=Object.assign({},yw,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return aw.addEventListener("message",fw(e,"requestReadLock",cw,lw,uw)),aw.addEventListener("message",fw(e,"requestWriteLock",hw,dw,pw)),e}return{isWorker:!0,readLock:e=>gw(e,cw,uw,lw),writeLock:e=>gw(e,hw,pw,dw)}})(t),!0!==bw.isWorker&&(bw.addEventListener("requestReadLock",(e=>{null!=mw[e.data.name]&&mw[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),bw.addEventListener("requestWriteLock",(async e=>{null!=mw[e.data.name]&&mw[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==mw[t.name]&&(mw[t.name]=((e,t)=>{if(!0===bw.isWorker)return{readLock:bw.readLock(e,t),writeLock:bw.writeLock(e,t)};const r=new sw({concurrency:1});let n;return{async readLock(){if(null!=n)return ww(n,t);n=new sw({concurrency:t.concurrency,autoStart:!1});const e=n,s=ww(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),s},writeLock:async()=>(n=null,ww(r,t))}})(t.name,t)),mw[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Bw(e))}async delete(e){if(this.peerId.equals(e))throw new Ga("Cannot delete self peer",Ew.ERR_INVALID_PARAMETERS);await this.datastore.delete(Bw(e))}async load(e){return Iw(e,await this.datastore.get(Bw(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter});return this.#D(e,s,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#B(e),s=await Nw(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#D(e,s,r,n)}async*all(e){const t=new tw;for await(const{key:r,value:n}of this.datastore.query(function(e,t){return null==e?{}:{prefix:Pw,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(Uw(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(Uw(r.key,r.value,t),Uw(n.key,n.value,t))))}}(e??{},t))){const e=Uw(r,n,t);e.id.equals(this.peerId)||(yield e)}}async#B(e){try{const t=await this.datastore.get(Bw(e));return{existingBuf:t,existingPeer:Iw(e,t)}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async#D(e,t,r,n){const s=Sw.encode(t);return null!=r&&Qn(s,r)?{peer:Iw(e,s),previous:n,updated:!1}:(await this.datastore.put(Bw(e),s),{peer:Iw(e,s),previous:n,updated:!0})}}class Fw{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 Kw(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const 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");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Xn(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");const 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");const 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");const 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");const r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const 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");const r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const 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");const r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const 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){const r=await Hp.openAndCertify(e,Gu.DOMAIN);if(!1===t?.equals(r.peerId))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,r.peerId),!1;const n=Gu.createFromProtobuf(r.payload);let s;try{s=await this.get(r.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=s?.peerRecordEnvelope){const e=await Hp.createFromProtobuf(s.peerRecordEnvelope),t=Gu.createFromProtobuf(e.payload);if(t.seqNumber>=n.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,n.seqNumber),!1}return await this.patch(n.peerId,{peerRecordEnvelope:e,addresses:n.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}))}}const Vw=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},qw=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[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}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},Hw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Xn(e);yield*r.sort(t)}():function*(){const r=Xn(e);yield*r.sort(t)}()},jw=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class $w{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const 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 Vw(this.putMany(e,r)),e=[],await Vw(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=qw(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=qw(r,(()=>t++>=n))}return null!=e.limit&&(r=jw(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=qw(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>qw(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Hw(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=qw(r,(()=>n++>=t))}return null!=e.limit&&(r=jw(r,e.limit)),r}}class zw extends $w{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw r=r??new Error("Not Found"),as(r,"ERR_NOT_FOUND");var r;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new Cw(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Cw(e)}}const Gw=e=>e;function Ww(e,t){const r=e.getPeerId();return null!=r&&hl(r).equals(t)&&(e=e.decapsulate(hu(`/p2p/${t.toString()}`))),e}class Yw{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){const{listen:r=[],announce:n=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.observed=new Map,this.announceFilter=t.announceFilter??Gw,this._updatePeerStoreAddresses=function(e,t){let r;return function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>hu(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=>hu(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>hu(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>hu(e)))}addObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){const t=(e=Ww(e,this.components.peerId)).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)));const t=new Set(e);return this.announceFilter(Array.from(t).map((e=>hu(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}class Xw{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=ob())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>function(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}(e))).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")}}const Jw=["metrics","connectionProtector","dns"],Qw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];var Zw=__webpack_require__(5507);const ev=["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 Zw.Netmask(e)));function tv(e){return xl(e)?function(e){for(const t of ev)if(t.contains(e))return!0;return!1}(e):Ll(e)?/^::$/.test(t=e)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^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(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t):void 0;var t}function rv(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(tv(`${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}}function nv(e){try{const{address:t}=e.nodeAddress();return Boolean(tv(t))}catch{return!0}}function sv(e,t){const r=function(e,t){const r=nv(e.multiaddr),n=nv(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;const n=function(e,t){const r=Sf.exactMatch(e.multiaddr),n=Sf.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==n)return n;const s=function(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}(e,t);return s}class iv extends Event{constructor(e,t){super(e),this.detail=t}}function ov(e){const t=[uv.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}const av=60;function cv(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:uv[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:uv[e.type],TTL:e.TTL??e.ttl??av,data:e.data instanceof Uint8Array?An(e.data):e.data})))}}function lv(e,t={}){const r=new sw({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ov(n.types).forEach((e=>{s.append("type",uv[e])})),n.onProgress?.(new iv("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=cv(await t.json());return n.onProgress?.(new iv("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw new Error("No DNS response received");return i}}var uv,hv=__webpack_require__(194);class dv{lru;constructor(e){this.lru=hv(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return cv({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:uv[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??av),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class pv{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new dv(t)),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["."]=[lv("https://cloudflare-dns.com/dns-query"),lv("https://dns.google/resolve")])}async query(e,t={}){const r=ov(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new iv("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new iv("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(uv||(uv={}));const{code:fv}=jl("dnsaddr"),gv=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Ga("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");const[,n]=e.stringTuples().find((([e])=>e===fv))??[],s=t?.dns??function(e={}){return new pv(e)}(),i=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[uv.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=hu(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},yv=__webpack_require__(6864);var mv,bv,wv;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"}(mv||(mv={})),(wv=bv||(bv={})).ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",wv.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",wv.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",wv.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",wv.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",wv.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",wv.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",wv.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",wv.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",wv.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",wv.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",wv.ERR_DIALED_SELF="ERR_DIALED_SELF",wv.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",wv.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",wv.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",wv.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",wv.ERR_INVALID_KEY="ERR_INVALID_KEY",wv.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",wv.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",wv.ERR_INVALID_PEER="ERR_INVALID_PEER",wv.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",wv.ERR_NOT_FOUND="ERR_NOT_FOUND",wv.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",wv.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",wv.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",wv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",wv.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",wv.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",wv.ERR_FIND_SELF="ERR_FIND_SELF",wv.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",wv.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",wv.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",wv.ERR_INVALID_CMS="ERR_INVALID_CMS",wv.ERR_MISSING_KEYS="ERR_MISSING_KEYS",wv.ERR_NO_KEY="ERR_NO_KEY",wv.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",wv.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",wv.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",wv.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",wv.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",wv.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",wv.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",wv.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",wv.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",wv.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",wv.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",wv.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",wv.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",wv.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",wv.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",wv.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",wv.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",wv.ERR_INVALID_RECORD="ERR_INVALID_RECORD",wv.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",wv.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",wv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",wv.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",wv.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",wv.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED";const vv={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:gv},addressSorter:sv},transportManager:{faultTolerance:dg.FATAL_ALL}};function Ev(e){if(tl(e))return{peerId:e,multiaddrs:[]};let t;if(Array.isArray(e)||(e=[e]),e.length>0){const r=e[0].getPeerId();t=null==r?void 0:hl(r),e.forEach((e=>{if(!uu(e))throw new Ga("Invalid Multiaddr",bv.ERR_INVALID_MULTIADDR);const r=e.getPeerId();if(null==r){if(null!=t)throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}else{const e=hl(r);if(null==t||!t.equals(e))throw new Ga("Multiaddrs must all have the same peer id or have no peer id",bv.ERR_INVALID_PARAMETERS)}}))}return{peerId:t,multiaddrs:e}}class Sv 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 _v(e,t,r,n){const s=new Sv(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(s):new Promise(((i,o)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void o(e)}a(),i(e)},l=e=>{a(),o(e.detail)},u=()=>{a(),o(s)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Av{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=us(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new za)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Iv{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new za),this.cleanup())}async join(e={}){const t=new Av(new 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();const e=await gi(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 kv extends ni{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(0===this.size)return queueMicrotask((()=>{this.safeDispatchEvent("empty")})),0===this.running&&queueMicrotask((()=>{this.safeDispatchEvent("idle")})),!1;if(this.pending{for(let t=0;t(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{e.abort(new za)})),this.clear()}async onEmpty(e){0!==this.size&&await _v(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.sizethis.size{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail)},i=()=>{r()},o=()=>{r(new Ga("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class Rv extends kv{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}const Tv=42e4,Cv="last-dial-failure",Pv=5,Bv=100,Dv=25,Nv=0,xv=5e3,Lv=Tv,Ov=10;class Mv{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??Pv,this.autoDialPriority=t.autoDialPriority??Nv,this.autoDialIntervalMs=t.autoDialInterval??xv,this.autoDialMaxQueueLength=t.maxQueueLength??Bv,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Lv,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ov,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Rv({concurrency:t.autoDialConcurrency??Dv,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;const e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections)return void(this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections));if(this.queue.size>this.autoDialMaxQueueLength)return this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),void this.sheduleNextAutodial();this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);const r=new cb(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)]}),s=n.sort((()=>Math.random()>.5?1:-1)),i=new tw;for(const e of s)i.has(e.id)||i.set(e.id,[...e.tags.values()].reduce(((e,t)=>e+t.value),0));const o=s.sort(((e,t)=>{const r=i.get(e.id)??0,n=i.get(t.id)??0;return r>n?-1:r{const t=e.metadata.get(Cv);if(null==t)return!0;const r=parseInt(An(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs}));this.log("selected %d/%d peers to dial",o.length,n.length);for(const e of o)this.queue.add((async()=>{const t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections)return this.log("got enough connections now %d/%d",t,this.minConnections),void this.queue.clear();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))}}const Uv=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],Kv={maxConnections:100,allow:[]};class Fv{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kv.maxConnections,this.allow=t.allow??Kv.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(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new tw;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),s=Math.max(t-this.maxConnections,0),i=[];for(const e of n)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString())))||i.push(e),i.length===s)break;await Promise.all(i.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??Uv;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return rn?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:ne.options.priority>t.options.priority?-1:e.options.priority{this.log.error("error in dial queue",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Ev(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if(null!=s)return this.log("already connected to %a",s.remoteAddr),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ga("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=>{const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let s=0;const i=[];for(const o of n){if(s===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",s,r),new Ga("Peer had more than maxPeerAddrsToDial",bv.ERR_TOO_MANY_ADDRESSES);s++;try{const r=await this.components.transportManager.dial(o.multiaddr,{...e,signal:t});return this.log("dial to %a succeeded",o.multiaddr),r}catch(e){if(this.log.error("dial failed to %a",o.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[Cv]:$t(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Ga(e.message,Ya);i.push(e)}}if(1===i.length)throw i[0];throw new Wa(i,"All multiaddr dials failed",bv.ERR_TRANSPORT_DIAL_FAILED)}finally{t.clear()}}),{peerId:r,priority:t.priority??$v,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal})}createDialAbortController(e){return qv([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:hu(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Ga("Tried to dial self",bv.ERR_DIALED_SELF);if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Ga("The dial request is blocked by gater.allowDialPeer",bv.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{const 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!==bv.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const 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!==bv.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of lu.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(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){const t=`/p2p/${e.toString()}`;s=s.map((e=>{const r=e.multiaddr.protos().pop();return!0===r?.path?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Ga("The dial request has no valid addresses",bv.ERR_NO_VALID_ADDRESSES);const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=c.sort(this.addressSorter);if(0===l.length)throw new Ga("The connection gater denied all addresses in the dial request",bv.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnTransientConnection||null!=r.find((e=>!Sf.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const $v=50,zv=5,Gv=100,Wv=5,Yv=10,Xv=25,Jv=0,Qv=100,Zv=Tv,eE=10;class tE{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Gv;const r=t.minConnections??zv;if(this.maxConnectionshu(e))),this.deny=(t.deny??[]).map((e=>hu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Yv,this.inboundConnectionRateLimiter=new qf({points:t.inboundConnectionThreshold??Wv,duration:1}),this.autoDial=new Mv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??Xv,autoDialPriority:t.autoDialPriority??Jv,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Zv,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eE,maxQueueLength:t.autoDialMaxQueueLength??Qv}),this.connectionPruner=new Fv({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new jv(e,{addressSorter:t.addressSorter??sv,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:gv},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,outbound:0};for(const t of this.connections.values())for(const r of t)"inbound"===r.direction?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const 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:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const 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()=>{const 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();const e=[];for(const t of this.connections.values())for(const 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){const{detail:t}=e;if(!this.started)return void await t.close();const r=t.remotePeer,n=this.connections.get(r);let s=!1;null!=n?n.push(t):(s=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e;if(!this.started)return;const r=t.remotePeer;let 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(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new Ga("Not started",bv.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();const{peerId:r}=Ev(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>!e.transient));if(null!=e)return this.log("had an existing non-transient connection to %p",r),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??$v});let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)e.id===n.id&&(i=!0);return i||s.push(n),n}async closeConnections(e,t={}){const 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){if(this.deny.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const 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({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>hu(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class rE{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 Ga("No content routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=new cb;for await(const s of gs(...r.routers.map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Ga("No content routers available",bv.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 Ga(mv.NOT_STARTED_YET,bv.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 Ga(mv.NOT_STARTED_YET,bv.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class nE{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=N(n);for(let e=0;ee.equals(t)))}add(e){if(!(e instanceof nE))throw new TypeError("Invalid Fingerprint");for(let t=0;te.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const oE={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aE={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cE=new globalThis.TextEncoder;__webpack_require__(8437);const lE={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!oE[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=oE[t];let s=aE[t],i=e;for(;i.length>0;){const e=cE.encodeInto(i,r);i=i.slice(e.read);for(let i=0;ifunction(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),$t(t,"base16")}(lE.hash(e,t))};class uE{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??lE,this.seed=e.seed??sE(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new iE(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new iE(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[sE(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new iE(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=$t(e));const t=new nE(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=95}}const hE={1:.5,2:.84,4:.95,8:.98};function dE(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=hE[r],s=Math.round(e/n);return{filterSize:s,bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log(s/r))+2,64)}}class pE{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??lE,this.seed=e.seed??sE(0,Math.pow(2,10)),this.filterSeries=[new uE({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=$t(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new uE({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=$t(e));for(let t=0;te+t.count),0)}}const fE=globalThis.CustomEvent??Event;class gE{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 Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new Ga("Should not try to find self",bv.ERR_FIND_SELF);const r=this,n=gs(...this.routers.map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new Ga(mv.NOT_FOUND,bv.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Ga("No peer routers available",bv.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=function(e,t=.001,r){return new pE({...dE(1024,t),...r??{}})}();for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,s=new EventTarget,i=[];let o,a=us(),c=us(),l=!1,u=!1;function h(){return n?i[0]?.done:Boolean(i.find((e=>e.done)))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=us(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new fE("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new fE("task-complete"))}))}l=!0,s.dispatchEvent(new fE("task-complete"))}catch(e){o=e,s.dispatchEvent(new fE("task-complete"))}}));;){if(h()||(c=us(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),l&&0===i.length)break}}(async function*(){const n=gs(...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){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id.toBytes())||(n.add(s.id.toBytes()),yield s))}}class yE extends ni{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=qv([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=us();const e=await _v(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=qv([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=Fm(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await gi(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("randomwalk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class mE{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){const t=this.handlers.get(e);if(null==t)throw new Ga(`No handler registered for protocol ${e}`,bv.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new Ga(`Handler already registered for protocol ${e}`,bv.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const n=yv.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){(Array.isArray(e)?e:[e]).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 Ga("invalid topology",bv.ERR_INVALID_PARAMETERS);const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.peerStore.get(t).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{e.code!==bv.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())r.transient&&!0!==e.notifyOnTransient||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class bE extends Map{metric;constructor(e){super();const{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){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class wE{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){const{name:t,metrics:r}=e;let n;return n=null!=r?new bE({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??dg.FATAL_ALL}add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ga("Transport must have a valid tag",bv.ERR_INVALID_KEY);if(this.transports.has(t))throw new Ga(`There is already a transport with the tag ${t}`,bv.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(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new Ga(`No transport available for address ${String(e)}`,bv.ERR_TRANSPORT_UNAVAILABLE);try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=bv.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Ga("Not started",bv.ERR_NODE_NOT_STARTED);if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t=[];for(const[r,n]of this.transports.entries()){const s=n.listenFilter(e),i=[];for(const e of s){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let s=this.listeners.get(r)??[];null==s&&(s=[],this.listeners.set(r,s)),s.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=s.findIndex((e=>e===t));s.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),i.push(t.listen(e))}if(0!==i.length){if(null==(await Promise.allSettled(i)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==dg.NO_FATAL)throw new Ga(`Transport (${r}) could not listen on any available address`,bv.ERR_NO_VALID_ADDRESSES)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===dg.FATAL_ALL)throw new Ga(e,bv.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const vE="/multistream/1.0.0",EE=1024,SE=$t("\n");async function _E(e,t,r){await e.write(t,r)}async function AE(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==SE[0])throw t.log.error("Invalid mss message - missing newline",r),new Ga("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}(e,t);return An(r.subarray())}async function IE(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=vi(e,{...r,maxDataLength:EE,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await AE(n,r);if(r.log.trace('handle: read "%s"',e),e!==vE){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await _E(n,$t(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log('handle: respond with "na" for "%s"',e),await _E(n,$t("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new rs(...t.map((e=>is.single($t(`${e}\n`)))),$t("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await _E(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',vE,e),await _E(n,$t(`${vE}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',vE,e)}}async function kE(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=us();let c=!1,l=!1;const u=us();let h=!1,d=!1;const p=us(),f=vi({sink:n,source:s},{...r,maxDataLength:EE});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',vE,t),await f.writeV([$t(`${vE}\n`),$t(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',vE,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await AE(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===vE&&(e=await AE(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength);const e=`${t}\n`;yield new rs(Uint8Array.from([19]),$t(`${vE}\n`),G(e.length),$t(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',vE,t,s.byteLength),c=!0,l=!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){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await gi(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=vi(e,{...r,maxDataLength:EE}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',vE,s);const i=$t(`${vE}\n`),o=$t(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await AE(n,r);if(r.log.trace('select: read "%s"',a),a===vE&&(r.log.trace("select: reading protocol response"),a=await AE(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await _E(n,$t(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await AE(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Ga("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const RE=Symbol.for("@libp2p/connection");class TE{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,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=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[RE]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ga("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new Ga("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&!0!==t?.runOnTransientConnection)throw new Ga("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const 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){const t=AbortSignal.timeout(500);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 CE(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class PE{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){const n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new Ga(`The multiaddr connection is blocked by gater.${r}`,bv.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Ga("connection denied",bv.ERR_CONNECTION_DENIED);let r,n,s,i,o;const a=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new Ga("inbound upgrade timeout",Ya))};a.addEventListener("abort",c,{once:!0});try{if(!0===await(this.components.connectionGater.denyInboundConnection?.(e)))throw new Ga("The multiaddr connection is blocked by gater.acceptConnection",bv.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,!0!==t?.skipEncryption){({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(a));const e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{const t=e.remoteAddr.getPeerId();if(null==t)throw new Ga("inbound connection that skipped encryption must have a peer id",bv.ERR_INVALID_MULTIADDR);const r=hl(t);o="native",n=r}if(s=r,null!=t?.muxerFactory)i=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexInbound({...a,...r},this.muxers);i=e.muxerFactory,s=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:s,muxerFactory:i,remotePeer:n,transient:t?.transient})}finally{a.removeEventListener("abort",c),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){const r=e.remoteAddr.getPeerId();let n,s,i,o,a,c;null!=r&&(n=hl(r),await this.shouldBlockConnection(n,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(l=await t.protect(e))}try{if(s=l,!0!==t?.skipEncryption){({conn:s,remotePeer:i,protocol:a}=await this._encryptOutbound(l,n));const e={...l,...s};await this.shouldBlockConnection(i,e,"denyOutboundEncryptedConnection")}else{if(null==n)throw new Ga("Encryption was skipped but no peer id was passed",bv.ERR_INVALID_PEER);a="native",i=n}if(o=s,null!=t?.muxerFactory)c=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexOutbound({...l,...s},this.muxers);c=e.muxerFactory,o=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:a,direction:"outbound",maConn:e,upgradedConn:o,muxerFactory:c,remotePeer:i,transient:t?.transient})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,transient:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),{stream:r,protocol:n}=await IE(e,t,{log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",n);const s=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(n,this.components.registrar);if(CE(n,"inbound",u)===s){const t=new Ga(`Too many inbound protocol streams for protocol "${n}" - limit ${s}`,bv.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=n,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(i,{protocols:[n]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:n})})).catch((async t=>{u.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()}))}}),l=async(e,t={})=>{if(null==c)throw new Ga("Stream is not multiplexed",bv.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",e);const r=await c.newStream();u.log.trace("started new stream %s for protocols %s",r.id,e);try{if(null==t.signal){r.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const n=AbortSignal.timeout(3e4);t={...t,signal:n}}r.log.trace("selecting protocol from protocols %s",e);const{stream:n,protocol:s}=await kE(r,e,{...t,log:r.log,yieldBytes:!0});r.log("selected protocol %s",s);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==bv.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,t),a=CE(s,"outbound",u);if(a>=o){const e=new Ga(`Too many outbound protocol streams for protocol "${s}" - ${a}/${o}`,bv.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw r.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[s]}),r.source=n.source,r.sink=n.sink,r.protocol=s,null!=n.closeWrite&&(r.closeWrite=n.closeWrite),null!=n.closeRead&&(r.closeRead=n.closeRead),null!=n.close&&(r.close=n.close),this.components.metrics?.trackProtocolStream(r,u),r}catch(t){if(u.log.error("could not create new stream for protocols %s",e,t),null==r.timeline.close&&r.abort(t),null!=t.code)throw t;throw new Ga(String(t),bv.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>(null!=u&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,transient:a,logger:this.components.logger,newStream:l??(()=>{throw new Ga("connection is not multiplexed",bv.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=c?c.streams:[],close:async e=>{null!=c&&(u.log.trace("close muxer"),await c.close(e)),u.log.trace("close maconn"),await n.close(e),u.log.trace("closed maconn")},abort:e=>{n.abort(e),null!=c&&c.abort(e)}},u=new TE(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(t.transient&&!0!==i.runOnTransientConnection)throw new Ga("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:r})}async _encryptInbound(e){const t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{const{stream:r,protocol:n}=await IE(e,t,{log:e.log}),s=this.connectionEncryption.get(n);if(null==s)throw new Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await s.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new Ga(t.message,bv.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await kE(e,r,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(null==i)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,n,t),protocol:s}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new Ga(r.message,bv.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const{stream:n,protocol:s}=await kE(e,r,{log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new Ga(String(t),bv.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{const{stream:n,protocol:s}=await IE(e,r,{log:e.log});return{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Ga(String(t),bv.ERR_MUXER_UNAVAILABLE)}}}class BE extends ni{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new ni,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new ii(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??ob(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new Xw(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Qw.includes(r)){const e=t.components[r];if(null==e&&!Jw.includes(r))throw new Ga(`${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)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.6.1"},logger:this.logger,events:t,datastore:e.datastore??new zw,connectionGater:rv(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Fw(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){const 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 PE(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 wE(this.components,e.transportManager)),this.configureComponent("connectionManager",new tE(this.components,e.connectionManager)),this.configureComponent("registrar",new mE(this.components)),this.configureComponent("addressManager",new Yw(this.components,e.addresses));const s=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new gE(this.components,{routers:s}));const i=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new rE(this.components,{routers:i})),this.configureComponent("randomWalk",new yE(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#x(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[sb]&&(this.log("registering service %s for content routing",t),i.push(r[sb])),null!=r[ib]&&(this.log("registering service %s for peer routing",t),s.push(r[ib])),null!=r[Pl]&&(this.log("registering service %s for peer discovery",t),r[Pl].addEventListener?.("peer",(e=>{this.#x(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}}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(){const e=new cb;for(const 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)throw new Ga("no protocols were provided to open a stream",bv.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ga("no protocols were provided to open a stream",bv.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){uu(e)&&(e=hl(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{const t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==bv.ERR_NOT_FOUND)throw e}const r=Jn([$t("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return function(e){const t=Rm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPublicKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PublicKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw nb(t.Type??"unknown")}}(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)}#x(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error(new Error(bv.ERR_DISCOVERED_SELF))}}async function DE(e={}){const t=e.peerId??=await Qb();if(null==t.privateKey)throw new Ga("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await async function(e){const t=Tm.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Im.RSA:return rb.rsa.unmarshalRsaPrivateKey(r);case Im.Ed25519:return rb.ed25519.unmarshalEd25519PrivateKey(r);case Im.Secp256k1:return rb.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw nb(t.Type??"RSA")}}(t.privateKey),new BE(await async function(e){const t=yv(vv,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ga(mv.ERR_PROTECTOR_REQUIRED,bv.ERR_PROTECTOR_REQUIRED);if(!(await pl(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new Ga("Private key doesn't match peer id",bv.ERR_INVALID_KEY);return t}(e))}class NE{numPeers;constructor(e){this.numPeers=e?.numPeersToUse??3}}const xE=new qn("sdk:filter"),LE={keepAlive:6e4};class OE{protocol;pubsubTopic;peers;receivedMessagesHashStr=[];keepAliveTimer=null;subscriptionCallbacks;constructor(e,t,r){this.protocol=r,this.peers=t,this.pubsubTopic=e,this.subscriptionCallbacks=new Map}async subscribe(e,t,r=LE){const n=Array.isArray(e)?e:[e];for(const e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:mn.TOPIC_DECODER_MISMATCH}],successes:[]};const s=jr(n),i=Array.from(s.keys()),o=this.peers.map((async e=>this.protocol.subscribe(this.pubsubTopic,e,i))),a=await Promise.allSettled(o),c=this.handleResult(a,"subscribe");return s.forEach(((e,r)=>{const n={decoders:e,callback:t};this.subscriptionCallbacks.set(r,n)})),r?.keepAlive&&this.startKeepAlivePings(r.keepAlive),c}async unsubscribe(e){const t=this.peers.map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.keepAliveTimer&&this.stopKeepAlivePings(),n}async ping(){const e=this.peers.map((async e=>this.protocol.ping(e))),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){const e=this.peers.map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.keepAliveTimer&&this.stopKeepAlivePings(),r}async processIncomingMessage(e){const t=function(e,t){const r=function(e,t){const r=Tn(e),n=Tn(t.contentTopic),s=function(e){if(e)return function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(e.valueOf())}(t.timestamp),i=Cn([r,t.payload,n,t.meta,s].filter(Hr));return gn(i)}(e,t);return Rn(r)}(this.pubsubTopic,e);if(this.receivedMessagesHashStr.includes(t))return void xE.info("Message already received, skipping");this.receivedMessagesHashStr.push(t);const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(xE.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:s}=e,{contentTopic:i}=r;if(i)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),i=await Promise.any(e);await s(i)}catch(e){xE.error("Error decoding message",e)}else xE.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):xE.error("No subscription callback available for ",r)}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)xE.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:mn.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}startKeepAlivePings(e){this.keepAliveTimer?xE.info("Recurring pings already set up."):this.keepAliveTimer=setInterval((()=>{(async()=>{try{xE.info("Recurring ping to peers."),await this.ping()}catch(e){xE.error("Stopping recurring pings due to failure",e),this.stopKeepAlivePings()}})()}),e)}stopKeepAlivePings(){this.keepAliveTimer?(xE.info("Stopping recurring pings."),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null):xE.info("Already stopped recurring pings.")}}class ME extends NE{protocol;activeSubscriptions=new Map;async handleIncomingMessage(e,t){const r=this.getActiveSubscription(e);r?await r.processIncomingMessage(t):xE.error(`No subscription locally registered for topic ${e}`)}constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Ls(this.handleIncomingMessage.bind(this),e,t),this.activeSubscriptions=new Map}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}async createSubscription(e){const t="string"==typeof e?e:Bn(e)?.[0];Nn(t,this.protocol.pubsubTopics);let r=[];try{r=await this.protocol.getPeers()}catch(e){return xE.error("Error getting peers to initiate subscription: ",e),{error:mn.GENERIC_FAIL,subscription:null}}return 0===r.length?{error:mn.NO_PEER_AVAILABLE,subscription:null}:(xE.info(`Creating filter subscription with ${r.length} peers: `,r.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(t)??this.setActiveSubscription(t,new OE(t,r,this.protocol))})}async subscribe(e,t,r=LE){const n=this.getUniquePubsubTopics(e);if(0===n.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(n.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:s,error:i}=await this.createSubscription(n[0]);if(i)throw Error(`Failed to create subscription: ${i}`);await s.subscribe(e,t,r);const o=Array.from(jr(Array.isArray(e)?e:[e]).keys());return async()=>{await s.unsubscribe(o)}}toSubscriptionIterator(e){return async function(e,t,r){const n=r?.iteratorDelay??60,s=[];let i;i=await e.subscribe(t,(e=>{s.push(e)}));const o=Number.isInteger(r?.timeoutMs),a=r?.timeoutMs??0,c=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-c>=a)return;await $r(n);const e=s.shift();if(!i&&0===s.length)return e;!e&&i||(yield e)}}(),async stop(){i&&(await i(),i=void 0)}}}(this,e)}getUniquePubsubTopics(e){return Array.isArray(e)?0===e.length?[]:[...new Set(e.map((e=>e.pubsubTopic)))]:[e.pubsubTopic]}}const UE=new qn("sdk:light-push");class KE extends NE{protocol;constructor(e,t){super({numPeersToUse:t?.numPeersToUse}),this.protocol=new Us(e,t)}async send(e,t){const r=[],n=[],{pubsubTopic:s}=e;try{Nn(s,this.protocol.pubsubTopics)}catch(e){return UE.error("Failed to send waku light push: pubsub topic not configured"),{failures:[{error:mn.TOPIC_NOT_CONFIGURED}],successes:[]}}const i=await this.protocol.getPeers();if(!i.length)return{successes:r,failures:[{error:mn.NO_PEER_AVAILABLE}]};const o=i.map((r=>this.protocol.send(e,t,r))),a=await Promise.allSettled(o);for(const e of a)if("fulfilled"===e.status){const{failure:t,success:s}=e.value;s&&r.push(s),t&&n.push(t)}else UE.error("Failed to send message to peer",e.reason),n.push({error:mn.GENERIC_FAIL});return{successes:r,failures:n}}}const FE=new qn("waku:store:protocol");class VE extends NE{protocol;constructor(e,t){super({numPeersToUse:1}),this.protocol=new $s(e,t)}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:s}=this.validateDecodersAndPubsubTopic(e,t),i=this.constructOptions(r,n,t),o=(await this.protocol.getPeers({numPeers:this.numPeers,maxBootstrapPeers:1}))[0];if(!o)throw new Error("No peers available to query");const a=this.protocol.queryPerPage(i,s,o);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t,r))break}async queryWithPromiseCallback(e,t,r){let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}createCursor(e){if(!(e&&e.timestamp&&e.payload&&e.contentTopic))throw new Error("Message is missing required fields");const t=Tn(e.contentTopic),r=gn(Cn([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 new Error("No decoders provided");const r=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(r.length>1)throw new Error("API does not support querying multiple pubsub topics at once");const n=r[0];if(Nn(n,this.protocol.pubsubTopics),t?.cursor?.pubsubTopic&&t.cursor.pubsubTopic!==n)throw new Error(`Cursor pubsub topic (${t?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${n})`);const s=new Map;e.forEach((e=>{if(s.has(e.contentTopic))throw new Error("API does not support different decoder per content topic");s.set(e.contentTopic,e)}));const i=e.filter((e=>e.pubsubTopic===n)).map((e=>e.contentTopic));if(0===i.length)throw new Error("No decoders found for topic "+n);return{pubsubTopic:n,contentTopics:i,decodersAsMap:s}}constructOptions(e,t,r={}){let n,s;return r?.timeFilter&&(n=r.timeFilter.startTime,s=r.timeFilter.endTime),n||FE.warn("No start time provided"),s||FE.warn("No end time provided"),Object.assign({pubsubTopic:e,pageDirection:bn.BACKWARD,pageSize:10},r,{contentTopics:t,startTime:n,endTime:s})}async processMessages(e,t,r){let n=!1,s=(await Promise.all(e)).filter(Hr);return this.shouldReverseOrder(r)&&(s=s.reverse()),await Promise.all(s.map((async e=>{e&&!n&&(n=Boolean(await t(e)))}))),n}shouldReverseOrder(e){return void 0===e?.pageDirection||e?.pageDirection===bn.BACKWARD}}async function qE(e={}){const t=await async function(e){(function(e){e.pubsubTopics?eR.info("Using pubsubTopics array to bootstrap the node."):e.contentTopics?eR.info("Using contentTopics and default cluster ID (1) to bootstrap the node."):e.shardInfo&&eR.info("Using shardInfo parameters to bootstrap the node.")})(e),e.contentTopics&&(e.shardInfo={contentTopics:e.contentTopics});const t=e.shardInfo?Mn(e.shardInfo):void 0;e.pubsubTopics=t?.pubsubTopics??e.pubsubTopics??[Sn];const r=e?.libp2p??{},n=r.peerDiscovery??[];var s,i;e?.defaultBootstrap&&n.push(...(s=e.pubsubTopics,[Uk(s.includes(Sn)?[GE.DEPRECATED_DEFAULT_PUBSUB]:[GE.SANDBOX,GE.TEST],Zk),(e,t)=>new Jk(e,t),Wk(s)])),e?.bootstrapPeers&&n.push((i={list:e.bootstrapPeers},e=>new ju(e,i))),r.peerDiscovery=n;const o=await async function(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"));const s=t?{pubsub:t}:{},i=e?{metadata:pi(e)}:{};return async function(e={}){const t=await DE(e);return!1!==e.start&&await t.start(),t}({connectionManager:{minConnections:1},transports:[Cg({filter:Rg})],streamMuxers:[ag()],connectionEncryption:[Cl()],...r,services:{identify:Mf({agentVersion:n??HE}),ping:ug({maxInboundStreams:r?.pingMaxInboundStreams??jE}),...i,...s,...r?.services}})}(t?.shardInfo,function(e={}){return t=>{e={...e,msgIdFn:({data:e})=>gn(e),globalSignaturePolicy:Kg.StrictNoSign,fallbackToFloodsub:!1};const r=new gm(t,e);return r.multicodecs=ym,r}}(e),r,e?.userAgent);return o}(e),r=function(e={}){return t=>new VE(t,e)}(e),n=function(e={}){return t=>new KE(t,e)}(e),s=(i=e,e=>new ME(e,i));var i;return new zE(e,t,r,n,s)}const HE="js-waku",jE=10,$E=new qn("waku");class zE{libp2p;relay;store;filter;lightPush;connectionManager;pubsubTopics;constructor(e,t,r,n,s,i){if(0==e.pubsubTopics.length)throw new Error("At least one pubsub topic must be provided");this.pubsubTopics=e.pubsubTopics,this.libp2p=t,r&&(this.store=r(t)),s&&(this.filter=s(t)),n&&(this.lightPush=n(t)),i&&(this.relay=i(t));const o=e.pingKeepAlive||300,a=this.relay?e.relayKeepAlive||300:0,c=this.libp2p.peerId.toString();this.connectionManager=li.create(c,t,{pingKeepAlive:o,relayKeepAlive:a},this.pubsubTopics,this.relay),$E.info("Waku node created",c,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}async dial(e,t){const r=t??[],n=function(e){return tl(e)?e:hu(e)}(e);void 0===t&&(this.relay&&r.push(yn.Relay),this.store&&r.push(yn.Store),this.filter&&r.push(yn.Filter),this.lightPush&&r.push(yn.LightPush));const s=[];return r.includes(yn.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>s.push(e))):$E.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Store)&&(this.store?s.push(this.store.protocol.multicodec):$E.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(yn.LightPush)&&(this.lightPush?s.push(this.lightPush.protocol.multicodec):$E.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(yn.Filter)&&(this.filter?s.push(this.filter.protocol.multicodec):$E.error("Filter codec not included in dial codec: protocol not mounted locally")),$E.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,s)}async start(){await this.libp2p.start()}async stop(){this.connectionManager.stop(),await this.libp2p.stop()}async subscribeToContentTopic(e,t,r){return(await async function(e,t,r){r.waku=r.waku??await qE({shardInfo:{contentTopics:[e]}});const{decoder:n,subscription:s}=await async function(e,t,r){if(!e.filter)throw new Error("Filter protocol missing from Waku node");const{shardInfo:n}=e.libp2p.components.metadata;if(!n)throw new Error("Shard info missing from Waku node.");const s=Bn(n),i=Ln(t);if(!s.includes(i))throw new Error("Content topic does not match any pubsub topic in shard info.");await e.dial(r),await ei(e,[yn.Filter]);let o=Yn(t,i);o&&(o=o??o);const{subscription:a,error:c}=await e.filter.createSubscription(i);if(c)throw new Error("Failed to create subscription for content topic.");return{decoder:o,subscription:a}}(r.waku,e,r.peer);return await s.subscribe(n,t),{subscription:s,waku:r.waku}}(e,r,{waku:this,peer:t})).subscription}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}getLocalMultiaddrWithID(){const 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()}}const GE={SANDBOX:"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",TEST:"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",DEPRECATED_DEFAULT_PUBSUB:"enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im"},WE="bootstrap",YE={store:2,filter:1,lightPush:1};var XE=__webpack_require__(495),JE=__webpack_require__.t(XE,2);const QE=BigInt(0),ZE=BigInt(1),eS=BigInt(2),tS=BigInt(3),rS=BigInt(8),nS=Object.freeze({a:QE,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:ZE,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),sS=(e,t)=>(e+t/eS)/t,iS={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=nS,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ZE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=sS(i*e,t),c=sS(-n*e,t);let l=NS(e-a*r-c*s,t),u=NS(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},oS=32,aS=32,cS=oS+1,lS=2*oS+1;function uS(e){const{a:t,b:r}=nS,n=NS(e*e),s=NS(n*e);return NS(s+t*e+r)}const hS=nS.a===QE;class dS extends Error{constructor(e){super(e)}}function pS(e){if(!(e instanceof fS))throw new TypeError("JacobianPoint expected")}class fS{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof mS))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(mS.ZERO)?fS.ZERO:new fS(e.x,e.y,ZE)}static toAffineBatch(e){const t=function(e,t=nS.P){const r=new Array(e.length),n=LS(e.reduce(((e,n,s)=>n===QE?e:(r[s]=e,NS(e*n,t))),ZE),t);return e.reduceRight(((e,n,s)=>n===QE?e:(r[s]=NS(e*r[s],t),NS(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return fS.toAffineBatch(e).map(fS.fromAffine)}equals(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a);return l===u&&h===d}negate(){return new fS(this.x,NS(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=NS(e*e),s=NS(t*t),i=NS(s*s),o=e+s,a=NS(eS*(NS(o*o)-n-i)),c=NS(tS*n),l=NS(c*c),u=NS(l-eS*a),h=NS(c*(a-u)-rS*i),d=NS(eS*t*r);return new fS(u,h,d)}add(e){pS(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===QE||i===QE)return this;if(t===QE||r===QE)return e;const a=NS(n*n),c=NS(o*o),l=NS(t*c),u=NS(s*a),h=NS(NS(r*o)*c),d=NS(NS(i*n)*a),p=NS(u-l),f=NS(d-h);if(p===QE)return f===QE?this.double():fS.ZERO;const g=NS(p*p),y=NS(p*g),m=NS(l*g),b=NS(f*f-y-eS*m),w=NS(f*(m-b)-h*y),v=NS(n*o*p);return new fS(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=fS.ZERO;if("bigint"==typeof e&&e===QE)return t;let r=DS(e);if(r===ZE)return this;if(!hS){let e=t,n=this;for(;r>QE;)r&ZE&&(e=e.add(n)),n=n.double(),r>>=ZE;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=iS.splitScalar(r),a=t,c=t,l=this;for(;s>QE||o>QE;)s&ZE&&(a=a.add(l)),o&ZE&&(c=c.add(l)),l=l.double(),s>>=ZE,o>>=ZE;return n&&(a=a.negate()),i&&(c=c.negate()),c=new fS(NS(c.x*iS.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=hS?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i>=u,o>a&&(o-=l,e+=ZE);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(gS(p,n[h])):s=s.add(gS(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=DS(e);if(hS){const{k1neg:e,k1:i,k2neg:o,k2:a}=iS.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=gS(e,c),u=gS(o,u),u=new fS(NS(u.x*iS.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return fS.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(fS.ZERO);null==e&&(e=s?rS:LS(n));const i=e,o=NS(i*i),a=NS(o*i),c=NS(t*o),l=NS(r*a),u=NS(n*i);if(s)return mS.ZERO;if(u!==ZE)throw new Error("invZ was invalid");return new mS(c,l)}}function gS(e,t){const r=t.negate();return e?r:t}fS.BASE=new fS(nS.Gx,nS.Gy,ZE),fS.ZERO=new fS(QE,ZE,QE);const yS=new WeakMap;class mS{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,yS.delete(this)}hasEvenY(){return this.y%eS===QE}static fromCompressedHex(e){const t=32===e.length,r=PS(t?e:e.subarray(1));if(!VS(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=nS,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=xS(l,tS)*l%t,h=xS(u,tS)*l%t,d=xS(h,eS)*c%t,p=xS(d,n)*d%t,f=xS(p,s)*p%t,g=xS(f,o)*f%t,y=xS(g,a)*g%t,m=xS(y,o)*f%t,b=xS(m,tS)*l%t,w=xS(b,i)*p%t,v=xS(w,r)*c%t,E=xS(v,eS);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(uS(r));const s=(n&ZE)===ZE;t?s&&(n=NS(-n)):!(1&~e[0])!==s&&(n=NS(-n));const i=new mS(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=PS(e.subarray(1,oS+1)),r=PS(e.subarray(oS+1,2*oS+1)),n=new mS(t,r);return n.assertValidity(),n}static fromHex(e){const t=BS(e),r=t.length,n=t[0];if(r===oS)return this.fromCompressedHex(t);if(r===cS&&(2===n||3===n))return this.fromCompressedHex(t);if(r===lS&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${cS} compressed bytes or ${lS} uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return mS.BASE.multiply(HS(e))}static fromSignature(e,t,r){const{r:n,s}=jS(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const i=OS(BS(e)),{n:o}=nS,a=2===r||3===r?n+o:n,c=LS(a,o),l=NS(-i*c,o),u=NS(s*c,o),h=1&r?"03":"02",d=mS.fromHex(h+IS(a)),p=mS.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return CS(this.toHex(e))}toHex(e=!1){const t=IS(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${IS(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!VS(t)||!VS(r))throw new Error(e);const n=NS(r*r);if(NS(n-uS(t))!==QE)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new mS(this.x,NS(-this.y))}double(){return fS.fromAffine(this).double().toAffine()}add(e){return fS.fromAffine(this).add(fS.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return fS.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=fS.fromAffine(this),s=t===QE||t===ZE||this!==mS.BASE?n.multiplyUnsafe(t):n.multiply(t),i=fS.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(fS.ZERO)?void 0:o.toAffine()}}function bS(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function wS(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${_S(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:PS(r),left:e.subarray(t+2)}}mS.BASE=new mS(nS.Gx,nS.Gy),mS.ZERO=new mS(QE,QE);class vS{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?_S(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new vS(TS(n.slice(0,64)),TS(n.slice(64,128)))}static fromDER(e){const t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${_S(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=wS(e.subarray(2)),{data:n,left:s}=wS(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${_S(s)}`);return{r:t,s:n}}(t?e:CS(e));return new vS(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!FS(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!FS(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=nS.n>>ZE;return this.s>e}normalizeS(){return this.hasHighS()?new vS(this.r,NS(-this.s,nS.n)):this}toDERRawBytes(){return CS(this.toDERHex())}toDERHex(){const e=bS(RS(this.s)),t=bS(RS(this.r)),r=e.length/2,n=t.length/2,s=RS(r),i=RS(n);return`30${RS(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return CS(this.toCompactHex())}toCompactHex(){return IS(this.r)+IS(this.s)}}function ES(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;tt.toString(16).padStart(2,"0")));function _S(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r0)return BigInt(e);if("bigint"==typeof e&&FS(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function NS(e,t=nS.P){const r=e%t;return r>=QE?r:t+r}function xS(e,t){const{P:r}=nS;let n=e;for(;t-- >QE;)n*=n,n%=r;return n}function LS(e,t=nS.P){if(e===QE||t<=QE)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=NS(e,t),n=t,s=QE,i=ZE,o=ZE,a=QE;for(;r!==QE;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==ZE)throw new Error("invert: does not exist");return NS(s,t)}function OS(e,t=!1){const r=function(e){const t=8*e.length-8*aS,r=PS(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=nS;return r>=n?r-n:r}let MS,US;class KS{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new 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 JS.hmacSha256(this.k,...e)}hmacSync(...e){return US(this.k,...e)}checkSync(){if("function"!=typeof US)throw new dS("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new 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;const t=[];for(;e0)t=BigInt(e);else if("string"==typeof e){if(e.length!==2*aS)throw new Error("Expected 32 bytes of private key");t=TS(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(e.length!==aS)throw new Error("Expected 32 bytes of private key");t=PS(e)}if(!FS(t))throw new Error("Expected private key: 0 < key < n");return t}function jS(e){if(e instanceof vS)return e.assertValidity(),e;try{return vS.fromDER(e)}catch(t){return vS.fromCompact(e)}}function $S(e){return PS(e.length>oS?e.slice(0,oS):e)}function zS(e){const t=$S(e),r=NS(t,nS.n);return GS(r{e=BS(e);const t=aS+8;if(e.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return kS(NS(PS(e),nS.n-ZE)+ZE)},randomBytes:(e=32)=>{if(YS.web)return YS.web.getRandomValues(new Uint8Array(e));if(YS.node){const{randomBytes:t}=YS.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>JS.hashToPrivateKey(JS.randomBytes(aS+8)),precompute(e=8,t=mS.BASE){const r=t===mS.BASE?t:new mS(t.x,t.y);return r._setWindowSize(e),r.multiply(tS),r},sha256:async(...e)=>{if(YS.web){const t=await YS.web.subtle.digest("SHA-256",ES(...e));return new Uint8Array(t)}if(YS.node){const{createHash:t}=YS.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(YS.web){const r=await YS.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=ES(...t),s=await YS.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(YS.node){const{createHmac:r}=YS.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=XS[e];if(void 0===r){const t=await JS.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return JS.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof MS)throw new dS("sha256Sync is undefined, you need to set it");let r=XS[e];if(void 0===r){const t=MS(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=ES(t,t),XS[e]=r}return MS(r,...t)},_JacobianPoint:fS};Object.defineProperties(JS,{sha256Sync:{configurable:!1,get:()=>MS,set(e){MS||(MS=e)}},hmacSha256Sync:{configurable:!1,get:()=>US,set(e){US||(US=e)}}});var QS=__webpack_require__(1176);function ZS(e){return new Uint8Array(QS.keccak256.arrayBuffer(e))}function e_(e,t,r){try{return function(e,t,r,n=WS){let s;try{s=jS(e),t=BS(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=OS(t);let c;try{c=function(e){return e instanceof mS?(e.assertValidity(),e):mS.fromHex(e)}(r)}catch(e){return!1}const{n:l}=nS,u=LS(o,l),h=NS(a*u,l),d=NS(i*u,l),p=mS.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&NS(p.x,l)===i}(vS.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const t_="Invalid record id";function r_(e,t){switch(t){case"udp":return r_(e,"udp4")||r_(e,"udp6");case"tcp":return r_(e,"tcp4")||r_(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=hu("/"+e+"/"+$l(e,r));return s=s.encapsulate(hu("/"+t+"/"+$l(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}function n_(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const s_=32,i_=64,o_=32;function a_(e,t){const r=new Uint8Array(i_);for(let n=0;nFr(d_)}(h_||(h_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(p_||(p_={})),function(e){let t;e.codec=()=>(null==t&&(t=Vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),h_.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=h_.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ir(t,e.codec()),e.decode=t=>ue(t,e.codec())}(f_||(f_={}));class g_{_key;constructor(e){this._key=E_(e,s_)}verify(e,t){return function(e,t,r){return xa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return p_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class y_{_key;_publicKey;constructor(e,t){this._key=E_(e,i_),this._publicKey=E_(t,s_)}sign(e){return function(e,t){const r=e.subarray(0,o_);return xa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new g_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=kt.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function m_(e){if(e.length>i_){const t=(e=E_(e,i_+s_)).subarray(0,i_),r=e.subarray(i_,e.length);return new y_(t,r)}const t=(e=E_(e,i_)).subarray(0,i_),r=e.subarray(s_);return new y_(t,r)}function b_(e){return e=E_(e,s_),new g_(e)}async function w_(){const{privateKey:e,publicKey:t}=function(){const e=xa.utils.randomPrivateKey(),t=xa.getPublicKey(e);return{privateKey:a_(e,t),publicKey:t}}();return new y_(e,t)}async function v_(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==o_)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=xa.getPublicKey(t);return{privateKey:a_(t,r),publicKey:r}}(e);return new y_(t,r)}function E_(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ga(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function S_(e){const t=[await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await A_(e)],r=await __({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function __(e){if(null==e.privateKey||null==e.publicKey)throw new Ga("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([c_.get().subtle.exportKey("jwk",e.privateKey),c_.get().subtle.exportKey("jwk",e.publicKey)])}async function A_(e){return c_.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 I_(e){if("RSA"!==e.kty)throw new Ga("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Ga("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*$t(e.n,"base64url").length}function k_(e){if(isNaN(e)||e<=0)throw new Ga("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return cn(e)}function R_(e){let t=e.toString(16);t.length%2>0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,i=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}const C_=8192;class P_{_key;constructor(e){this._key=e}verify(e,t){return async function(e,t,r){const n=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return c_.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}(this._key,t,e)}marshal(){return function(e){if(null==e.n||null==e.e)throw new Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Ud({valueHex:new Jd({value:[Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return p_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}}class B_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return k_(16)}sign(e){return async function(e,t){const r=await c_.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await c_.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Ga("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new P_(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 Ga("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Jd({value:[new Hd({value:0}),Hd.fromBigInt(T_($t(e.n,"base64url"))),Hd.fromBigInt(T_($t(e.e,"base64url"))),Hd.fromBigInt(T_($t(e.d,"base64url"))),Hd.fromBigInt(T_($t(e.p,"base64url"))),Hd.fromBigInt(T_($t(e.q,"base64url"))),Hd.fromBigInt(T_($t(e.dp,"base64url"))),Hd.fromBigInt(T_($t(e.dq,"base64url"))),Hd.fromBigInt(T_($t(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return f_.encode({Type:h_.RSA,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return async function(e,t){const r=c_.get(),n=new Jd({value:[new Hd({value:0}),new Jd({value:[new Gd({value:"1.2.840.113549.1.1.1"}),new Dd]}),new Od({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),i=k_(16),o=await mh(Io,t,i,{c:1e4,dkLen:32}),a=k_(16),c=await r.subtle.importKey("raw",o,"AES-CBC",!1,["encrypt"]),l=await r.subtle.encrypt({name:"AES-CBC",iv:a},c,s),u=new Jd({value:[new Od({valueHex:i}),new Hd({value:1e4}),new Hd({value:32}),new Jd({value:[new Gd({value:"1.2.840.113549.2.11"}),new Dd]})]}),h=new Jd({value:[new Gd({value:"1.2.840.113549.1.5.13"}),new Jd({value:[new Jd({value:[new Gd({value:"1.2.840.113549.1.5.12"}),u]}),new Jd({value:[new Gd({value:"2.16.840.1.101.3.4.1.42"}),new Od({valueHex:a})]})]})]}),d=new Jd({value:[h,new Od({valueHex:l})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...An(new Uint8Array(d,0,d.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}(this,e);if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function D_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value;return{n:An(R_(r[1].toBigInt()),"base64url"),e:An(R_(r[2].toBigInt()),"base64url"),d:An(R_(r[3].toBigInt()),"base64url"),p:An(R_(r[4].toBigInt()),"base64url"),q:An(R_(r[5].toBigInt()),"base64url"),dp:An(R_(r[6].toBigInt()),"base64url"),dq:An(R_(r[7].toBigInt()),"base64url"),qi:An(R_(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await S_(t);return new B_(r.privateKey,r.publicKey)}function N_(e){const t=function(e){const{result:t}=Rd(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:An(R_(r[0].toBigInt()),"base64url"),e:An(R_(r[1].toBigInt()),"base64url")}}(e);if(I_(t)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new P_(t)}async function x_(e){if(I_(e)>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await S_(e);return new B_(t.privateKey,t.publicKey)}async function L_(e){if(e>C_)throw new Ga("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await c_.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 __(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new B_(t.privateKey,t.publicKey)}function O_(e){try{$c.ProjectivePoint.fromHex(e)}catch(e){throw new Ga(String(e),"ERR_INVALID_PUBLIC_KEY")}}class M_{_key;constructor(e){O_(e),this._key=e}verify(e,t){return function(e,t,r){const n=Pt.digest(r instanceof Uint8Array?r:r.subarray());if(n_(n))return n.then((({digest:r})=>$c.verify(t,r,e))).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.verify(t,n.digest,e)}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,$c.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return p_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}async hash(){const e=Pt.digest(this.bytes);let t;return n_(e)?({bytes:t}=await e):t=e.bytes,t}}class U_{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return $c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{$c.getPublicKey(e,!0)}catch(e){throw new Ga(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),O_(this._publicKey)}sign(e){return function(e,t){const r=Pt.digest(t instanceof Uint8Array?t:t.subarray());if(n_(r))return r.then((({digest:t})=>$c.sign(t,e).toDERRawBytes())).catch((e=>{throw new Ga(String(e),"ERR_INVALID_INPUT")}));try{return $c.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ga(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new M_(this._publicKey)}marshal(){return this._key}get bytes(){return f_.encode({Type:h_.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Qn(this.bytes,e.bytes)}hash(){const e=Pt.digest(this.bytes);return n_(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return An(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return u_(this.bytes,e);throw new Ga(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function K_(e){return new U_(e)}function F_(e){return new M_(e)}async function V_(){const e=$c.utils.randomPrivateKey();return new U_(e)}const q_={rsa:B,ed25519:P,secp256k1:D};function H_(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function j_(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class $_ 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(){const e=this.get("id");if(!e)throw new Error("id not found.");return Rn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(t_)}get rs(){const e=this.get("rs");if(e)return Un(e)}get rsv(){const e=this.get("rsv");if(e)return Un(e)}get ip(){return z_(this,"ip","ip4")}set ip(e){W_(this,"ip","ip4",e)}get tcp(){return G_(this,"tcp","tcp")}set tcp(e){Y_(this,"tcp","tcp",e)}get udp(){return G_(this,"udp","udp")}set udp(e){Y_(this,"udp","udp",e)}get ip6(){return z_(this,"ip6","ip6")}set ip6(e){W_(this,"ip6","ip6",e)}get tcp6(){return G_(this,"tcp6","tcp")}set tcp6(e){Y_(this,"tcp6","tcp",e)}get udp6(){return G_(this,"udp6","udp")}set udp6(e){Y_(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){X_(this,"waku2",e,(e=>new Uint8Array([j_(e)])))}}function z_(e,t,r){const n=e.get(t);if(n)return $l(r,n)}function G_(e,t,r){const n=e.get(t);if(n)return Number($l(r,n))}function W_(e,t,r,n){X_(e,t,n,zl.bind({},r))}function Y_(e,t,r,n){W_(e,t,r,n?.toString(10))}function X_(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function J_(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=BS(e),s=HS(t),i=[GS(s),zS(n)];if(null!=r){!0===r&&(r=JS.randomBytes(oS));const e=BS(r);if(e.length!==oS)throw new Error(`sign: Expected ${oS} bytes of extra data`);i.push(e)}return{seed:ES(...i),m:$S(n),d:s}}(e,t,r.extraEntropy),o=new KS(32,aS);let a;for(await o.reseed(n);!(a=qS(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(ZS(t),e,{der:!1})}const Q_=new qn("enr");var Z_,eA;!function(e){e.TCP="tcp",e.UDP="udp"}(Z_||(Z_={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(eA||(eA={}));class tA extends $_{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){const n=new tA(e,t,r);try{const e=n.publicKey;e&&(n.peerId=await function(e){return pl(new q_.secp256k1.Secp256k1PublicKey(e).bytes,void 0)}(e))}catch(e){Q_.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=mS.fromHex(e).toRawBytes(!1);return kn(ZS(t.slice(1)))}(this.publicKey):void 0;throw new Error(t_)}getLocationMultiaddr=r_.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Q_.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new 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(){const e=[];for(const t of Object.values(eA)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const 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 new Error(t_);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return e_(t,ZS(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(t_);return this.signature=await J_(t,e),this.signature}}let rA=!1,nA=!1;const sA={debug:1,default:2,info:2,warning:3,error:4,off:5};let iA=sA.default,oA=null;const aA=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var cA,lA;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(cA||(cA={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(lA||(lA={}));const uA="0123456789abcdef";class hA{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==sA[r]&&this.throwArgumentError("invalid log level name","logLevel",e),iA>sA[r]||console.log.apply(console,t)}debug(...e){this._log(hA.levels.DEBUG,e)}info(...e){this._log(hA.levels.INFO,e)}warn(...e){this._log(hA.levels.WARNING,e)}makeError(e,t,r){if(nA)return this.makeError("censored error",t,{});t||(t=hA.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4],r+=uA[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}`);const s=e;let i="";switch(t){case lA.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case lA.CALL_EXCEPTION:case lA.INSUFFICIENT_FUNDS:case lA.MISSING_NEW:case lA.NONCE_EXPIRED:case lA.REPLACEMENT_UNDERPRICED:case lA.TRANSACTION_REPLACED:case lA.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=new Error(e);return o.reason=s,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,hA.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"),aA&&this.throwError("platform missing String.prototype.normalize",hA.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:aA})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,hA.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,hA.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",hA.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",hA.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",hA.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return oA||(oA=new hA("logger/5.7.0")),oA}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),rA){if(!e)return;this.globalLogger().throwError("error censorship permanent",hA.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}nA=!!e,rA=!!t}static setLogLevel(e){const t=sA[e.toLowerCase()];null!=t?iA=t:hA.globalLogger().warn("invalid log level - "+e)}static from(e){return new hA(e)}}hA.errors=lA,hA.levels=cA;const dA=new hA("bytes/5.7.0");function pA(e){return!!e.toHexString}function fA(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return fA(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function gA(e){return"number"==typeof e&&e==e&&e%1==0}function yA(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!gA(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function mA(e,t){if(t||(t={}),"number"==typeof e){dA.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),fA(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),pA(e)&&(e=e.toHexString()),bA(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":dA.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e>4]+wA[15&n]}return t}return dA.throwArgumentError("invalid hexlify value","value",e)}const EA=new hA("rlp/5.7.0");function SA(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function _A(e,t,r){let n=0;for(let s=0;st+1+n&&EA.throwError("child data too short",hA.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function kA(e,t){if(0===e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&EA.throwError("data short segment too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data long segment too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),IA(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{});const n=_A(e,t+1,r);return t+1+r+n>e.length&&EA.throwError("data array too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:vA(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&EA.throwError("data too short",hA.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:vA(e.slice(t+1,t+1+r))}}return{consumed:1,result:vA(e[t])}}const RA=new qn("enr:decoder");class TA{static fromString(e){if(!e.startsWith(tA.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${tA.RECORD_PREFIX}'`);return TA.fromRLP($t(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=mA(e),r=kA(t,0);return r.consumed!==t.length&&EA.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(In);return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;eCA.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let s=0;for(let i=0;i(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},DA={name:"v6",size:16,isFormat:e=>e.length>0&&PA.test(e),encode(e,t,r){let n=16+(r=~~r),s=-1,i=0,o=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l>8),r=97?u-=87:u>=65?u-=55:(u-=48,o=10*o+u),i=(i<<4)+u)}if(!1===a)!0===c?(r>8),r=s+2;e--)t[e]=t[e-2];t[s]=0,t[s+1]=0,s=r}if(s!==r&&-1!==s)for(r>n-2&&(r=n-2);n>s;)t[--n]=rs?t[--r]:0;else for(;r=qA||(64512&e.charCodeAt(i))!==qA?t+=3:(n=i,t+=4)}}return t}function jA(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(HA(e)+r));let s=r;for(let r=0;r>6,t[s++]=128|63&i;else if((63488&i)!==VA)t[s++]=224|(61440&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i;else{const o=r+1;if(o===n||i>=qA)t[s++]=239,t[s++]=191,t[s++]=189;else{const n=e.charCodeAt(o);(64512&n)!==qA?(t[s++]=239,t[s++]=191,t[s++]=189):(r=o,i=65536|(1023&i)<<10|1023&n,t[s++]=240|(1835008&i)>>18,t[s++]=128|(258048&i)>>12,t[s++]=128|(4032&i)>>6,t[s++]=128|63&i)}}}return jA.bytes=s-r,t}function $A(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let s=t;s191&&t<224)r=(31&t)<<6|63&e[s++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;const i=VA|r>>10&1023;n+=String.fromCharCode(i),r=qA|1023&r}else r=(15&t)<<12|(63&e[s++])<<6|63&e[s++];n+=String.fromCharCode(r)}return $A.bytes=r-t,n}jA.bytes=0,$A.bytes=0;const zA=e=>e instanceof Uint8Array;function GA(e){return"string"==typeof e?HA(e):e.byteLength}function WA(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):jA(e)}function YA(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return jA(t,e,r),jA.bytes}const XA=Math.pow(2,24),JA=Math.pow(2,16),QA=Math.pow(2,8),ZA=(e,t)=>e[t]*XA+e[t+1]*JA+e[t+2]*QA+e[t+3],eI=(e,t)=>e[t]<<8|e[t+1],tI=(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),rI=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function nI(e,t,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=t.length||n>=s?0:function(e,t,r,n,s){s-n>t.length-r&&(s=n+t.length-r);let i=s-n;const o=e.length-n;return i>o&&(i=o),(0!==n||se)}}const iI=sI({encode(e,t,r){t||(t=new Uint8Array(iI.encodingLength(e))),r||(r=0);const n=r,s=e.replace(/^\.|\.$/gm,"");if(s.length){const e=s.split(".");for(let n=0;n=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(i+=o?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=eI(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,i+=o?0:1,o=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=a+1,s>254)throw new Error("Cannot decode name (name too long)");r.push($A(e,t,t+a)),t+=a,i+=o?0:a}}return iI.decode.bytes=i,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:GA(e.replace(/^\.|\.$/gm,""))+2}),oI=sI({encode(e,t,r){t||(t=new Uint8Array(oI.encodingLength(e))),r||(r=0);const n=YA(t,e,r+1);return t[r]=n,oI.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=$A(e,t+1,t+1+r);return oI.decode.bytes=r+1,n},encodingLength:e=>GA(e)+1}),aI=sI({bytes:12,encode(e,t,r){t||(t=new Uint8Array(aI.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),s="response"===e.type?32768:0;return rI(t,e.id||0,r),rI(t,n|s,r+2),rI(t,e.questions.length,r+4),rI(t,e.answers.length,r+6),rI(t,e.authorities.length,r+8),rI(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw new Error("Header must be 12 bytes");const r=eI(e,t+2);return{id:eI(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:MA(r>>11&15),flag_aa:1==(r>>10&1),flag_tc:1==(r>>9&1),flag_rd:1==(r>>8&1),flag_ra:1==(r>>7&1),flag_z:1==(r>>6&1),flag_ad:1==(r>>5&1),flag_cd:1==(r>>4&1),rcode:OA(15&r),questions:new Array(eI(e,t+4)),answers:new Array(eI(e,t+6)),authorities:new Array(eI(e,t+8)),additionals:new Array(eI(e,t+10))}},encodingLength:()=>12}),cI=sI({encode(e,t,r){t||(t=new Uint8Array(cI.encodingLength(e))),r||(r=0);const n=e.length;return rI(t,n,r),nI(e,t,r+2,0,n),cI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n=e.slice(t+2,t+2+r);return cI.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),lI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(lI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),lI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=eI(e,t),n=iI.decode(e,t+2);return lI.decode.bytes=r+2,n},encodingLength:e=>iI.encodingLength(e)+2}),uI=sI({encode(e,t,r){t||(t=new Uint8Array(uI.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mname,t,r),r+=iI.encode.bytes,iI.encode(e.rname,t,r),r+=iI.encode.bytes,tI(t,e.serial||0,r),r+=4,tI(t,e.refresh||0,r),r+=4,tI(t,e.retry||0,r),r+=4,tI(t,e.expire||0,r),r+=4,tI(t,e.minimum||0,r),rI(t,(r+=4)-n-2,n),uI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=iI.decode(e,t),t+=iI.decode.bytes,n.rname=iI.decode(e,t),t+=iI.decode.bytes,n.serial=ZA(e,t),t+=4,n.refresh=ZA(e,t),t+=4,n.retry=ZA(e,t),t+=4,n.expire=ZA(e,t),t+=4,n.minimum=ZA(e,t),t+=4,uI.decode.bytes=t-r,n},encodingLength:e=>22+iI.encodingLength(e.mname)+iI.encodingLength(e.rname)}),hI=sI({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t0;){const r=e[t++];if(--n,ne?(zA(e)?e.length:GA(e))+2:2}),pI=sI({encode(e,t,r){t||(t=new Uint8Array(pI.encodingLength(e))),r||(r=0);const n=r;return r+=2,oI.encode(e.cpu,t,r),r+=oI.encode.bytes,oI.encode(e.os,t,r),r+=oI.encode.bytes,rI(t,r-n-2,n),pI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=oI.decode(e,t),t+=oI.decode.bytes,n.os=oI.decode(e,t),t+=oI.decode.bytes,pI.decode.bytes=t-r,n},encodingLength:e=>oI.encodingLength(e.cpu)+oI.encodingLength(e.os)+2}),fI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(fI.encodingLength(e))),r||(r=0),iI.encode(e,t,r+2),rI(t,iI.encode.bytes,r),fI.encode.bytes=iI.encode.bytes+2,t),decode(e,t){t||(t=0);const r=iI.decode(e,t+2);return fI.decode.bytes=iI.decode.bytes+2,r},encodingLength:e=>iI.encodingLength(e)+2}),gI=sI({encode(e,t,r){t||(t=new Uint8Array(gI.encodingLength(e))),r||(r=0),rI(t,e.priority||0,r+2),rI(t,e.weight||0,r+4),rI(t,e.port||0,r+6),iI.encode(e.target,t,r+8);const n=iI.encode.bytes+6;return rI(t,n,r),gI.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=eI(e,t),n={};return n.priority=eI(e,t+2),n.weight=eI(e,t+4),n.port=eI(e,t+6),n.target=iI.decode(e,t+8),gI.decode.bytes=r+2,n},encodingLength:e=>8+iI.encodingLength(e.target)}),yI=sI({encode(e,t,r){const n=yI.encodingLength(e);return t||(t=new Uint8Array(yI.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=yI.ISSUER_CRITICAL),rI(t,n-2,r),t[r+=2]=e.flags||0,r+=1,oI.encode(e.tag,t,r),r+=oI.encode.bytes,YA(t,e.value,r),r+=GA(e.value),yI.encode.bytes=n,t},decode(e,t){t||(t=0);const r=eI(e,t),n=t+=2,s={};return s.flags=e[t],t+=1,s.tag=oI.decode(e,t),t+=oI.decode.bytes,s.value=$A(e,t,n+r),s.issuerCritical=!!(s.flags&yI.ISSUER_CRITICAL),yI.decode.bytes=r+2,s},encodingLength:e=>oI.encodingLength(e.tag)+oI.encodingLength(e.value)+2});yI.ISSUER_CRITICAL=128;const mI=sI({encode(e,t,r){t||(t=new Uint8Array(mI.encodingLength(e))),r||(r=0);const n=r;return r+=2,rI(t,e.preference||0,r),r+=2,iI.encode(e.exchange,t,r),r+=iI.encode.bytes,rI(t,r-n-2,n),mI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=eI(e,t),t+=2,n.exchange=iI.decode(e,t),t+=iI.decode.bytes,mI.decode.bytes=t-r,n},encodingLength:e=>4+iI.encodingLength(e.exchange)}),bI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(bI.encodingLength(e))),r||(r=0),rI(t,4,r),r+=2,BA.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,BA.decode(e,t)),bytes:6}),wI=sI({encode:(e,t,r)=>(t||(t=new Uint8Array(wI.encodingLength(e))),r||(r=0),rI(t,16,r),r+=2,DA.encode(e,t,r),wI.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=DA.decode(e,t);return wI.decode.bytes=18,r},bytes:18}),vI=e=>new Uint8Array(e),EI=sI({encode(e,t,r){t||(t=new Uint8Array(EI.encodingLength(e))),r||(r=0);const n=r,s=FA(e.code);if(rI(t,s,r),r+=2,e.data)rI(t,e.data.length,r),r+=2,nI(e.data,t,r),r+=e.data.length;else switch(s){case 8:{const n=e.sourcePrefixLength||0,s=e.family||function(e){return NA(e)===BA.size?1:2}(e.ip),i=function(e,t,r){r=~~r;const n=NA(e);return"function"==typeof t&&(t=t(r+n)),n===BA.size?BA.encode(e,t,r):DA.encode(e,t,r)}(e.ip,vI),o=Math.ceil(n/8);rI(t,o+4,r),rI(t,s,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,nI(i,t,r,0,o),r+=o}break;case 11:e.timeout?(rI(t,2,r),r+=2,rI(t,e.timeout,r),r+=2):(rI(t,0,r),r+=2);break;case 12:{const n=e.length||0;rI(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;rI(t,n,r),r+=2;for(const n of e.tags)rI(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return EI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=eI(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);const n=eI(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=eI(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const s=new Uint8Array(1===r.family?4:16);nI(e,s,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===BA.size)return BA.decode(e,t,r);if(r===DA.size)return DA.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${BA.size} for v4 or ${DA.size} for v6.`)}(s)}break;case 11:n>0&&(r.timeout=eI(e,t),t+=2);break;case 14:r.tags=[];for(let s=0;s0;)n[i++]=EI.decode(e,t),t+=EI.decode.bytes,s-=EI.decode.bytes;return SI.decode.bytes=t-r,n},encodingLength:e=>2+VI(e||[],EI)}),_I=sI({encode(e,t,r){t||(t=new Uint8Array(_I.encodingLength(e))),r||(r=0);const n=r,s=e.key;if(!zA(s))throw new Error("Key must be a Buffer");return r+=2,rI(t,e.flags,r),t[r+=2]=_I.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,nI(s,t,r+=1,0,s.length),r+=s.length,_I.encode.bytes=r-n,rI(t,_I.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);if(t+=2,n.flags=eI(e,t),e[t+=2]!==_I.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+s+2),t+=n.key.length,_I.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.key)});_I.PROTOCOL_DNSSEC=3,_I.ZONE_KEY=128,_I.SECURE_ENTRYPOINT=32768;const AI=sI({encode(e,t,r){t||(t=new Uint8Array(AI.encodingLength(e))),r||(r=0);const n=r,s=e.signature;if(!zA(s))throw new Error("Signature must be a Buffer");return r+=2,rI(t,LA(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,tI(t,e.originalTTL,r),r+=4,tI(t,e.expiration,r),r+=4,tI(t,e.inception,r),r+=4,rI(t,e.keyTag,r),r+=2,iI.encode(e.signersName,t,r),nI(s,t,r+=iI.encode.bytes,0,s.length),r+=s.length,AI.encode.bytes=r-n,rI(t,AI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.typeCovered=xA(eI(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=ZA(e,t),t+=4,n.expiration=ZA(e,t),t+=4,n.inception=ZA(e,t),t+=4,n.keyTag=eI(e,t),t+=2,n.signersName=iI.decode(e,t),t+=iI.decode.bytes,n.signature=e.slice(t,r+s+2),t+=n.signature.length,AI.decode.bytes=t-r,n},encodingLength:e=>20+iI.encodingLength(e.signersName)+GA(e.signature)}),II=sI({encode(e,t,r){t||(t=new Uint8Array(II.encodingLength(e))),r||(r=0);const n=r;return r+=2,iI.encode(e.mbox||".",t,r),r+=iI.encode.bytes,iI.encode(e.txt||".",t,r),r+=iI.encode.bytes,II.encode.bytes=r-n,rI(t,II.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=iI.decode(e,t)||".",t+=iI.decode.bytes,n.txt=iI.decode(e,t)||".",t+=iI.decode.bytes,II.decode.bytes=t-r,n},encodingLength:e=>2+iI.encodingLength(e.mbox||".")+iI.encodingLength(e.txt||".")}),kI=sI({encode(e,t,r){t||(t=new Uint8Array(kI.encodingLength(e))),r||(r=0);const n=r,s=[];for(let t=0;t>8]&&(s[r>>8]=[]),s[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e2+iI.encodingLength(e.nextDomain)+kI.encodingLength(e.rrtypes)}),TI=sI({encode(e,t,r){t||(t=new Uint8Array(TI.encodingLength(e))),r||(r=0);const n=r,s=e.salt;if(!zA(s))throw new Error("salt must be a Buffer");const i=e.nextDomain;if(!zA(i))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,rI(t,e.iterations,r),t[r+=2]=s.length,nI(s,t,r+=1,0,s.length),t[r+=s.length]=i.length,nI(i,t,r+=1,0,i.length),r+=i.length,kI.encode(e.rrtypes,t,r),r+=kI.encode.bytes,TI.encode.bytes=r-n,rI(t,TI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=eI(e,t);const i=e[t+=2];t+=1,n.salt=e.slice(t,t+i);const o=e[t+=i];return t+=1,n.nextDomain=e.slice(t,t+o),t+=o,n.rrtypes=kI.decode(e,t,s-(t-r)),t+=kI.decode.bytes,TI.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+kI.encodingLength(e.rrtypes)}),CI=sI({encode(e,t,r){t||(t=new Uint8Array(CI.encodingLength(e))),r||(r=0);const n=r,s=e.digest;if(!zA(s))throw new Error("Digest must be a Buffer");return r+=2,rI(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,nI(s,t,r+=1,0,s.length),r+=s.length,CI.encode.bytes=r-n,rI(t,CI.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=eI(e,t);return t+=2,n.keyTag=eI(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+s+2),t+=n.digest.length,CI.decode.bytes=t-r,n},encodingLength:e=>6+GA(e.digest)});function PI(e){switch(e.toUpperCase()){case"A":return bI;case"PTR":case"CNAME":case"DNAME":return fI;case"TXT":return hI;case"NULL":return dI;case"AAAA":return wI;case"SRV":return gI;case"HINFO":return pI;case"CAA":return yI;case"NS":return lI;case"SOA":return uI;case"MX":return mI;case"OPT":return SI;case"DNSKEY":return _I;case"RRSIG":return AI;case"RP":return II;case"NSEC":return RI;case"NSEC3":return TI;case"DS":return CI}return cI}const BI=sI({encode(e,t,r){t||(t=new Uint8Array(BI.encodingLength(e))),r||(r=0);const n=r;if(iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");rI(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,rI(t,e.flags||0,r+6),r+=8,SI.encode(e.options||[],t,r),r+=SI.encode.bytes}else{let n=KA(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),rI(t,n,r+2),tI(t,e.ttl||0,r+4),r+=8;const s=PI(e.type);s.encode(e.data,t,r),r+=s.encode.bytes}return BI.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=iI.decode(e,t),t+=iI.decode.bytes,r.type=xA(eI(e,t)),"OPT"===r.type)r.udpPayloadSize=eI(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=eI(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=SI.decode(e,t+8),t+=8+SI.decode.bytes;else{const n=eI(e,t+2);r.ttl=ZA(e,t+4),r.class=UA(-32769&n),r.flush=!!(32768&n);const s=PI(r.type);r.data=s.decode(e,t+8),t+=8+s.decode.bytes}return BI.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return iI.encodingLength(e.name)+8+PI(e.type).encodingLength(t)}}),DI=sI({encode(e,t,r){t||(t=new Uint8Array(DI.encodingLength(e))),r||(r=0);const n=r;return iI.encode(e.name,t,r),r+=iI.encode.bytes,rI(t,LA(e.type),r),r+=2,rI(t,KA(void 0===e.class?"IN":e.class),r),r+=2,DI.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=iI.decode(e,t),t+=iI.decode.bytes,n.type=xA(eI(e,t)),t+=2,n.class=UA(eI(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),DI.decode.bytes=t-r,n},encodingLength:e=>iI.encodingLength(e.name)+4}),NI=256,xI={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(FI(e))),r||(r=0);const s=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),aI.encode(e,t,r),r+=aI.encode.bytes,r=qI(e.questions,DI,t,r),r=qI(e.answers,BI,t,r),r=qI(e.authorities,BI,t,r),r=qI(e.additionals,BI,t,r),xI.encode.bytes=r-s,n&&UI.bytes!==t.length?t.slice(0,UI.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=aI.decode(e,t);return t+=aI.decode.bytes,t=HI(n.questions,DI,e,t),t=HI(n.answers,BI,e,t),t=HI(n.authorities,BI,e,t),t=HI(n.additionals,BI,e,t),xI.decode.bytes=t-r,n},encodingLength:function(e){return aI.encodingLength(e)+VI(e.questions||[],DI)+VI(e.answers||[],BI)+VI(e.authorities||[],BI)+VI(e.additionals||[],BI)}};function LI(e,t){if(e.questions)throw new Error("Only one .question object expected instead of a .questions array!");const r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}xI.encode.bytes=0,xI.decode.bytes=0;const OI={encode:function(e,t,r){return t=xI.encode(LI(e,"query"),t,r),OI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return OI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"query"))}};OI.encode.bytes=0,OI.decode.bytes=0;const MI={encode:function(e,t,r){return t=xI.encode(LI(e,"response"),t,r),MI.encode.bytes=xI.encode.bytes,t},decode:function(e,t){const r=xI.decode(e,t);return MI.decode.bytes=xI.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return xI.encodingLength(LI(e,"response"))}};MI.encode.bytes=0,MI.decode.bytes=0;const UI=xI.encode,KI=xI.decode,FI=xI.encodingLength;function VI(e,t){let r=0;for(let n=0;n255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==s[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);s[r]=e,i[e]=r}const o=r.charCodeAt(0),a={name:e,encodingLength(e){const 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);const i=n%4,c=n-i;let l=r,u=0;for(;u>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===i){const r=s[e.charCodeAt(u)]<<10|s[e.charCodeAt(u+1)]<<4|s[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===i&&(t[l++]=s[e.charCodeAt(u)]<<2|s[e.charCodeAt(u+1)]>>4);return a.encode.bytes=l-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);const s=r-t,c=s%3,l=t+s-c,u=[];for(let r=t;r>18&63],i[t>>12&63],i[t>>6&63],i[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(i[t>>10],i[t>>4&63],i[t<<2&63]),1===n&&u.push(o)}else if(1===c){const t=e[r-1];u.push(i[t>>2],i[t<<4&63]),1===n&&u.push(o,o)}return a.decode.bytes=s,String.fromCharCode.apply(String,u)}};return a}jI("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const $I=jI("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let zI="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;zI||(zI=class extends Error{constructor(e="Request aborted."){super(e)}}),zI.prototype.name="AbortError",zI.prototype.code="ABORT_ERR";const GI="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class WI 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}}}WI.prototype.name="HTTPStatusError",WI.prototype.code="HTTP_STATUS";class YI extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:ZI(this.cause)}}}YI.prototype.name="ResponseError",YI.prototype.code="RESPONSE_ERR";class XI extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}XI.prototype.name="TimeoutError",XI.prototype.code="ETIMEOUT";const JI=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,QI=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function ZI(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const ek=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,tk=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,rk=/\[(((pk|name)=([^\]]+)))\]/gi;function nk(e,t){t.lastIndex=0;const r={};for(;;){const n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class sk extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${ik.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}sk.prototype.name="InvalidProtocolError",sk.prototype.code="EPROTOCOL";const ik=["http:","https:","udp4:","udp6:"];class ok{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;const 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))throw new Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`);this.port=r}}toJSON(){return this.toString()}}class ak extends ok{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){const 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 ck extends ak{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw new Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class lk extends ak{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw new Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function uk(e){return QI.test(e)&&!JI.test(e)?`[${e}]`:e}class hk extends ok{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 new 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){const e=QI.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||JI.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${uk(this.host)}:${this.port}${this.path}`;try{this.url=new GI(t)}catch(e){throw new Error(e.message+` [${t}]`)}}toString(){const 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,s=this.name?` [name=${this.name}]`:"",i=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",o=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${uk(this.host)}${t}${n}${r}${i}${o}${s}`}}function dk(e){let t;if("string"==typeof e)t=function(e){const t=ek.exec(e),r=t[2]||"https:",n=t[3],s=t[5],i=t[6],o=t[7];if("https:"===r||"http:"===r){const e=nk(o,tk);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:s,path:i,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=nk(o,rk),i=/^\[(.*)\]$/.exec(n);if(i&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!i&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return i?new lk({protocol:"udp6:",ipv6:i[1],port:s,pk:t.pk,name:t.name}):new ck({protocol:"udp4:",ipv4:n,port:s,pk:t.pk,name:t.name})}throw new sk(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Can not convert ${e} to an endpoint`);if(e instanceof ok)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new ck(t);if("udp6:"===r)return new lk(t);if("https:"===r||"http:"===r)return new hk(t);throw new sk(r,JSON.stringify(t))}const pk="application/dns-message";function fk(){}function gk(e,t,r,n,s){return new Promise(((i,o)=>{const a=new GI(e);"GET"===t&&r&&(a.search="?dns="+$I.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",pk),"POST"===t&&l.setRequestHeader("Content-Type",pk),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new XI(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new WI(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new WI(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new WI(c,l.status,t));else{let e;if("string"==typeof l.response)e=jA(l.response);else if(l.response instanceof Uint8Array)e=l.response;else{if(!(Array.isArray(l.response)||l.response instanceof ArrayBuffer))throw new Error("Unprocessable response "+l.response);e=new Uint8Array(l.response)}u(null,e)}},"POST"===t?l.send(r):l.send(),s&&s.addEventListener("abort",h);let u=function(e,t){u=fk,s&&s.removeEventListener("abort",h),i(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new zI);try{l.abort()}catch(e){}}}))}function yk(e){const t=null===e.time||void 0===e.time?Date.now():e.time,r=function(e){return e.filter((e=>e.cors||e.endpoint.cors))}(e.data.map((e=>(e.endpoint=dk(Object.assign({name:e.name},e.endpoint)),e)))),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}}Error;const mk=yk({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});const bk=new GI("https://martinheidegger.github.io/dns-query/resolvers.json");function wk(e){return/^@/.test(e)}const vk=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:bk,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r,n){const s=t?t.localStoragePrefix+t.name:null;if(s)try{const e=JSON.parse(localStorage.getItem(s));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:i}=await gk(e,"GET",null,r,void 0),o={time:Date.now(),data:JSON.parse($A(i))};if(s)try{localStorage.setItem(s,JSON.stringify(o))}catch(e){o.time=null}return o}(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=>yk({data:e.data.resolvers,time:e.time}))).catch((()=>t||mk)):Promise.resolve(mk),this._dataP):this._dataP.then((e=>e.timee.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=_k),"dns"===e&&(e=Ak),"function"==typeof e)return this.data().then((t=>t.endpoints.filter(e)));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(wk))try{return Promise.resolve(e.map(dk))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(wk(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return dk(e)}))))}};function Ek(e,t){return t=Object.assign({retries:5,timeout:3e4},t),e.question?(r=t.endpoints,function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(r)?r:Promise.resolve(r)).then((r=>{if(!Array.isArray(r)||0===r.length)throw new Error("No endpoints defined to lookup dns records.");return Sk(r.map(dk),function(e){const t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(e),t)})).then((e=>(e.question=e.questions[0],delete e.questions,e))):Promise.reject(new Error("To request data you need to specify a .question!"));var r}function Sk(e,t,r){const n=1===e.length?e[0]:e[Math.floor(Math.random()*e.length)%e.length];return function(e,t,r,n){return n&&n.aborted?Promise.reject(new zI):"udp4:"===e.protocol||"udp6:"===e.protocol?function(){throw new Error('Only "doh" endpoints are supported in the browser')}():function(e,t,r,n){return function(e,t,r,n,s){return gk(e,t,r,n,s)}(e.url,e.method,UI(Object.assign({flags:NI},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new YI("Empty.");else try{const e=KI(t);return e.response=r,e}catch(e){n=new YI("Invalid packet (cause="+e.message+")",e)}throw Object.assign(n,{response:r})}))}(e,t,r,n)}(n,t,r.timeout,r.signal).then((e=>(e.endpoint=n.toString(),e)),(s=>{if("AbortError"===s.name||0===r.retries)throw s.endpoint=n.toString(),s;return r.retries>0&&(r.retries-=1),Sk(e,t,r)}))}function _k(e){return"https:"===e.protocol||"http:"===e.protocol}function Ak(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const Ik=new qn("dns-over-https");class kk{endpoints;retries;static async create(e,t){const r=e??await vk.endpoints("doh");return new kk(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await Ek({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw Ik.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=t.map((e=>e.data)),n=[];return r.forEach((e=>{"string"==typeof e?n.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?n.push(e):n.push(Rn(e))})):n.push(Rn(e))})),n}}var Rk=__webpack_require__(5818);class Tk{static RECORD_PREFIX=tA.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 new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=Tk.parseRootValues(e),n=Rk.decode.asBytes(t),s=e.split(" sig")[0],i=Tn(s);if(!e_($t(r.signature,"base64url").slice(0,64),ZS(i),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const Ck=new qn("discovery:fetch_nodes");function Pk(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function Bk(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function Dk(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function Nk(e,t,r){if(Pk(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relaythis._search(s,i)));return xk.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){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=Tk.parseTree(e[r]),i={domain:s,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=new Set;for(;!Pk(n,i)&&othis._search(s,i))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(Tk.ROOT_PREFIX)?Tk.ROOT_PREFIX:e.startsWith(Tk.BRANCH_PREFIX)?Tk.BRANCH_PREFIX:e.startsWith(Tk.RECORD_PREFIX)?Tk.RECORD_PREFIX:""}(r);try{switch(i){case Tk.ROOT_PREFIX:return n=Tk.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case Tk.BRANCH_PREFIX:return s=Tk.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case Tk.RECORD_PREFIX:return TA.fromString(r);default:return null}}catch(t){return xk.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return xk.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const Ok=new qn("peer-discovery-dns");class Mk extends ni{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;Ok.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){if(Ok.info("Starting peer discovery via dns"),this._started=!0,void 0===this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await Lk.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[WE]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(WE)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:Kn(r)}}})),s&&this.dispatchEvent(new ii("peer",{detail:t}))}}stop(){this._started=!1}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}function Uk(e,t=YE){return r=>new Mk(r,{enrUrls:e,wantedNodeCapabilityCount:t})}class Kk{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new Kk({query:{numPeers:t},response:void 0})}encode(){return Or.encode(this.proto)}static decode(e){const t=Or.decode(e);return new Kk(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const Fk="/vac/waku/peer-exchange/2.0.0-alpha1",Vk=new qn("peer-exchange");class qk extends _s{constructor(e,t){super(Fk,e,Vk,t)}async query(e){const{numPeers:t}=e,r=Kk.createRequest({numPeers:BigInt(t)}),n=await this.peerStore.get(e.peerId);if(!n)return{peerInfos:null,error:mn.NO_PEER_AVAILABLE};let s;try{s=await this.getStream(n)}catch(e){return Vk.error("Failed to get stream",e),{peerInfos:null,error:mn.NO_STREAM_AVAILABLE}}const i=await ys([r.encode()],is,s,ls,(async e=>await Xn(e)));try{const e=new rs;i.forEach((t=>{e.append(t)}));const{response:t}=Kk.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Hr).map((async e=>({ENR:await TA.fromRLP(e)})))),error:null}:(Vk.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:mn.EMPTY_PAYLOAD})}catch(e){return Vk.error("Failed to decode push reply",e),{peerInfos:null,error:mn.DECODE_FAILED}}}}const Hk=new qn("peer-exchange-discovery"),jk=1e4,$k=3,zk=wn.PEER_EXCHANGE;class Gk extends ni{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(Fk)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>Hk.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new qk(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(Hk.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(Hk.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Pl](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=jk,maxRetries:n=$k}=this.options;Hk.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const s=this.queryAttempts.get(t)??1;s>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,s+1),this.startRecurringQueries(e).catch((e=>{Hk.error(`Error in startRecurringQueries: ${e}`)}))}),r*s)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return Hk.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){Hk.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;r&&n&&(await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{tags:{[zk]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:Kn(s)}}}),Hk.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))))}return{error:null,peerInfos:r}}abortQueriesForPeer(e){Hk.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}}function Wk(e){return t=>new Gk(t,e)}const Yk=new qn("peer-exchange-discovery"),Xk=wn.LOCAL;class Jk extends ni{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){Yk.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=await ew({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[hu(t)],tags:{[this.options?.tagName??Xk]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new ii("peer",{detail:{id:r,multiaddrs:[hu(t)]}})))}Yk.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(Yk.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find((e=>e.toString().includes("ws")||e.toString().includes("wss")));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),s=this.getPeersFromLocalStorage(),i=s.findIndex((e=>e.id===t.toString()));i>=0?s[i].address=n.toString():s.push({id:t.toString(),address:n.toString()}),this.peers=s,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(Qk):[]}catch(e){return Yk.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){Yk.error("Error saving peers to local storage:",e)}}}function Qk(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const Zk={lightPush:1,filter:1,store:1},eR=new qn("sdk:create");var tR,rR=__webpack_require__(2549),nR=function(e,t,r,n){return new(r||(r=Promise))((function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},sR=function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0?[4,this.send(this.queue)]:[3,2];case 1:e.sent()&&(console.log("Sent ",this.queue.length," telemetry logs"),this.queue=[]),e.label=2;case 2:return[2]}}))}))}),this.intervalPeriod)),[2]}))}))},e.prototype.stop=function(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)},e.prototype.send=function(e){return nR(this,void 0,void 0,(function(){var t,r,n,s=this;return sR(this,(function(i){switch(i.label){case 0:t=e.map((function(e){return{id:++s.requestId,telemetryType:e.messageType.toString(),telemetryData:e}})),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=i.sent()).status?(console.error("Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=i.sent(),console.error("Error sending messages to telemetry service: ",n),console.error("Failed trying to send the following messages: ",t),[2,!1];case 4:return[2]}}))}))},e}(),oR=function(e){return t=void 0,r=void 0,s=function(){var t,r,n;return function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&(e.push([{messageType:tR.LIGHT_PUSH_FILTER,timestamp:Math.floor((new Date).getTime()/1e3),peerIdSender:r,peerIdReporter:r,sequenceHash:o,sequenceTotal:a,sequenceIndex:c,contentTopic:lR,pubsubTopic:Ln(lR)}]),d=document.createElement("div"),p=document.getElementById("messagesSent"),d.textContent="Message: ".concat(o," ").concat(c," of ").concat(a),p.insertBefore(d,p.firstChild),p.insertBefore(document.createElement("br"),p.firstChild),document.dispatchEvent(dR),c++),h.failures.length>0&&console.error("Failed to send message",h.failures),c} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(\"@protobufjs/aspromise\"),\r\n inquire = require(\"@protobufjs/inquire\");\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n var options = options || {};\n this._capacity = options.capacity;\n\n this._head = 0;\n this._tail = 0;\n\n if (Array.isArray(array)) {\n this._fromArray(array);\n } else {\n this._capacityMask = 0x3;\n this._list = new Array(4);\n }\n}\n\n/**\n * --------------\n * PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var len = this.size();\n if (i >= len || i < -len) return undefined;\n if (i < 0) i += len;\n i = (this._head + i) & this._capacityMask;\n return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n if (this._head === this._tail) return undefined;\n return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n get: function length() {\n return this.size();\n }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n if (this._head === this._tail) return 0;\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n if (arguments.length === 0) return this.size();\n var len = this._list.length;\n this._head = (this._head - 1 + len) & this._capacityMask;\n this._list[this._head] = item;\n if (this._tail === this._head) this._growArray();\n if (this._capacity && this.size() > this._capacity) this.pop();\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n var head = this._head;\n if (head === this._tail) return undefined;\n var item = this._list[head];\n this._list[head] = undefined;\n this._head = (head + 1) & this._capacityMask;\n if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n if (arguments.length === 0) return this.size();\n var tail = this._tail;\n this._list[tail] = item;\n this._tail = (tail + 1) & this._capacityMask;\n if (this._tail === this._head) {\n this._growArray();\n }\n if (this._capacity && this.size() > this._capacity) {\n this.shift();\n }\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n var tail = this._tail;\n if (tail === this._head) return undefined;\n var len = this._list.length;\n this._tail = (tail - 1 + len) & this._capacityMask;\n var item = this._list[this._tail];\n this._list[this._tail] = undefined;\n if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size) return void 0;\n if (i < 0) i += size;\n i = (this._head + i) & this._capacityMask;\n var item = this._list[i];\n var k;\n if (index < size / 2) {\n for (k = index; k > 0; k--) {\n this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._head = (this._head + 1 + len) & this._capacityMask;\n } else {\n for (k = size - 1 - index; k > 0; k--) {\n this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._tail = (this._tail - 1 + len) & this._capacityMask;\n }\n return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n var i = index;\n var removed;\n var del_count = count;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size || count < 1) return void 0;\n if (i < 0) i += size;\n if (count === 1 || !count) {\n removed = new Array(1);\n removed[0] = this.removeOne(i);\n return removed;\n }\n if (i === 0 && i + count >= size) {\n removed = this.toArray();\n this.clear();\n return removed;\n }\n if (i + count > size) count = size - i;\n var k;\n removed = new Array(count);\n for (k = 0; k < count; k++) {\n removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n }\n i = (this._head + i) & this._capacityMask;\n if (index + count === size) {\n this._tail = (this._tail - count + len) & this._capacityMask;\n for (k = count; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (index === 0) {\n this._head = (this._head + count + len) & this._capacityMask;\n for (k = count - 1; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (i < size / 2) {\n this._head = (this._head + index + count + len) & this._capacityMask;\n for (k = index; k > 0; k--) {\n this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n }\n i = (this._head - 1 + len) & this._capacityMask;\n while (del_count > 0) {\n this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n if (index < 0) this._tail = i;\n } else {\n this._tail = i;\n i = (i + count + len) & this._capacityMask;\n for (k = size - (count + index); k > 0; k--) {\n this.push(this._list[i++]);\n }\n i = this._tail;\n while (del_count > 0) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n }\n if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var size = this.size();\n if (i < 0) i += size;\n if (i > size) return void 0;\n if (arguments.length > 2) {\n var k;\n var temp;\n var removed;\n var arg_len = arguments.length;\n var len = this._list.length;\n var arguments_index = 2;\n if (!size || i < size / 2) {\n temp = new Array(i);\n for (k = 0; k < i; k++) {\n temp[k] = this._list[(this._head + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i > 0) {\n this._head = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._head = (this._head + i + len) & this._capacityMask;\n }\n while (arg_len > arguments_index) {\n this.unshift(arguments[--arg_len]);\n }\n for (k = i; k > 0; k--) {\n this.unshift(temp[k - 1]);\n }\n } else {\n temp = new Array(size - (i + count));\n var leng = temp.length;\n for (k = 0; k < leng; k++) {\n temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i != size) {\n this._tail = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._tail = (this._tail - leng + len) & this._capacityMask;\n }\n while (arguments_index < arg_len) {\n this.push(arguments[arguments_index++]);\n }\n for (k = 0; k < leng; k++) {\n this.push(temp[k]);\n }\n }\n return removed;\n } else {\n return this.remove(i, count);\n }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n this._list = new Array(this._list.length);\n this._head = 0;\n this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n return this._copyArray(false);\n};\n\n/**\n * -------------\n * INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n var length = array.length;\n var capacity = this._nextPowerOf2(length);\n\n this._list = new Array(capacity);\n this._capacityMask = capacity - 1;\n this._tail = length;\n\n for (var i = 0; i < length; i++) this._list[i] = array[i];\n};\n\n/**\n *\n * @param fullCopy\n * @param size Initialize the array with a specific size. Will default to the current list size\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy, size) {\n var src = this._list;\n var capacity = src.length;\n var length = this.length;\n size = size | length;\n\n // No prealloc requested and the buffer is contiguous\n if (size == length && this._head < this._tail) {\n // Simply do a fast slice copy\n return this._list.slice(this._head, this._tail);\n }\n\n var dest = new Array(size);\n\n var k = 0;\n var i;\n if (fullCopy || this._head > this._tail) {\n for (i = this._head; i < capacity; i++) dest[k++] = src[i];\n for (i = 0; i < this._tail; i++) dest[k++] = src[i];\n } else {\n for (i = this._head; i < this._tail; i++) dest[k++] = src[i];\n }\n\n return dest;\n}\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n if (this._head != 0) {\n // double array size and copy existing data, head to end, then beginning to tail.\n var newList = this._copyArray(true, this._list.length << 1);\n\n this._tail = this._list.length;\n this._head = 0;\n\n this._list = newList;\n } else {\n this._tail = this._list.length;\n this._list.length <<= 1;\n }\n\n this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n this._list.length >>>= 1;\n this._capacityMask >>>= 1;\n};\n\n/**\n * Find the next power of 2, at least 4\n * @private\n * @param {number} num \n * @returns {number}\n */\nDenque.prototype._nextPowerOf2 = function _nextPowerOf2(num) {\n var log2 = Math.log(num) / Math.log(2);\n var nextPow2 = 1 << (log2 + 1);\n\n return Math.max(nextPow2, 4);\n}\n\nmodule.exports = Denque;\n","'use strict';\n\n/**\n * @typedef {{ [key: string]: any }} Extensions\n * @typedef {Error} Err\n * @property {string} message\n */\n\n/**\n *\n * @param {Error} obj\n * @param {Extensions} props\n * @returns {Error & Extensions}\n */\nfunction assign(obj, props) {\n for (const key in props) {\n Object.defineProperty(obj, key, {\n value: props[key],\n enumerable: true,\n configurable: true,\n });\n }\n\n return obj;\n}\n\n/**\n *\n * @param {any} err - An Error\n * @param {string|Extensions} code - A string code or props to set on the error\n * @param {Extensions} [props] - Props to set on the error\n * @returns {Error & Extensions}\n */\nfunction createError(err, code, props) {\n if (!err || typeof err === 'string') {\n throw new TypeError('Please pass an Error to err-code');\n }\n\n if (!props) {\n props = {};\n }\n\n if (typeof code === 'object') {\n props = code;\n code = '';\n }\n\n if (code) {\n props.code = code;\n }\n\n try {\n return assign(err, props);\n } catch (_) {\n props.message = err.message;\n props.stack = err.stack;\n\n const ErrClass = function () {};\n\n ErrClass.prototype = Object.create(Object.getPrototypeOf(err));\n\n // @ts-ignore\n const output = assign(new ErrClass(), props);\n\n return output;\n }\n}\n\nmodule.exports = createError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst event_iterator_1 = require(\"./event-iterator\");\nexports.EventIterator = event_iterator_1.EventIterator;\nfunction subscribe(event, options, evOptions) {\n return new event_iterator_1.EventIterator(({ push }) => {\n this.addEventListener(event, push, options);\n return () => this.removeEventListener(event, push, options);\n }, evOptions);\n}\nexports.subscribe = subscribe;\nexports.default = event_iterator_1.EventIterator;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass EventQueue {\n constructor() {\n this.pullQueue = [];\n this.pushQueue = [];\n this.eventHandlers = {};\n this.isPaused = false;\n this.isStopped = false;\n }\n push(value) {\n if (this.isStopped)\n return;\n const resolution = { value, done: false };\n if (this.pullQueue.length) {\n const placeholder = this.pullQueue.shift();\n if (placeholder)\n placeholder.resolve(resolution);\n }\n else {\n this.pushQueue.push(Promise.resolve(resolution));\n if (this.highWaterMark !== undefined &&\n this.pushQueue.length >= this.highWaterMark &&\n !this.isPaused) {\n this.isPaused = true;\n if (this.eventHandlers.highWater) {\n this.eventHandlers.highWater();\n }\n else if (console) {\n console.warn(`EventIterator queue reached ${this.pushQueue.length} items`);\n }\n }\n }\n }\n stop() {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n for (const placeholder of this.pullQueue) {\n placeholder.resolve({ value: undefined, done: true });\n }\n this.pullQueue.length = 0;\n }\n fail(error) {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n if (this.pullQueue.length) {\n for (const placeholder of this.pullQueue) {\n placeholder.reject(error);\n }\n this.pullQueue.length = 0;\n }\n else {\n const rejection = Promise.reject(error);\n /* Attach error handler to avoid leaking an unhandled promise rejection. */\n rejection.catch(() => { });\n this.pushQueue.push(rejection);\n }\n }\n remove() {\n Promise.resolve().then(() => {\n if (this.removeCallback)\n this.removeCallback();\n });\n }\n [Symbol.asyncIterator]() {\n return {\n next: (value) => {\n const result = this.pushQueue.shift();\n if (result) {\n if (this.lowWaterMark !== undefined &&\n this.pushQueue.length <= this.lowWaterMark &&\n this.isPaused) {\n this.isPaused = false;\n if (this.eventHandlers.lowWater) {\n this.eventHandlers.lowWater();\n }\n }\n return result;\n }\n else if (this.isStopped) {\n return Promise.resolve({ value: undefined, done: true });\n }\n else {\n return new Promise((resolve, reject) => {\n this.pullQueue.push({ resolve, reject });\n });\n }\n },\n return: () => {\n this.isStopped = true;\n this.pushQueue.length = 0;\n this.remove();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n }\n}\nclass EventIterator {\n constructor(listen, { highWaterMark = 100, lowWaterMark = 1 } = {}) {\n const queue = new EventQueue();\n queue.highWaterMark = highWaterMark;\n queue.lowWaterMark = lowWaterMark;\n queue.removeCallback =\n listen({\n push: value => queue.push(value),\n stop: () => queue.stop(),\n fail: error => queue.fail(error),\n on: (event, fn) => {\n queue.eventHandlers[event] = fn;\n },\n }) || (() => { });\n this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();\n Object.freeze(this);\n }\n}\nexports.EventIterator = EventIterator;\nexports.default = EventIterator;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n","/*\n * [hi-base32]{@link https://github.com/emn178/hi-base32}\n *\n * @version 0.5.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var root = typeof window === 'object' ? window : {};\n var NODE_JS = !root.HI_BASE32_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n }\n var COMMON_JS = !root.HI_BASE32_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var BASE32_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('');\n var BASE32_DECODE_CHAR = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16,\n 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,\n 'Z': 25, '2': 26, '3': 27, '4': 28, '5': 29, '6': 30, '7': 31\n };\n\n var blocks = [0, 0, 0, 0, 0, 0, 0, 0];\n\n var throwInvalidUtf8 = function (position, partial) {\n if (partial.length > 10) {\n partial = '...' + partial.substr(-10);\n }\n var err = new Error('Decoded data is not valid UTF-8.'\n + ' Maybe try base32.decode.asBytes()?'\n + ' Partial data after reading ' + position + ' bytes: ' + partial + ' <-');\n err.position = position;\n throw err;\n };\n\n var toUtf8String = function (bytes) {\n var str = '', length = bytes.length, i = 0, followingChars = 0, b, c;\n while (i < length) {\n b = bytes[i++];\n if (b <= 0x7F) {\n str += String.fromCharCode(b);\n continue;\n } else if (b > 0xBF && b <= 0xDF) {\n c = b & 0x1F;\n followingChars = 1;\n } else if (b <= 0xEF) {\n c = b & 0x0F;\n followingChars = 2;\n } else if (b <= 0xF7) {\n c = b & 0x07;\n followingChars = 3;\n } else {\n throwInvalidUtf8(i, str);\n }\n\n for (var j = 0; j < followingChars; ++j) {\n b = bytes[i++];\n if (b < 0x80 || b > 0xBF) {\n throwInvalidUtf8(i, str);\n }\n c <<= 6;\n c += b & 0x3F;\n }\n if (c >= 0xD800 && c <= 0xDFFF) {\n throwInvalidUtf8(i, str);\n }\n if (c > 0x10FFFF) {\n throwInvalidUtf8(i, str);\n }\n\n if (c <= 0xFFFF) {\n str += String.fromCharCode(c);\n } else {\n c -= 0x10000;\n str += String.fromCharCode((c >> 10) + 0xD800);\n str += String.fromCharCode((c & 0x3FF) + 0xDC00);\n }\n }\n return str;\n };\n\n var decodeAsBytes = function (base32Str) {\n if (base32Str === '') {\n return [];\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n base32Str = base32Str.replace(/=/g, '');\n var v1, v2, v3, v4, v5, v6, v7, v8, bytes = [], index = 0, length = base32Str.length;\n\n // 4 char to 3 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n bytes[index++] = (v7 << 5 | v8) & 255;\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n }\n return bytes;\n };\n\n var encodeAscii = function (str) {\n var v1, v2, v3, v4, v5, base32Str = '', length = str.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i++);\n v5 = str.charCodeAt(i++);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encodeUtf8 = function (str) {\n var v1, v2, v3, v4, v5, code, end = false, base32Str = '',\n index = 0, i, start = 0, bytes = 0, length = str.length;\n if (str === '') {\n return base32Str;\n }\n do {\n blocks[0] = blocks[5];\n blocks[1] = blocks[6];\n blocks[2] = blocks[7];\n for (i = start; index < length && i < 5; ++index) {\n code = str.charCodeAt(index);\n if (code < 0x80) {\n blocks[i++] = code;\n } else if (code < 0x800) {\n blocks[i++] = 0xc0 | (code >> 6);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i++] = 0xe0 | (code >> 12);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++index) & 0x3ff));\n blocks[i++] = 0xf0 | (code >> 18);\n blocks[i++] = 0x80 | ((code >> 12) & 0x3f);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n }\n }\n bytes += i - start;\n start = i - 5;\n if (index === length) {\n ++index;\n }\n if (index > length && i < 6) {\n end = true;\n }\n v1 = blocks[0];\n if (i > 4) {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n v5 = blocks[4];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n } else if (i === 1) {\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (i === 2) {\n v2 = blocks[1];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (i === 3) {\n v2 = blocks[1];\n v3 = blocks[2];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n } while (!end);\n return base32Str;\n };\n\n var encodeBytes = function (bytes) {\n var v1, v2, v3, v4, v5, base32Str = '', length = bytes.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i++];\n v5 = bytes[i++];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = bytes[i++];\n v2 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encode = function (input, asciiOnly) {\n var notString = typeof(input) !== 'string';\n if (notString && input.constructor === ArrayBuffer) {\n input = new Uint8Array(input);\n }\n if (notString) {\n return encodeBytes(input);\n } else if (asciiOnly) {\n return encodeAscii(input);\n } else {\n return encodeUtf8(input);\n }\n };\n\n var decode = function (base32Str, asciiOnly) {\n if (!asciiOnly) {\n return toUtf8String(decodeAsBytes(base32Str));\n }\n if (base32Str === '') {\n return '';\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n var v1, v2, v3, v4, v5, v6, v7, v8, str = '', length = base32Str.indexOf('=');\n if (length === -1) {\n length = base32Str.length;\n }\n\n // 8 char to 5 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255) +\n String.fromCharCode((v7 << 5 | v8) & 255);\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255);\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255);\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255);\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255);\n }\n return str;\n };\n\n var exports = {\n encode: encode,\n decode: decode\n };\n decode.asBytes = decodeAsBytes;\n\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n root.base32 = exports;\n if (AMD) {\n define(function() {\n return exports;\n });\n }\n }\n})();\n","// https://github.com/electron/electron/issues/2288\nfunction isElectron() {\n // Renderer process\n if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {\n return true;\n }\n\n // Main process\n if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {\n return true;\n }\n\n // Detect the user agent when the `nodeIntegration` option is set to false\n if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = isElectron;\n","'use strict';\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n};\n","/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.9.3\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2023\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n\n var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray\n ? function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n }\n : Array.isArray;\n\n var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))\n ? function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n }\n : ArrayBuffer.isView;\n\n // [message: string, isString: bool]\n var formatMessage = function (message) {\n var type = typeof message;\n if (type === 'string') {\n return [message, true];\n }\n if (type !== 'object' || message === null) {\n throw new Error(INPUT_ERROR);\n }\n if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n return [new Uint8Array(message), false];\n }\n if (!isArray(message) && !isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n return [message, false];\n }\n\n var empty = function (message) {\n return formatMessage(message)[0].length === 0;\n };\n\n var cloneArray = function (array) {\n var newArray = [];\n for (var i = 0; i < array.length; ++i) {\n newArray[i] = array[i];\n }\n return newArray;\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (empty(n) && empty(s)) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var result = formatMessage(message);\n message = result[0];\n var isString = result[1];\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (isString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var result = formatMessage(str);\n str = result[0];\n var isString = result[1];\n var bytes = 0, length = str.length;\n if (isString) {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n } else {\n bytes = length;\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = (w - bytes % w) % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n array[j] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n define(function () {\n return methods;\n });\n }\n }\n})();\n","'use strict';\nconst isOptionObject = require('is-plain-obj');\n\nconst {hasOwnProperty} = Object.prototype;\nconst {propertyIsEnumerable} = Object;\nconst defineProperty = (object, name, value) => Object.defineProperty(object, name, {\n\tvalue,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true\n});\n\nconst globalThis = this;\nconst defaultMergeOptions = {\n\tconcatArrays: false,\n\tignoreUndefined: false\n};\n\nconst getEnumerableOwnPropertyKeys = value => {\n\tconst keys = [];\n\n\tfor (const key in value) {\n\t\tif (hasOwnProperty.call(value, key)) {\n\t\t\tkeys.push(key);\n\t\t}\n\t}\n\n\t/* istanbul ignore else */\n\tif (Object.getOwnPropertySymbols) {\n\t\tconst symbols = Object.getOwnPropertySymbols(value);\n\n\t\tfor (const symbol of symbols) {\n\t\t\tif (propertyIsEnumerable.call(value, symbol)) {\n\t\t\t\tkeys.push(symbol);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys;\n};\n\nfunction clone(value) {\n\tif (Array.isArray(value)) {\n\t\treturn cloneArray(value);\n\t}\n\n\tif (isOptionObject(value)) {\n\t\treturn cloneOptionObject(value);\n\t}\n\n\treturn value;\n}\n\nfunction cloneArray(array) {\n\tconst result = array.slice(0, 0);\n\n\tgetEnumerableOwnPropertyKeys(array).forEach(key => {\n\t\tdefineProperty(result, key, clone(array[key]));\n\t});\n\n\treturn result;\n}\n\nfunction cloneOptionObject(object) {\n\tconst result = Object.getPrototypeOf(object) === null ? Object.create(null) : {};\n\n\tgetEnumerableOwnPropertyKeys(object).forEach(key => {\n\t\tdefineProperty(result, key, clone(object[key]));\n\t});\n\n\treturn result;\n}\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {string[]} keys keys to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nconst mergeKeys = (merged, source, keys, config) => {\n\tkeys.forEach(key => {\n\t\tif (typeof source[key] === 'undefined' && config.ignoreUndefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Do not recurse into prototype chain of merged\n\t\tif (key in merged && merged[key] !== Object.getPrototypeOf(merged)) {\n\t\t\tdefineProperty(merged, key, merge(merged[key], source[key], config));\n\t\t} else {\n\t\t\tdefineProperty(merged, key, clone(source[key]));\n\t\t}\n\t});\n\n\treturn merged;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n *\n * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat)\n */\nconst concatArrays = (merged, source, config) => {\n\tlet result = merged.slice(0, 0);\n\tlet resultIndex = 0;\n\n\t[merged, source].forEach(array => {\n\t\tconst indices = [];\n\n\t\t// `result.concat(array)` with cloning\n\t\tfor (let k = 0; k < array.length; k++) {\n\t\t\tif (!hasOwnProperty.call(array, k)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tindices.push(String(k));\n\n\t\t\tif (array === merged) {\n\t\t\t\t// Already cloned\n\t\t\t\tdefineProperty(result, resultIndex++, array[k]);\n\t\t\t} else {\n\t\t\t\tdefineProperty(result, resultIndex++, clone(array[k]));\n\t\t\t}\n\t\t}\n\n\t\t// Merge non-index keys\n\t\tresult = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config);\n\t});\n\n\treturn result;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nfunction merge(merged, source, config) {\n\tif (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) {\n\t\treturn concatArrays(merged, source, config);\n\t}\n\n\tif (!isOptionObject(source) || !isOptionObject(merged)) {\n\t\treturn clone(source);\n\t}\n\n\treturn mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config);\n}\n\nmodule.exports = function (...options) {\n\tconst config = merge(clone(defaultMergeOptions), (this !== globalThis && this) || {}, defaultMergeOptions);\n\tlet merged = {_: {}};\n\n\tfor (const option of options) {\n\t\tif (option === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isOptionObject(option)) {\n\t\t\tthrow new TypeError('`' + option + '` is not an Option Object');\n\t\t}\n\n\t\tmerged = merge(merged, {_: option}, config);\n\t}\n\n\treturn merged._;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","module.exports = require('./lib/murmurHash3js');\n","/* jshint -W086: true */\n// +----------------------------------------------------------------------+\n// | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js\n// | A javascript implementation of MurmurHash3's x86 hashing algorithms. |\n// |----------------------------------------------------------------------|\n// | Copyright (c) 2012-2015 Karan Lyons |\n// | https://github.com/karanlyons/murmurHash3.js/blob/c1778f75792abef7bdd74bc85d2d4e1a3d25cfe9/murmurHash3.js |\n// | Freely distributable under the MIT license. |\n// +----------------------------------------------------------------------+\n\n;(function (root, undefined) {\n 'use strict';\n\n // Create a local object that'll be exported or referenced globally.\n var library = {\n 'version': '3.0.0',\n 'x86': {},\n 'x64': {},\n 'inputValidation': true\n };\n\n // PRIVATE FUNCTIONS\n // -----------------\n\n function _validBytes(bytes) {\n // check the input is an array or a typed array\n if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) {\n return false;\n }\n\n // check all bytes are actually bytes\n for (var i = 0; i < bytes.length; i++) {\n if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {\n return false;\n }\n }\n return true;\n }\n\n function _x86Multiply(m, n) {\n //\n // Given two 32bit ints, returns the two multiplied together as a\n // 32bit int.\n //\n\n return ((m & 0xffff) * n) + ((((m >>> 16) * n) & 0xffff) << 16);\n }\n\n function _x86Rotl(m, n) {\n //\n // Given a 32bit int and an int representing a number of bit positions,\n // returns the 32bit int rotated left by that number of positions.\n //\n\n return (m << n) | (m >>> (32 - n));\n }\n\n function _x86Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x86 mix of that block.\n //\n\n h ^= h >>> 16;\n h = _x86Multiply(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = _x86Multiply(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h;\n }\n\n function _x64Add(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // added together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] + n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] + n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] + n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += m[0] + n[0];\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Multiply(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // multiplied together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] * n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] * n[3];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[2] += m[3] * n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] * n[3];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[2] * n[2];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[3] * n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Rotl(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) rotated left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 32) {\n return [m[1], m[0]];\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];\n } else {\n n -= 32;\n return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];\n }\n }\n\n function _x64LeftShift(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) shifted left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 0) {\n return m;\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];\n } else {\n return [m[1] << (n - 32), 0];\n }\n }\n\n function _x64Xor(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // xored together as a 64bit int (as an array of two 32bit ints).\n //\n\n return [m[0] ^ n[0], m[1] ^ n[1]];\n }\n\n function _x64Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x64 mix of that block.\n // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the\n // only place where we need to right shift 64bit ints.)\n //\n\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xff51afd7, 0xed558ccd]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n\n return h;\n }\n\n // PUBLIC FUNCTIONS\n // ----------------\n\n library.x86.hash32 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 32 bit hash\n // using the x86 flavor of MurmurHash3, as an unsigned int.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 4;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n\n var k1 = 0;\n\n var c1 = 0xcc9e2d51;\n var c2 = 0x1b873593;\n\n for (var i = 0; i < blocks; i = i + 4) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n\n h1 ^= k1;\n h1 = _x86Rotl(h1, 13);\n h1 = _x86Multiply(h1, 5) + 0xe6546b64;\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h1 = _x86Fmix(h1);\n\n return h1 >>> 0;\n };\n\n library.x86.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x86 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n\n seed = seed || 0;\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n var h2 = seed;\n var h3 = seed;\n var h4 = seed;\n\n var k1 = 0;\n var k2 = 0;\n var k3 = 0;\n var k4 = 0;\n\n var c1 = 0x239b961b;\n var c2 = 0xab0e9789;\n var c3 = 0x38b34ae5;\n var c4 = 0xa1e38b93;\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n k2 = (bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24);\n k3 = (bytes[i + 8]) | (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24);\n k4 = (bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n\n h1 = _x86Rotl(h1, 19);\n h1 += h2;\n h1 = _x86Multiply(h1, 5) + 0x561ccd1b;\n\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n h2 = _x86Rotl(h2, 17);\n h2 += h3;\n h2 = _x86Multiply(h2, 5) + 0x0bcaa747;\n\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n h3 = _x86Rotl(h3, 15);\n h3 += h4;\n h3 = _x86Multiply(h3, 5) + 0x96cd1c35;\n\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n h4 = _x86Rotl(h4, 13);\n h4 += h1;\n h4 = _x86Multiply(h4, 5) + 0x32ac3b17;\n }\n\n k1 = 0;\n k2 = 0;\n k3 = 0;\n k4 = 0;\n\n switch (remainder) {\n case 15:\n k4 ^= bytes[i + 14] << 16;\n\n case 14:\n k4 ^= bytes[i + 13] << 8;\n\n case 13:\n k4 ^= bytes[i + 12];\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n case 12:\n k3 ^= bytes[i + 11] << 24;\n\n case 11:\n k3 ^= bytes[i + 10] << 16;\n\n case 10:\n k3 ^= bytes[i + 9] << 8;\n\n case 9:\n k3 ^= bytes[i + 8];\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n case 8:\n k2 ^= bytes[i + 7] << 24;\n\n case 7:\n k2 ^= bytes[i + 6] << 16;\n\n case 6:\n k2 ^= bytes[i + 5] << 8;\n\n case 5:\n k2 ^= bytes[i + 4];\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n case 4:\n k1 ^= bytes[i + 3] << 24;\n\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h2 ^= bytes.length;\n h3 ^= bytes.length;\n h4 ^= bytes.length;\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n h1 = _x86Fmix(h1);\n h2 = _x86Fmix(h2);\n h3 = _x86Fmix(h3);\n h4 = _x86Fmix(h4);\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n return (\"00000000\" + (h1 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h3 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h4 >>> 0).toString(16)).slice(-8);\n };\n\n library.x64.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x64 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = [0, seed];\n var h2 = [0, seed];\n\n var k1 = [0, 0];\n var k2 = [0, 0];\n\n var c1 = [0x87c37b91, 0x114253d5];\n var c2 = [0x4cf5ad43, 0x2745937f];\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = [(bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24), (bytes[i]) |\n (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)];\n k2 = [(bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24), (bytes[i + 8]) |\n (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24)];\n\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n\n h1 = _x64Rotl(h1, 27);\n h1 = _x64Add(h1, h2);\n h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 0x52dce729]);\n\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n h2 = _x64Rotl(h2, 31);\n h2 = _x64Add(h2, h1);\n h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);\n }\n\n k1 = [0, 0];\n k2 = [0, 0];\n\n switch (remainder) {\n case 15:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 14]], 48));\n\n case 14:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 13]], 40));\n\n case 13:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 12]], 32));\n\n case 12:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 11]], 24));\n\n case 11:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 10]], 16));\n\n case 10:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 9]], 8));\n\n case 9:\n k2 = _x64Xor(k2, [0, bytes[i + 8]]);\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n case 8:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 7]], 56));\n\n case 7:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 6]], 48));\n\n case 6:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 5]], 40));\n\n case 5:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 4]], 32));\n\n case 4:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 3]], 24));\n\n case 3:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 2]], 16));\n\n case 2:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 1]], 8));\n\n case 1:\n k1 = _x64Xor(k1, [0, bytes[i]]);\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n }\n\n h1 = _x64Xor(h1, [0, bytes.length]);\n h2 = _x64Xor(h2, [0, bytes.length]);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n h1 = _x64Fmix(h1);\n h2 = _x64Fmix(h2);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n return (\"00000000\" + (h1[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h1[1] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[1] >>> 0).toString(16)).slice(-8);\n };\n\n // INITIALIZATION\n // --------------\n\n // Export murmurHash3 for CommonJS, either as an AMD module or just as part\n // of the global object.\n if (typeof exports !== 'undefined') {\n\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = library;\n }\n\n exports.murmurHash3 = library;\n\n } else if (typeof define === 'function' && define.amd) {\n\n define([], function () {\n return library;\n });\n } else {\n\n // Use murmurHash3.noConflict to restore `murmurHash3` back to its\n // original value. Returns a reference to the library object, to allow\n // it to be used under a different name.\n library._murmurHash3 = root.murmurHash3;\n\n library.noConflict = function () {\n root.murmurHash3 = library._murmurHash3;\n library._murmurHash3 = undefined;\n library.noConflict = undefined;\n\n return library;\n };\n\n root.murmurHash3 = library;\n }\n})(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n var Netmask, atob, chr, chr0, chrA, chra, ip2long, long2ip;\n\n long2ip = function(long) {\n var a, b, c, d;\n a = (long & (0xff << 24)) >>> 24;\n b = (long & (0xff << 16)) >>> 16;\n c = (long & (0xff << 8)) >>> 8;\n d = long & 0xff;\n return [a, b, c, d].join('.');\n };\n\n ip2long = function(ip) {\n var b, c, i, j, n, ref;\n b = [];\n for (i = j = 0; j <= 3; i = ++j) {\n if (ip.length === 0) {\n break;\n }\n if (i > 0) {\n if (ip[0] !== '.') {\n throw new Error('Invalid IP');\n }\n ip = ip.substring(1);\n }\n ref = atob(ip), n = ref[0], c = ref[1];\n ip = ip.substring(c);\n b.push(n);\n }\n if (ip.length !== 0) {\n throw new Error('Invalid IP');\n }\n switch (b.length) {\n case 1:\n if (b[0] > 0xFFFFFFFF) {\n throw new Error('Invalid IP');\n }\n return b[0] >>> 0;\n case 2:\n if (b[0] > 0xFF || b[1] > 0xFFFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1]) >>> 0;\n case 3:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;\n case 4:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;\n default:\n throw new Error('Invalid IP');\n }\n };\n\n chr = function(b) {\n return b.charCodeAt(0);\n };\n\n chr0 = chr('0');\n\n chra = chr('a');\n\n chrA = chr('A');\n\n atob = function(s) {\n var base, dmax, i, n, start;\n n = 0;\n base = 10;\n dmax = '9';\n i = 0;\n if (s.length > 1 && s[i] === '0') {\n if (s[i + 1] === 'x' || s[i + 1] === 'X') {\n i += 2;\n base = 16;\n } else if ('0' <= s[i + 1] && s[i + 1] <= '9') {\n i++;\n base = 8;\n dmax = '7';\n }\n }\n start = i;\n while (i < s.length) {\n if ('0' <= s[i] && s[i] <= dmax) {\n n = (n * base + (chr(s[i]) - chr0)) >>> 0;\n } else if (base === 16) {\n if ('a' <= s[i] && s[i] <= 'f') {\n n = (n * base + (10 + chr(s[i]) - chra)) >>> 0;\n } else if ('A' <= s[i] && s[i] <= 'F') {\n n = (n * base + (10 + chr(s[i]) - chrA)) >>> 0;\n } else {\n break;\n }\n } else {\n break;\n }\n if (n > 0xFFFFFFFF) {\n throw new Error('too large');\n }\n i++;\n }\n if (i === start) {\n throw new Error('empty octet');\n }\n return [n, i];\n };\n\n Netmask = (function() {\n function Netmask(net, mask) {\n var error, i, j, ref;\n if (typeof net !== 'string') {\n throw new Error(\"Missing `net' parameter\");\n }\n if (!mask) {\n ref = net.split('/', 2), net = ref[0], mask = ref[1];\n }\n if (!mask) {\n mask = 32;\n }\n if (typeof mask === 'string' && mask.indexOf('.') > -1) {\n try {\n this.maskLong = ip2long(mask);\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid mask: \" + mask);\n }\n for (i = j = 32; j >= 0; i = --j) {\n if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) {\n this.bitmask = i;\n break;\n }\n }\n } else if (mask || mask === 0) {\n this.bitmask = parseInt(mask, 10);\n this.maskLong = 0;\n if (this.bitmask > 0) {\n this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0;\n }\n } else {\n throw new Error(\"Invalid mask: empty\");\n }\n try {\n this.netLong = (ip2long(net) & this.maskLong) >>> 0;\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid net address: \" + net);\n }\n if (!(this.bitmask <= 32)) {\n throw new Error(\"Invalid mask for ip4: \" + mask);\n }\n this.size = Math.pow(2, 32 - this.bitmask);\n this.base = long2ip(this.netLong);\n this.mask = long2ip(this.maskLong);\n this.hostmask = long2ip(~this.maskLong);\n this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;\n this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);\n this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;\n }\n\n Netmask.prototype.contains = function(ip) {\n if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) {\n ip = new Netmask(ip);\n }\n if (ip instanceof Netmask) {\n return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);\n } else {\n return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;\n }\n };\n\n Netmask.prototype.next = function(count) {\n if (count == null) {\n count = 1;\n }\n return new Netmask(long2ip(this.netLong + (this.size * count)), this.mask);\n };\n\n Netmask.prototype.forEach = function(fn) {\n var index, lastLong, long;\n long = ip2long(this.first);\n lastLong = ip2long(this.last);\n index = 0;\n while (long <= lastLong) {\n fn(long2ip(long), long, index);\n index++;\n long++;\n }\n };\n\n Netmask.prototype.toString = function() {\n return this.base + \"/\" + this.bitmask;\n };\n\n return Netmask;\n\n })();\n\n exports.ip2long = ip2long;\n\n exports.long2ip = long2ip;\n\n exports.Netmask = Netmask;\n\n}).call(this);\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @throws Will throw an error for various malformed input conditions.\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n remaining -= length;\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n try {\n rval += forge.util.decodeUtf8(obj.value);\n } catch(e) {\n if(e.message === 'URI malformed') {\n rval +=\n '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';\n } else {\n throw e;\n }\n }\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [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];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n// Deprecated equivalent of sha1WithRSAEncryption\n_IN('1.3.14.3.2.29', 'sha1WithRSASignature');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('2.16.840.1.101.3.4.2.4', 'sha224');\n_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');\n_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');\n_IN('1.2.840.113549.2.2', 'md2');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.4', 'surname');\n_IN('2.5.4.5', 'serialNumber');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.12', 'title');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('2.5.4.42', 'givenName');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n // accept \"NEW CERTIFICATE REQUEST\" as \"CERTIFICATE REQUEST\"\n // https://datatracker.ietf.org/doc/html/rfc7468#section-7\n var type = match[1];\n if(type === 'NEW CERTIFICATE REQUEST') {\n type = 'CERTIFICATE REQUEST';\n }\n\n var msg = {\n type: type,\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,\n 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,\n 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,\n 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,\n 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,\n 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,\n 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,\n 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n // captured only to check existence for md2 and md5\n capture: 'parameters',\n optional: true,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme, options) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // see PKCS1-v1-5DigestAlgorithms in RFC 8017\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha224 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512 ||\n oid === forge.oids['sha512-224'] ||\n oid === forge.oids['sha512-256'])) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n // special check for md2 and md5 that NULL parameters exist\n if(oid === forge.oids.md2 || oid === forge.oids.md5) {\n if(!('parameters' in capture)) {\n throw new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value. ' +\n 'Missing algorithm identifer NULL parameters.');\n }\n }\n\n // compare the given digest to the decrypted one\n return digest === capture.digest;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","// full library entry point.\r\n\r\n\"use strict\";\r\nmodule.exports = require(\"./src/index\");\r\n","\"use strict\";\r\nmodule.exports = common;\r\n\r\nvar commonRe = /\\/|\\./;\r\n\r\n/**\r\n * Provides common type definitions.\r\n * Can also be used to provide additional google types or your own custom types.\r\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\r\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\r\n * @returns {undefined}\r\n * @property {INamespace} google/protobuf/any.proto Any\r\n * @property {INamespace} google/protobuf/duration.proto Duration\r\n * @property {INamespace} google/protobuf/empty.proto Empty\r\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\r\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\r\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\r\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\r\n * @example\r\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\r\n * protobuf.common(\"descriptor\", descriptorJson);\r\n *\r\n * // manually provides a custom definition (uses my.foo namespace)\r\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\r\n */\r\nfunction common(name, json) {\r\n if (!commonRe.test(name)) {\r\n name = \"google/protobuf/\" + name + \".proto\";\r\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\r\n }\r\n common[name] = json;\r\n}\r\n\r\n// Not provided because of limited use (feel free to discuss or to provide yourself):\r\n//\r\n// google/protobuf/descriptor.proto\r\n// google/protobuf/source_context.proto\r\n// google/protobuf/type.proto\r\n//\r\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\r\n// the repository or package within the google/protobuf directory.\r\n\r\ncommon(\"any\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.Any message.\r\n * @interface IAny\r\n * @type {Object}\r\n * @property {string} [typeUrl]\r\n * @property {Uint8Array} [bytes]\r\n * @memberof common\r\n */\r\n Any: {\r\n fields: {\r\n type_url: {\r\n type: \"string\",\r\n id: 1\r\n },\r\n value: {\r\n type: \"bytes\",\r\n id: 2\r\n }\r\n }\r\n }\r\n});\r\n\r\nvar timeType;\r\n\r\ncommon(\"duration\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.Duration message.\r\n * @interface IDuration\r\n * @type {Object}\r\n * @property {number|Long} [seconds]\r\n * @property {number} [nanos]\r\n * @memberof common\r\n */\r\n Duration: timeType = {\r\n fields: {\r\n seconds: {\r\n type: \"int64\",\r\n id: 1\r\n },\r\n nanos: {\r\n type: \"int32\",\r\n id: 2\r\n }\r\n }\r\n }\r\n});\r\n\r\ncommon(\"timestamp\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.Timestamp message.\r\n * @interface ITimestamp\r\n * @type {Object}\r\n * @property {number|Long} [seconds]\r\n * @property {number} [nanos]\r\n * @memberof common\r\n */\r\n Timestamp: timeType\r\n});\r\n\r\ncommon(\"empty\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.Empty message.\r\n * @interface IEmpty\r\n * @memberof common\r\n */\r\n Empty: {\r\n fields: {}\r\n }\r\n});\r\n\r\ncommon(\"struct\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.Struct message.\r\n * @interface IStruct\r\n * @type {Object}\r\n * @property {Object.} [fields]\r\n * @memberof common\r\n */\r\n Struct: {\r\n fields: {\r\n fields: {\r\n keyType: \"string\",\r\n type: \"Value\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.Value message.\r\n * @interface IValue\r\n * @type {Object}\r\n * @property {string} [kind]\r\n * @property {0} [nullValue]\r\n * @property {number} [numberValue]\r\n * @property {string} [stringValue]\r\n * @property {boolean} [boolValue]\r\n * @property {IStruct} [structValue]\r\n * @property {IListValue} [listValue]\r\n * @memberof common\r\n */\r\n Value: {\r\n oneofs: {\r\n kind: {\r\n oneof: [\r\n \"nullValue\",\r\n \"numberValue\",\r\n \"stringValue\",\r\n \"boolValue\",\r\n \"structValue\",\r\n \"listValue\"\r\n ]\r\n }\r\n },\r\n fields: {\r\n nullValue: {\r\n type: \"NullValue\",\r\n id: 1\r\n },\r\n numberValue: {\r\n type: \"double\",\r\n id: 2\r\n },\r\n stringValue: {\r\n type: \"string\",\r\n id: 3\r\n },\r\n boolValue: {\r\n type: \"bool\",\r\n id: 4\r\n },\r\n structValue: {\r\n type: \"Struct\",\r\n id: 5\r\n },\r\n listValue: {\r\n type: \"ListValue\",\r\n id: 6\r\n }\r\n }\r\n },\r\n\r\n NullValue: {\r\n values: {\r\n NULL_VALUE: 0\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.ListValue message.\r\n * @interface IListValue\r\n * @type {Object}\r\n * @property {Array.} [values]\r\n * @memberof common\r\n */\r\n ListValue: {\r\n fields: {\r\n values: {\r\n rule: \"repeated\",\r\n type: \"Value\",\r\n id: 1\r\n }\r\n }\r\n }\r\n});\r\n\r\ncommon(\"wrappers\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.DoubleValue message.\r\n * @interface IDoubleValue\r\n * @type {Object}\r\n * @property {number} [value]\r\n * @memberof common\r\n */\r\n DoubleValue: {\r\n fields: {\r\n value: {\r\n type: \"double\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.FloatValue message.\r\n * @interface IFloatValue\r\n * @type {Object}\r\n * @property {number} [value]\r\n * @memberof common\r\n */\r\n FloatValue: {\r\n fields: {\r\n value: {\r\n type: \"float\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.Int64Value message.\r\n * @interface IInt64Value\r\n * @type {Object}\r\n * @property {number|Long} [value]\r\n * @memberof common\r\n */\r\n Int64Value: {\r\n fields: {\r\n value: {\r\n type: \"int64\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.UInt64Value message.\r\n * @interface IUInt64Value\r\n * @type {Object}\r\n * @property {number|Long} [value]\r\n * @memberof common\r\n */\r\n UInt64Value: {\r\n fields: {\r\n value: {\r\n type: \"uint64\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.Int32Value message.\r\n * @interface IInt32Value\r\n * @type {Object}\r\n * @property {number} [value]\r\n * @memberof common\r\n */\r\n Int32Value: {\r\n fields: {\r\n value: {\r\n type: \"int32\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.UInt32Value message.\r\n * @interface IUInt32Value\r\n * @type {Object}\r\n * @property {number} [value]\r\n * @memberof common\r\n */\r\n UInt32Value: {\r\n fields: {\r\n value: {\r\n type: \"uint32\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.BoolValue message.\r\n * @interface IBoolValue\r\n * @type {Object}\r\n * @property {boolean} [value]\r\n * @memberof common\r\n */\r\n BoolValue: {\r\n fields: {\r\n value: {\r\n type: \"bool\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.StringValue message.\r\n * @interface IStringValue\r\n * @type {Object}\r\n * @property {string} [value]\r\n * @memberof common\r\n */\r\n StringValue: {\r\n fields: {\r\n value: {\r\n type: \"string\",\r\n id: 1\r\n }\r\n }\r\n },\r\n\r\n /**\r\n * Properties of a google.protobuf.BytesValue message.\r\n * @interface IBytesValue\r\n * @type {Object}\r\n * @property {Uint8Array} [value]\r\n * @memberof common\r\n */\r\n BytesValue: {\r\n fields: {\r\n value: {\r\n type: \"bytes\",\r\n id: 1\r\n }\r\n }\r\n }\r\n});\r\n\r\ncommon(\"field_mask\", {\r\n\r\n /**\r\n * Properties of a google.protobuf.FieldMask message.\r\n * @interface IDoubleValue\r\n * @type {Object}\r\n * @property {number} [value]\r\n * @memberof common\r\n */\r\n FieldMask: {\r\n fields: {\r\n paths: {\r\n rule: \"repeated\",\r\n type: \"string\",\r\n id: 1\r\n }\r\n }\r\n }\r\n});\r\n\r\n/**\r\n * Gets the root definition of the specified common proto file.\r\n *\r\n * Bundled definitions are:\r\n * - google/protobuf/any.proto\r\n * - google/protobuf/duration.proto\r\n * - google/protobuf/empty.proto\r\n * - google/protobuf/field_mask.proto\r\n * - google/protobuf/struct.proto\r\n * - google/protobuf/timestamp.proto\r\n * - google/protobuf/wrappers.proto\r\n *\r\n * @param {string} file Proto file name\r\n * @returns {INamespace|null} Root definition or `null` if not defined\r\n */\r\ncommon.get = function get(file) {\r\n return common[file] || null;\r\n};\r\n","\"use strict\";\r\n/**\r\n * Runtime message from/to plain object converters.\r\n * @namespace\r\n */\r\nvar converter = exports;\r\n\r\nvar Enum = require(\"./enum\"),\r\n util = require(\"./util\");\r\n\r\n/**\r\n * Generates a partial value fromObject conveter.\r\n * @param {Codegen} gen Codegen instance\r\n * @param {Field} field Reflected field\r\n * @param {number} fieldIndex Field index\r\n * @param {string} prop Property reference\r\n * @returns {Codegen} Codegen instance\r\n * @ignore\r\n */\r\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\r\n var defaultAlreadyEmitted = false;\r\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n if (field.resolvedType) {\r\n if (field.resolvedType instanceof Enum) { gen\r\n (\"switch(d%s){\", prop);\r\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\r\n // enum unknown values passthrough\r\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\r\n (\"default:\")\r\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\r\n if (!field.repeated) gen // fallback to default value only for\r\n // arrays, to avoid leaving holes.\r\n (\"break\"); // for non-repeated fields, just ignore\r\n defaultAlreadyEmitted = true;\r\n }\r\n gen\r\n (\"case%j:\", keys[i])\r\n (\"case %i:\", values[keys[i]])\r\n (\"m%s=%j\", prop, values[keys[i]])\r\n (\"break\");\r\n } gen\r\n (\"}\");\r\n } else gen\r\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\r\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\r\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\r\n } else {\r\n var isUnsigned = false;\r\n switch (field.type) {\r\n case \"double\":\r\n case \"float\": gen\r\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\r\n break;\r\n case \"uint32\":\r\n case \"fixed32\": gen\r\n (\"m%s=d%s>>>0\", prop, prop);\r\n break;\r\n case \"int32\":\r\n case \"sint32\":\r\n case \"sfixed32\": gen\r\n (\"m%s=d%s|0\", prop, prop);\r\n break;\r\n case \"uint64\":\r\n isUnsigned = true;\r\n // eslint-disable-next-line no-fallthrough\r\n case \"int64\":\r\n case \"sint64\":\r\n case \"fixed64\":\r\n case \"sfixed64\": gen\r\n (\"if(util.Long)\")\r\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\r\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\r\n (\"m%s=parseInt(d%s,10)\", prop, prop)\r\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\r\n (\"m%s=d%s\", prop, prop)\r\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\r\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\r\n break;\r\n case \"bytes\": gen\r\n (\"if(typeof d%s===\\\"string\\\")\", prop)\r\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\r\n (\"else if(d%s.length >= 0)\", prop)\r\n (\"m%s=d%s\", prop, prop);\r\n break;\r\n case \"string\": gen\r\n (\"m%s=String(d%s)\", prop, prop);\r\n break;\r\n case \"bool\": gen\r\n (\"m%s=Boolean(d%s)\", prop, prop);\r\n break;\r\n /* default: gen\r\n (\"m%s=d%s\", prop, prop);\r\n break; */\r\n }\r\n }\r\n return gen;\r\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n}\r\n\r\n/**\r\n * Generates a plain object to runtime message converter specific to the specified message type.\r\n * @param {Type} mtype Message type\r\n * @returns {Codegen} Codegen instance\r\n */\r\nconverter.fromObject = function fromObject(mtype) {\r\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n var fields = mtype.fieldsArray;\r\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\r\n (\"if(d instanceof this.ctor)\")\r\n (\"return d\");\r\n if (!fields.length) return gen\r\n (\"return new this.ctor\");\r\n gen\r\n (\"var m=new this.ctor\");\r\n for (var i = 0; i < fields.length; ++i) {\r\n var field = fields[i].resolve(),\r\n prop = util.safeProp(field.name);\r\n\r\n // Map fields\r\n if (field.map) { gen\r\n (\"if(d%s){\", prop)\r\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\r\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\r\n (\"m%s={}\", prop)\r\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\r\n break;\r\n case \"bytes\": gen\r\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\r\n break;\r\n default: gen\r\n (\"d%s=m%s\", prop, prop);\r\n break;\r\n }\r\n }\r\n return gen;\r\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n}\r\n\r\n/**\r\n * Generates a runtime message to plain object converter specific to the specified message type.\r\n * @param {Type} mtype Message type\r\n * @returns {Codegen} Codegen instance\r\n */\r\nconverter.toObject = function toObject(mtype) {\r\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\r\n if (!fields.length)\r\n return util.codegen()(\"return {}\");\r\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\r\n (\"if(!o)\")\r\n (\"o={}\")\r\n (\"var d={}\");\r\n\r\n var repeatedFields = [],\r\n mapFields = [],\r\n normalFields = [],\r\n i = 0;\r\n for (; i < fields.length; ++i)\r\n if (!fields[i].partOf)\r\n ( fields[i].resolve().repeated ? repeatedFields\r\n : fields[i].map ? mapFields\r\n : normalFields).push(fields[i]);\r\n\r\n if (repeatedFields.length) { gen\r\n (\"if(o.arrays||o.defaults){\");\r\n for (i = 0; i < repeatedFields.length; ++i) gen\r\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\r\n gen\r\n (\"}\");\r\n }\r\n\r\n if (mapFields.length) { gen\r\n (\"if(o.objects||o.defaults){\");\r\n for (i = 0; i < mapFields.length; ++i) gen\r\n (\"d%s={}\", util.safeProp(mapFields[i].name));\r\n gen\r\n (\"}\");\r\n }\r\n\r\n if (normalFields.length) { gen\r\n (\"if(o.defaults){\");\r\n for (i = 0; i < normalFields.length; ++i) {\r\n var field = normalFields[i],\r\n prop = util.safeProp(field.name);\r\n if (field.resolvedType instanceof Enum) gen\r\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\r\n else if (field.long) gen\r\n (\"if(util.Long){\")\r\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\r\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\r\n (\"}else\")\r\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\r\n else if (field.bytes) {\r\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\r\n gen\r\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\r\n (\"else{\")\r\n (\"d%s=%s\", prop, arrayDefault)\r\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\r\n (\"}\");\r\n } else gen\r\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\r\n } gen\r\n (\"}\");\r\n }\r\n var hasKs2 = false;\r\n for (i = 0; i < fields.length; ++i) {\r\n var field = fields[i],\r\n index = mtype._fieldsArray.indexOf(field),\r\n prop = util.safeProp(field.name);\r\n if (field.map) {\r\n if (!hasKs2) { hasKs2 = true; gen\r\n (\"var ks2\");\r\n } gen\r\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\r\n (\"d%s={}\", prop)\r\n (\"for(var j=0;j>>3){\");\r\n\r\n var i = 0;\r\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\r\n var field = mtype._fieldsArray[i].resolve(),\r\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\r\n ref = \"m\" + util.safeProp(field.name); gen\r\n (\"case %i: {\", field.id);\r\n\r\n // Map fields\r\n if (field.map) { gen\r\n (\"if(%s===util.emptyObject)\", ref)\r\n (\"%s={}\", ref)\r\n (\"var c2 = r.uint32()+r.pos\");\r\n\r\n if (types.defaults[field.keyType] !== undefined) gen\r\n (\"k=%j\", types.defaults[field.keyType]);\r\n else gen\r\n (\"k=null\");\r\n\r\n if (types.defaults[type] !== undefined) gen\r\n (\"value=%j\", types.defaults[type]);\r\n else gen\r\n (\"value=null\");\r\n\r\n gen\r\n (\"while(r.pos>>3){\")\r\n (\"case 1: k=r.%s(); break\", field.keyType)\r\n (\"case 2:\");\r\n\r\n if (types.basic[type] === undefined) gen\r\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\r\n else gen\r\n (\"value=r.%s()\", type);\r\n\r\n gen\r\n (\"break\")\r\n (\"default:\")\r\n (\"r.skipType(tag2&7)\")\r\n (\"break\")\r\n (\"}\")\r\n (\"}\");\r\n\r\n if (types.long[field.keyType] !== undefined) gen\r\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\r\n else gen\r\n (\"%s[k]=value\", ref);\r\n\r\n // Repeated fields\r\n } else if (field.repeated) { gen\r\n\r\n (\"if(!(%s&&%s.length))\", ref, ref)\r\n (\"%s=[]\", ref);\r\n\r\n // Packable (always check for forward and backward compatiblity)\r\n if (types.packed[type] !== undefined) gen\r\n (\"if((t&7)===2){\")\r\n (\"var c2=r.uint32()+r.pos\")\r\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\r\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\r\n}\r\n\r\n/**\r\n * Generates an encoder specific to the specified message type.\r\n * @param {Type} mtype Message type\r\n * @returns {Codegen} Codegen instance\r\n */\r\nfunction encoder(mtype) {\r\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\r\n (\"if(!w)\")\r\n (\"w=Writer.create()\");\r\n\r\n var i, ref;\r\n\r\n // \"when a message is serialized its known fields should be written sequentially by field number\"\r\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\r\n\r\n for (var i = 0; i < fields.length; ++i) {\r\n var field = fields[i].resolve(),\r\n index = mtype._fieldsArray.indexOf(field),\r\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\r\n wireType = types.basic[type];\r\n ref = \"m\" + util.safeProp(field.name);\r\n\r\n // Map fields\r\n if (field.map) {\r\n gen\r\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\r\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\r\n if (wireType === undefined) gen\r\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\r\n else gen\r\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\r\n gen\r\n (\"}\")\r\n (\"}\");\r\n\r\n // Repeated fields\r\n } else if (field.repeated) { gen\r\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\r\n\r\n // Packed repeated\r\n if (field.packed && types.packed[type] !== undefined) { gen\r\n\r\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\r\n (\"for(var i=0;i<%s.length;++i)\", ref)\r\n (\"w.%s(%s[i])\", type, ref)\r\n (\"w.ldelim()\");\r\n\r\n // Non-packed\r\n } else { gen\r\n\r\n (\"for(var i=0;i<%s.length;++i)\", ref);\r\n if (wireType === undefined)\r\n genTypePartial(gen, field, index, ref + \"[i]\");\r\n else gen\r\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\r\n\r\n } gen\r\n (\"}\");\r\n\r\n // Non-repeated\r\n } else {\r\n if (field.optional) gen\r\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\r\n\r\n if (wireType === undefined)\r\n genTypePartial(gen, field, index, ref);\r\n else gen\r\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\r\n\r\n }\r\n }\r\n\r\n return gen\r\n (\"return w\");\r\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r\n}\r\n","\"use strict\";\r\nmodule.exports = Enum;\r\n\r\n// extends ReflectionObject\r\nvar ReflectionObject = require(\"./object\");\r\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\r\n\r\nvar Namespace = require(\"./namespace\"),\r\n util = require(\"./util\");\r\n\r\n/**\r\n * Constructs a new enum instance.\r\n * @classdesc Reflected enum.\r\n * @extends ReflectionObject\r\n * @constructor\r\n * @param {string} name Unique name within its namespace\r\n * @param {Object.} [values] Enum values as an object, by name\r\n * @param {Object.} [options] Declared options\r\n * @param {string} [comment] The comment for this enum\r\n * @param {Object.} [comments] The value comments for this enum\r\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\r\n */\r\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\r\n ReflectionObject.call(this, name, options);\r\n\r\n if (values && typeof values !== \"object\")\r\n throw TypeError(\"values must be an object\");\r\n\r\n /**\r\n * Enum values by id.\r\n * @type {Object.}\r\n */\r\n this.valuesById = {};\r\n\r\n /**\r\n * Enum values by name.\r\n * @type {Object.}\r\n */\r\n this.values = Object.create(this.valuesById); // toJSON, marker\r\n\r\n /**\r\n * Enum comment text.\r\n * @type {string|null}\r\n */\r\n this.comment = comment;\r\n\r\n /**\r\n * Value comment texts, if any.\r\n * @type {Object.}\r\n */\r\n this.comments = comments || {};\r\n\r\n /**\r\n * Values options, if any\r\n * @type {Object>|undefined}\r\n */\r\n this.valuesOptions = valuesOptions;\r\n\r\n /**\r\n * Reserved ranges, if any.\r\n * @type {Array.}\r\n */\r\n this.reserved = undefined; // toJSON\r\n\r\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\r\n // compatible enum. This is used by pbts to write actual enum definitions that work for\r\n // static and reflection code alike instead of emitting generic object definitions.\r\n\r\n if (values)\r\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\r\n if (typeof values[keys[i]] === \"number\") // use forward entries only\r\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\r\n}\r\n\r\n/**\r\n * Enum descriptor.\r\n * @interface IEnum\r\n * @property {Object.} values Enum values\r\n * @property {Object.} [options] Enum options\r\n */\r\n\r\n/**\r\n * Constructs an enum from an enum descriptor.\r\n * @param {string} name Enum name\r\n * @param {IEnum} json Enum descriptor\r\n * @returns {Enum} Created enum\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nEnum.fromJSON = function fromJSON(name, json) {\r\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\r\n enm.reserved = json.reserved;\r\n return enm;\r\n};\r\n\r\n/**\r\n * Converts this enum to an enum descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IEnum} Enum descriptor\r\n */\r\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"options\" , this.options,\r\n \"valuesOptions\" , this.valuesOptions,\r\n \"values\" , this.values,\r\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\r\n \"comment\" , keepComments ? this.comment : undefined,\r\n \"comments\" , keepComments ? this.comments : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * Adds a value to this enum.\r\n * @param {string} name Value name\r\n * @param {number} id Value id\r\n * @param {string} [comment] Comment, if any\r\n * @param {Object.|undefined} [options] Options, if any\r\n * @returns {Enum} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If there is already a value with this name or id\r\n */\r\nEnum.prototype.add = function add(name, id, comment, options) {\r\n // utilized by the parser but not by .fromJSON\r\n\r\n if (!util.isString(name))\r\n throw TypeError(\"name must be a string\");\r\n\r\n if (!util.isInteger(id))\r\n throw TypeError(\"id must be an integer\");\r\n\r\n if (this.values[name] !== undefined)\r\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\r\n\r\n if (this.isReservedId(id))\r\n throw Error(\"id \" + id + \" is reserved in \" + this);\r\n\r\n if (this.isReservedName(name))\r\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\r\n\r\n if (this.valuesById[id] !== undefined) {\r\n if (!(this.options && this.options.allow_alias))\r\n throw Error(\"duplicate id \" + id + \" in \" + this);\r\n this.values[name] = id;\r\n } else\r\n this.valuesById[this.values[name] = id] = name;\r\n\r\n if (options) {\r\n if (this.valuesOptions === undefined)\r\n this.valuesOptions = {};\r\n this.valuesOptions[name] = options || null;\r\n }\r\n\r\n this.comments[name] = comment || null;\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes a value from this enum\r\n * @param {string} name Value name\r\n * @returns {Enum} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If `name` is not a name of this enum\r\n */\r\nEnum.prototype.remove = function remove(name) {\r\n\r\n if (!util.isString(name))\r\n throw TypeError(\"name must be a string\");\r\n\r\n var val = this.values[name];\r\n if (val == null)\r\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\r\n\r\n delete this.valuesById[val];\r\n delete this.values[name];\r\n delete this.comments[name];\r\n if (this.valuesOptions)\r\n delete this.valuesOptions[name];\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Tests if the specified id is reserved.\r\n * @param {number} id Id to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nEnum.prototype.isReservedId = function isReservedId(id) {\r\n return Namespace.isReservedId(this.reserved, id);\r\n};\r\n\r\n/**\r\n * Tests if the specified name is reserved.\r\n * @param {string} name Name to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nEnum.prototype.isReservedName = function isReservedName(name) {\r\n return Namespace.isReservedName(this.reserved, name);\r\n};\r\n","\"use strict\";\r\nmodule.exports = Field;\r\n\r\n// extends ReflectionObject\r\nvar ReflectionObject = require(\"./object\");\r\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\r\n\r\nvar Enum = require(\"./enum\"),\r\n types = require(\"./types\"),\r\n util = require(\"./util\");\r\n\r\nvar Type; // cyclic\r\n\r\nvar ruleRe = /^required|optional|repeated$/;\r\n\r\n/**\r\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\r\n * @name Field\r\n * @classdesc Reflected message field.\r\n * @extends FieldBase\r\n * @constructor\r\n * @param {string} name Unique name within its namespace\r\n * @param {number} id Unique id within its namespace\r\n * @param {string} type Value type\r\n * @param {string|Object.} [rule=\"optional\"] Field rule\r\n * @param {string|Object.} [extend] Extended type if different from parent\r\n * @param {Object.} [options] Declared options\r\n */\r\n\r\n/**\r\n * Constructs a field from a field descriptor.\r\n * @param {string} name Field name\r\n * @param {IField} json Field descriptor\r\n * @returns {Field} Created field\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nField.fromJSON = function fromJSON(name, json) {\r\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\r\n};\r\n\r\n/**\r\n * Not an actual constructor. Use {@link Field} instead.\r\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\r\n * @exports FieldBase\r\n * @extends ReflectionObject\r\n * @constructor\r\n * @param {string} name Unique name within its namespace\r\n * @param {number} id Unique id within its namespace\r\n * @param {string} type Value type\r\n * @param {string|Object.} [rule=\"optional\"] Field rule\r\n * @param {string|Object.} [extend] Extended type if different from parent\r\n * @param {Object.} [options] Declared options\r\n * @param {string} [comment] Comment associated with this field\r\n */\r\nfunction Field(name, id, type, rule, extend, options, comment) {\r\n\r\n if (util.isObject(rule)) {\r\n comment = extend;\r\n options = rule;\r\n rule = extend = undefined;\r\n } else if (util.isObject(extend)) {\r\n comment = options;\r\n options = extend;\r\n extend = undefined;\r\n }\r\n\r\n ReflectionObject.call(this, name, options);\r\n\r\n if (!util.isInteger(id) || id < 0)\r\n throw TypeError(\"id must be a non-negative integer\");\r\n\r\n if (!util.isString(type))\r\n throw TypeError(\"type must be a string\");\r\n\r\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\r\n throw TypeError(\"rule must be a string rule\");\r\n\r\n if (extend !== undefined && !util.isString(extend))\r\n throw TypeError(\"extend must be a string\");\r\n\r\n /**\r\n * Field rule, if any.\r\n * @type {string|undefined}\r\n */\r\n if (rule === \"proto3_optional\") {\r\n rule = \"optional\";\r\n }\r\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\r\n\r\n /**\r\n * Field type.\r\n * @type {string}\r\n */\r\n this.type = type; // toJSON\r\n\r\n /**\r\n * Unique field id.\r\n * @type {number}\r\n */\r\n this.id = id; // toJSON, marker\r\n\r\n /**\r\n * Extended type if different from parent.\r\n * @type {string|undefined}\r\n */\r\n this.extend = extend || undefined; // toJSON\r\n\r\n /**\r\n * Whether this field is required.\r\n * @type {boolean}\r\n */\r\n this.required = rule === \"required\";\r\n\r\n /**\r\n * Whether this field is optional.\r\n * @type {boolean}\r\n */\r\n this.optional = !this.required;\r\n\r\n /**\r\n * Whether this field is repeated.\r\n * @type {boolean}\r\n */\r\n this.repeated = rule === \"repeated\";\r\n\r\n /**\r\n * Whether this field is a map or not.\r\n * @type {boolean}\r\n */\r\n this.map = false;\r\n\r\n /**\r\n * Message this field belongs to.\r\n * @type {Type|null}\r\n */\r\n this.message = null;\r\n\r\n /**\r\n * OneOf this field belongs to, if any,\r\n * @type {OneOf|null}\r\n */\r\n this.partOf = null;\r\n\r\n /**\r\n * The field type's default value.\r\n * @type {*}\r\n */\r\n this.typeDefault = null;\r\n\r\n /**\r\n * The field's default value on prototypes.\r\n * @type {*}\r\n */\r\n this.defaultValue = null;\r\n\r\n /**\r\n * Whether this field's value should be treated as a long.\r\n * @type {boolean}\r\n */\r\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\r\n\r\n /**\r\n * Whether this field's value is a buffer.\r\n * @type {boolean}\r\n */\r\n this.bytes = type === \"bytes\";\r\n\r\n /**\r\n * Resolved type if not a basic type.\r\n * @type {Type|Enum|null}\r\n */\r\n this.resolvedType = null;\r\n\r\n /**\r\n * Sister-field within the extended type if a declaring extension field.\r\n * @type {Field|null}\r\n */\r\n this.extensionField = null;\r\n\r\n /**\r\n * Sister-field within the declaring namespace if an extended field.\r\n * @type {Field|null}\r\n */\r\n this.declaringField = null;\r\n\r\n /**\r\n * Internally remembers whether this field is packed.\r\n * @type {boolean|null}\r\n * @private\r\n */\r\n this._packed = null;\r\n\r\n /**\r\n * Comment for this field.\r\n * @type {string|null}\r\n */\r\n this.comment = comment;\r\n}\r\n\r\n/**\r\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\r\n * @name Field#packed\r\n * @type {boolean}\r\n * @readonly\r\n */\r\nObject.defineProperty(Field.prototype, \"packed\", {\r\n get: function() {\r\n // defaults to packed=true if not explicity set to false\r\n if (this._packed === null)\r\n this._packed = this.getOption(\"packed\") !== false;\r\n return this._packed;\r\n }\r\n});\r\n\r\n/**\r\n * @override\r\n */\r\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\r\n if (name === \"packed\") // clear cached before setting\r\n this._packed = null;\r\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\r\n};\r\n\r\n/**\r\n * Field descriptor.\r\n * @interface IField\r\n * @property {string} [rule=\"optional\"] Field rule\r\n * @property {string} type Field type\r\n * @property {number} id Field id\r\n * @property {Object.} [options] Field options\r\n */\r\n\r\n/**\r\n * Extension field descriptor.\r\n * @interface IExtensionField\r\n * @extends IField\r\n * @property {string} extend Extended type\r\n */\r\n\r\n/**\r\n * Converts this field to a field descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IField} Field descriptor\r\n */\r\nField.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\r\n \"type\" , this.type,\r\n \"id\" , this.id,\r\n \"extend\" , this.extend,\r\n \"options\" , this.options,\r\n \"comment\" , keepComments ? this.comment : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * Resolves this field's type references.\r\n * @returns {Field} `this`\r\n * @throws {Error} If any reference cannot be resolved\r\n */\r\nField.prototype.resolve = function resolve() {\r\n\r\n if (this.resolved)\r\n return this;\r\n\r\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\r\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\r\n if (this.resolvedType instanceof Type)\r\n this.typeDefault = null;\r\n else // instanceof Enum\r\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\r\n } else if (this.options && this.options.proto3_optional) {\r\n // proto3 scalar value marked optional; should default to null\r\n this.typeDefault = null;\r\n }\r\n\r\n // use explicitly set default value if present\r\n if (this.options && this.options[\"default\"] != null) {\r\n this.typeDefault = this.options[\"default\"];\r\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\r\n this.typeDefault = this.resolvedType.values[this.typeDefault];\r\n }\r\n\r\n // remove unnecessary options\r\n if (this.options) {\r\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\r\n delete this.options.packed;\r\n if (!Object.keys(this.options).length)\r\n this.options = undefined;\r\n }\r\n\r\n // convert to internal data type if necesssary\r\n if (this.long) {\r\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\r\n\r\n /* istanbul ignore else */\r\n if (Object.freeze)\r\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\r\n\r\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\r\n var buf;\r\n if (util.base64.test(this.typeDefault))\r\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\r\n else\r\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\r\n this.typeDefault = buf;\r\n }\r\n\r\n // take special care of maps and repeated fields\r\n if (this.map)\r\n this.defaultValue = util.emptyObject;\r\n else if (this.repeated)\r\n this.defaultValue = util.emptyArray;\r\n else\r\n this.defaultValue = this.typeDefault;\r\n\r\n // ensure proper value on prototype\r\n if (this.parent instanceof Type)\r\n this.parent.ctor.prototype[this.name] = this.defaultValue;\r\n\r\n return ReflectionObject.prototype.resolve.call(this);\r\n};\r\n\r\n/**\r\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\r\n * @typedef FieldDecorator\r\n * @type {function}\r\n * @param {Object} prototype Target prototype\r\n * @param {string} fieldName Field name\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Field decorator (TypeScript).\r\n * @name Field.d\r\n * @function\r\n * @param {number} fieldId Field id\r\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\r\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\r\n * @param {T} [defaultValue] Default value\r\n * @returns {FieldDecorator} Decorator function\r\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\r\n */\r\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\r\n\r\n // submessage: decorate the submessage and use its name as the type\r\n if (typeof fieldType === \"function\")\r\n fieldType = util.decorateType(fieldType).name;\r\n\r\n // enum reference: create a reflected copy of the enum and keep reuseing it\r\n else if (fieldType && typeof fieldType === \"object\")\r\n fieldType = util.decorateEnum(fieldType).name;\r\n\r\n return function fieldDecorator(prototype, fieldName) {\r\n util.decorateType(prototype.constructor)\r\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\r\n };\r\n};\r\n\r\n/**\r\n * Field decorator (TypeScript).\r\n * @name Field.d\r\n * @function\r\n * @param {number} fieldId Field id\r\n * @param {Constructor|string} fieldType Field type\r\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\r\n * @returns {FieldDecorator} Decorator function\r\n * @template T extends Message\r\n * @variation 2\r\n */\r\n// like Field.d but without a default value\r\n\r\n// Sets up cyclic dependencies (called in index-light)\r\nField._configure = function configure(Type_) {\r\n Type = Type_;\r\n};\r\n","\"use strict\";\r\nvar protobuf = module.exports = require(\"./index-minimal\");\r\n\r\nprotobuf.build = \"light\";\r\n\r\n/**\r\n * A node-style callback as used by {@link load} and {@link Root#load}.\r\n * @typedef LoadCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any, otherwise `null`\r\n * @param {Root} [root] Root, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\r\n * @param {string|string[]} filename One or multiple files to load\r\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\r\n * @param {LoadCallback} callback Callback function\r\n * @returns {undefined}\r\n * @see {@link Root#load}\r\n */\r\nfunction load(filename, root, callback) {\r\n if (typeof root === \"function\") {\r\n callback = root;\r\n root = new protobuf.Root();\r\n } else if (!root)\r\n root = new protobuf.Root();\r\n return root.load(filename, callback);\r\n}\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\r\n * @name load\r\n * @function\r\n * @param {string|string[]} filename One or multiple files to load\r\n * @param {LoadCallback} callback Callback function\r\n * @returns {undefined}\r\n * @see {@link Root#load}\r\n * @variation 2\r\n */\r\n// function load(filename:string, callback:LoadCallback):undefined\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\r\n * @name load\r\n * @function\r\n * @param {string|string[]} filename One or multiple files to load\r\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\r\n * @returns {Promise} Promise\r\n * @see {@link Root#load}\r\n * @variation 3\r\n */\r\n// function load(filename:string, [root:Root]):Promise\r\n\r\nprotobuf.load = load;\r\n\r\n/**\r\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\r\n * @param {string|string[]} filename One or multiple files to load\r\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\r\n * @returns {Root} Root namespace\r\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\r\n * @see {@link Root#loadSync}\r\n */\r\nfunction loadSync(filename, root) {\r\n if (!root)\r\n root = new protobuf.Root();\r\n return root.loadSync(filename);\r\n}\r\n\r\nprotobuf.loadSync = loadSync;\r\n\r\n// Serialization\r\nprotobuf.encoder = require(\"./encoder\");\r\nprotobuf.decoder = require(\"./decoder\");\r\nprotobuf.verifier = require(\"./verifier\");\r\nprotobuf.converter = require(\"./converter\");\r\n\r\n// Reflection\r\nprotobuf.ReflectionObject = require(\"./object\");\r\nprotobuf.Namespace = require(\"./namespace\");\r\nprotobuf.Root = require(\"./root\");\r\nprotobuf.Enum = require(\"./enum\");\r\nprotobuf.Type = require(\"./type\");\r\nprotobuf.Field = require(\"./field\");\r\nprotobuf.OneOf = require(\"./oneof\");\r\nprotobuf.MapField = require(\"./mapfield\");\r\nprotobuf.Service = require(\"./service\");\r\nprotobuf.Method = require(\"./method\");\r\n\r\n// Runtime\r\nprotobuf.Message = require(\"./message\");\r\nprotobuf.wrappers = require(\"./wrappers\");\r\n\r\n// Utility\r\nprotobuf.types = require(\"./types\");\r\nprotobuf.util = require(\"./util\");\r\n\r\n// Set up possibly cyclic reflection dependencies\r\nprotobuf.ReflectionObject._configure(protobuf.Root);\r\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\r\nprotobuf.Root._configure(protobuf.Type);\r\nprotobuf.Field._configure(protobuf.Type);\r\n","\"use strict\";\r\nvar protobuf = exports;\r\n\r\n/**\r\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\r\n * @name build\r\n * @type {string}\r\n * @const\r\n */\r\nprotobuf.build = \"minimal\";\r\n\r\n// Serialization\r\nprotobuf.Writer = require(\"./writer\");\r\nprotobuf.BufferWriter = require(\"./writer_buffer\");\r\nprotobuf.Reader = require(\"./reader\");\r\nprotobuf.BufferReader = require(\"./reader_buffer\");\r\n\r\n// Utility\r\nprotobuf.util = require(\"./util/minimal\");\r\nprotobuf.rpc = require(\"./rpc\");\r\nprotobuf.roots = require(\"./roots\");\r\nprotobuf.configure = configure;\r\n\r\n/* istanbul ignore next */\r\n/**\r\n * Reconfigures the library according to the environment.\r\n * @returns {undefined}\r\n */\r\nfunction configure() {\r\n protobuf.util._configure();\r\n protobuf.Writer._configure(protobuf.BufferWriter);\r\n protobuf.Reader._configure(protobuf.BufferReader);\r\n}\r\n\r\n// Set up buffer utility according to the environment\r\nconfigure();\r\n","\"use strict\";\r\nvar protobuf = module.exports = require(\"./index-light\");\r\n\r\nprotobuf.build = \"full\";\r\n\r\n// Parser\r\nprotobuf.tokenize = require(\"./tokenize\");\r\nprotobuf.parse = require(\"./parse\");\r\nprotobuf.common = require(\"./common\");\r\n\r\n// Configure parser\r\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\r\n","\"use strict\";\r\nmodule.exports = MapField;\r\n\r\n// extends Field\r\nvar Field = require(\"./field\");\r\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\r\n\r\nvar types = require(\"./types\"),\r\n util = require(\"./util\");\r\n\r\n/**\r\n * Constructs a new map field instance.\r\n * @classdesc Reflected map field.\r\n * @extends FieldBase\r\n * @constructor\r\n * @param {string} name Unique name within its namespace\r\n * @param {number} id Unique id within its namespace\r\n * @param {string} keyType Key type\r\n * @param {string} type Value type\r\n * @param {Object.} [options] Declared options\r\n * @param {string} [comment] Comment associated with this field\r\n */\r\nfunction MapField(name, id, keyType, type, options, comment) {\r\n Field.call(this, name, id, type, undefined, undefined, options, comment);\r\n\r\n /* istanbul ignore if */\r\n if (!util.isString(keyType))\r\n throw TypeError(\"keyType must be a string\");\r\n\r\n /**\r\n * Key type.\r\n * @type {string}\r\n */\r\n this.keyType = keyType; // toJSON, marker\r\n\r\n /**\r\n * Resolved key type if not a basic type.\r\n * @type {ReflectionObject|null}\r\n */\r\n this.resolvedKeyType = null;\r\n\r\n // Overrides Field#map\r\n this.map = true;\r\n}\r\n\r\n/**\r\n * Map field descriptor.\r\n * @interface IMapField\r\n * @extends {IField}\r\n * @property {string} keyType Key type\r\n */\r\n\r\n/**\r\n * Extension map field descriptor.\r\n * @interface IExtensionMapField\r\n * @extends IMapField\r\n * @property {string} extend Extended type\r\n */\r\n\r\n/**\r\n * Constructs a map field from a map field descriptor.\r\n * @param {string} name Field name\r\n * @param {IMapField} json Map field descriptor\r\n * @returns {MapField} Created map field\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nMapField.fromJSON = function fromJSON(name, json) {\r\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\r\n};\r\n\r\n/**\r\n * Converts this map field to a map field descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IMapField} Map field descriptor\r\n */\r\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"keyType\" , this.keyType,\r\n \"type\" , this.type,\r\n \"id\" , this.id,\r\n \"extend\" , this.extend,\r\n \"options\" , this.options,\r\n \"comment\" , keepComments ? this.comment : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nMapField.prototype.resolve = function resolve() {\r\n if (this.resolved)\r\n return this;\r\n\r\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\r\n if (types.mapKey[this.keyType] === undefined)\r\n throw Error(\"invalid key type: \" + this.keyType);\r\n\r\n return Field.prototype.resolve.call(this);\r\n};\r\n\r\n/**\r\n * Map field decorator (TypeScript).\r\n * @name MapField.d\r\n * @function\r\n * @param {number} fieldId Field id\r\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\r\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\r\n * @returns {FieldDecorator} Decorator function\r\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\r\n */\r\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\r\n\r\n // submessage value: decorate the submessage and use its name as the type\r\n if (typeof fieldValueType === \"function\")\r\n fieldValueType = util.decorateType(fieldValueType).name;\r\n\r\n // enum reference value: create a reflected copy of the enum and keep reuseing it\r\n else if (fieldValueType && typeof fieldValueType === \"object\")\r\n fieldValueType = util.decorateEnum(fieldValueType).name;\r\n\r\n return function mapFieldDecorator(prototype, fieldName) {\r\n util.decorateType(prototype.constructor)\r\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\r\n };\r\n};\r\n","\"use strict\";\r\nmodule.exports = Message;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\n/**\r\n * Constructs a new message instance.\r\n * @classdesc Abstract runtime message.\r\n * @constructor\r\n * @param {Properties} [properties] Properties to set\r\n * @template T extends object = object\r\n */\r\nfunction Message(properties) {\r\n // not used internally\r\n if (properties)\r\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\r\n this[keys[i]] = properties[keys[i]];\r\n}\r\n\r\n/**\r\n * Reference to the reflected type.\r\n * @name Message.$type\r\n * @type {Type}\r\n * @readonly\r\n */\r\n\r\n/**\r\n * Reference to the reflected type.\r\n * @name Message#$type\r\n * @type {Type}\r\n * @readonly\r\n */\r\n\r\n/*eslint-disable valid-jsdoc*/\r\n\r\n/**\r\n * Creates a new message of this type using the specified properties.\r\n * @param {Object.} [properties] Properties to set\r\n * @returns {Message} Message instance\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.create = function create(properties) {\r\n return this.$type.create(properties);\r\n};\r\n\r\n/**\r\n * Encodes a message of this type.\r\n * @param {T|Object.} message Message to encode\r\n * @param {Writer} [writer] Writer to use\r\n * @returns {Writer} Writer\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.encode = function encode(message, writer) {\r\n return this.$type.encode(message, writer);\r\n};\r\n\r\n/**\r\n * Encodes a message of this type preceeded by its length as a varint.\r\n * @param {T|Object.} message Message to encode\r\n * @param {Writer} [writer] Writer to use\r\n * @returns {Writer} Writer\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\r\n return this.$type.encodeDelimited(message, writer);\r\n};\r\n\r\n/**\r\n * Decodes a message of this type.\r\n * @name Message.decode\r\n * @function\r\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\r\n * @returns {T} Decoded message\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.decode = function decode(reader) {\r\n return this.$type.decode(reader);\r\n};\r\n\r\n/**\r\n * Decodes a message of this type preceeded by its length as a varint.\r\n * @name Message.decodeDelimited\r\n * @function\r\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\r\n * @returns {T} Decoded message\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.decodeDelimited = function decodeDelimited(reader) {\r\n return this.$type.decodeDelimited(reader);\r\n};\r\n\r\n/**\r\n * Verifies a message of this type.\r\n * @name Message.verify\r\n * @function\r\n * @param {Object.} message Plain object to verify\r\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\r\n */\r\nMessage.verify = function verify(message) {\r\n return this.$type.verify(message);\r\n};\r\n\r\n/**\r\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\r\n * @param {Object.} object Plain object\r\n * @returns {T} Message instance\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.fromObject = function fromObject(object) {\r\n return this.$type.fromObject(object);\r\n};\r\n\r\n/**\r\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\r\n * @param {T} message Message instance\r\n * @param {IConversionOptions} [options] Conversion options\r\n * @returns {Object.} Plain object\r\n * @template T extends Message\r\n * @this Constructor\r\n */\r\nMessage.toObject = function toObject(message, options) {\r\n return this.$type.toObject(message, options);\r\n};\r\n\r\n/**\r\n * Converts this message to JSON.\r\n * @returns {Object.} JSON object\r\n */\r\nMessage.prototype.toJSON = function toJSON() {\r\n return this.$type.toObject(this, util.toJSONOptions);\r\n};\r\n\r\n/*eslint-enable valid-jsdoc*/","\"use strict\";\r\nmodule.exports = Method;\r\n\r\n// extends ReflectionObject\r\nvar ReflectionObject = require(\"./object\");\r\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\r\n\r\nvar util = require(\"./util\");\r\n\r\n/**\r\n * Constructs a new service method instance.\r\n * @classdesc Reflected service method.\r\n * @extends ReflectionObject\r\n * @constructor\r\n * @param {string} name Method name\r\n * @param {string|undefined} type Method type, usually `\"rpc\"`\r\n * @param {string} requestType Request message type\r\n * @param {string} responseType Response message type\r\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\r\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\r\n * @param {Object.} [options] Declared options\r\n * @param {string} [comment] The comment for this method\r\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\r\n */\r\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\r\n\r\n /* istanbul ignore next */\r\n if (util.isObject(requestStream)) {\r\n options = requestStream;\r\n requestStream = responseStream = undefined;\r\n } else if (util.isObject(responseStream)) {\r\n options = responseStream;\r\n responseStream = undefined;\r\n }\r\n\r\n /* istanbul ignore if */\r\n if (!(type === undefined || util.isString(type)))\r\n throw TypeError(\"type must be a string\");\r\n\r\n /* istanbul ignore if */\r\n if (!util.isString(requestType))\r\n throw TypeError(\"requestType must be a string\");\r\n\r\n /* istanbul ignore if */\r\n if (!util.isString(responseType))\r\n throw TypeError(\"responseType must be a string\");\r\n\r\n ReflectionObject.call(this, name, options);\r\n\r\n /**\r\n * Method type.\r\n * @type {string}\r\n */\r\n this.type = type || \"rpc\"; // toJSON\r\n\r\n /**\r\n * Request type.\r\n * @type {string}\r\n */\r\n this.requestType = requestType; // toJSON, marker\r\n\r\n /**\r\n * Whether requests are streamed or not.\r\n * @type {boolean|undefined}\r\n */\r\n this.requestStream = requestStream ? true : undefined; // toJSON\r\n\r\n /**\r\n * Response type.\r\n * @type {string}\r\n */\r\n this.responseType = responseType; // toJSON\r\n\r\n /**\r\n * Whether responses are streamed or not.\r\n * @type {boolean|undefined}\r\n */\r\n this.responseStream = responseStream ? true : undefined; // toJSON\r\n\r\n /**\r\n * Resolved request type.\r\n * @type {Type|null}\r\n */\r\n this.resolvedRequestType = null;\r\n\r\n /**\r\n * Resolved response type.\r\n * @type {Type|null}\r\n */\r\n this.resolvedResponseType = null;\r\n\r\n /**\r\n * Comment for this method\r\n * @type {string|null}\r\n */\r\n this.comment = comment;\r\n\r\n /**\r\n * Options properly parsed into an object\r\n */\r\n this.parsedOptions = parsedOptions;\r\n}\r\n\r\n/**\r\n * Method descriptor.\r\n * @interface IMethod\r\n * @property {string} [type=\"rpc\"] Method type\r\n * @property {string} requestType Request type\r\n * @property {string} responseType Response type\r\n * @property {boolean} [requestStream=false] Whether requests are streamed\r\n * @property {boolean} [responseStream=false] Whether responses are streamed\r\n * @property {Object.} [options] Method options\r\n * @property {string} comment Method comments\r\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\r\n */\r\n\r\n/**\r\n * Constructs a method from a method descriptor.\r\n * @param {string} name Method name\r\n * @param {IMethod} json Method descriptor\r\n * @returns {Method} Created method\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nMethod.fromJSON = function fromJSON(name, json) {\r\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\r\n};\r\n\r\n/**\r\n * Converts this method to a method descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IMethod} Method descriptor\r\n */\r\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\r\n \"requestType\" , this.requestType,\r\n \"requestStream\" , this.requestStream,\r\n \"responseType\" , this.responseType,\r\n \"responseStream\" , this.responseStream,\r\n \"options\" , this.options,\r\n \"comment\" , keepComments ? this.comment : undefined,\r\n \"parsedOptions\" , this.parsedOptions,\r\n ]);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nMethod.prototype.resolve = function resolve() {\r\n\r\n /* istanbul ignore if */\r\n if (this.resolved)\r\n return this;\r\n\r\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\r\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\r\n\r\n return ReflectionObject.prototype.resolve.call(this);\r\n};\r\n","\"use strict\";\r\nmodule.exports = Namespace;\r\n\r\n// extends ReflectionObject\r\nvar ReflectionObject = require(\"./object\");\r\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\r\n\r\nvar Field = require(\"./field\"),\r\n util = require(\"./util\"),\r\n OneOf = require(\"./oneof\");\r\n\r\nvar Type, // cyclic\r\n Service,\r\n Enum;\r\n\r\n/**\r\n * Constructs a new namespace instance.\r\n * @name Namespace\r\n * @classdesc Reflected namespace.\r\n * @extends NamespaceBase\r\n * @constructor\r\n * @param {string} name Namespace name\r\n * @param {Object.} [options] Declared options\r\n */\r\n\r\n/**\r\n * Constructs a namespace from JSON.\r\n * @memberof Namespace\r\n * @function\r\n * @param {string} name Namespace name\r\n * @param {Object.} json JSON object\r\n * @returns {Namespace} Created namespace\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nNamespace.fromJSON = function fromJSON(name, json) {\r\n return new Namespace(name, json.options).addJSON(json.nested);\r\n};\r\n\r\n/**\r\n * Converts an array of reflection objects to JSON.\r\n * @memberof Namespace\r\n * @param {ReflectionObject[]} array Object array\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\r\n */\r\nfunction arrayToJSON(array, toJSONOptions) {\r\n if (!(array && array.length))\r\n return undefined;\r\n var obj = {};\r\n for (var i = 0; i < array.length; ++i)\r\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\r\n return obj;\r\n}\r\n\r\nNamespace.arrayToJSON = arrayToJSON;\r\n\r\n/**\r\n * Tests if the specified id is reserved.\r\n * @param {Array.|undefined} reserved Array of reserved ranges and names\r\n * @param {number} id Id to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nNamespace.isReservedId = function isReservedId(reserved, id) {\r\n if (reserved)\r\n for (var i = 0; i < reserved.length; ++i)\r\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\r\n return true;\r\n return false;\r\n};\r\n\r\n/**\r\n * Tests if the specified name is reserved.\r\n * @param {Array.|undefined} reserved Array of reserved ranges and names\r\n * @param {string} name Name to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nNamespace.isReservedName = function isReservedName(reserved, name) {\r\n if (reserved)\r\n for (var i = 0; i < reserved.length; ++i)\r\n if (reserved[i] === name)\r\n return true;\r\n return false;\r\n};\r\n\r\n/**\r\n * Not an actual constructor. Use {@link Namespace} instead.\r\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\r\n * @exports NamespaceBase\r\n * @extends ReflectionObject\r\n * @abstract\r\n * @constructor\r\n * @param {string} name Namespace name\r\n * @param {Object.} [options] Declared options\r\n * @see {@link Namespace}\r\n */\r\nfunction Namespace(name, options) {\r\n ReflectionObject.call(this, name, options);\r\n\r\n /**\r\n * Nested objects by name.\r\n * @type {Object.|undefined}\r\n */\r\n this.nested = undefined; // toJSON\r\n\r\n /**\r\n * Cached nested objects as an array.\r\n * @type {ReflectionObject[]|null}\r\n * @private\r\n */\r\n this._nestedArray = null;\r\n}\r\n\r\nfunction clearCache(namespace) {\r\n namespace._nestedArray = null;\r\n return namespace;\r\n}\r\n\r\n/**\r\n * Nested objects of this namespace as an array for iteration.\r\n * @name NamespaceBase#nestedArray\r\n * @type {ReflectionObject[]}\r\n * @readonly\r\n */\r\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\r\n get: function() {\r\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\r\n }\r\n});\r\n\r\n/**\r\n * Namespace descriptor.\r\n * @interface INamespace\r\n * @property {Object.} [options] Namespace options\r\n * @property {Object.} [nested] Nested object descriptors\r\n */\r\n\r\n/**\r\n * Any extension field descriptor.\r\n * @typedef AnyExtensionField\r\n * @type {IExtensionField|IExtensionMapField}\r\n */\r\n\r\n/**\r\n * Any nested object descriptor.\r\n * @typedef AnyNestedObject\r\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\r\n */\r\n\r\n/**\r\n * Converts this namespace to a namespace descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {INamespace} Namespace descriptor\r\n */\r\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\r\n return util.toObject([\r\n \"options\" , this.options,\r\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\r\n ]);\r\n};\r\n\r\n/**\r\n * Adds nested objects to this namespace from nested object descriptors.\r\n * @param {Object.} nestedJson Any nested object descriptors\r\n * @returns {Namespace} `this`\r\n */\r\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\r\n var ns = this;\r\n /* istanbul ignore else */\r\n if (nestedJson) {\r\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\r\n nested = nestedJson[names[i]];\r\n ns.add( // most to least likely\r\n ( nested.fields !== undefined\r\n ? Type.fromJSON\r\n : nested.values !== undefined\r\n ? Enum.fromJSON\r\n : nested.methods !== undefined\r\n ? Service.fromJSON\r\n : nested.id !== undefined\r\n ? Field.fromJSON\r\n : Namespace.fromJSON )(names[i], nested)\r\n );\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Gets the nested object of the specified name.\r\n * @param {string} name Nested object name\r\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\r\n */\r\nNamespace.prototype.get = function get(name) {\r\n return this.nested && this.nested[name]\r\n || null;\r\n};\r\n\r\n/**\r\n * Gets the values of the nested {@link Enum|enum} of the specified name.\r\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\r\n * @param {string} name Nested enum name\r\n * @returns {Object.} Enum values\r\n * @throws {Error} If there is no such enum\r\n */\r\nNamespace.prototype.getEnum = function getEnum(name) {\r\n if (this.nested && this.nested[name] instanceof Enum)\r\n return this.nested[name].values;\r\n throw Error(\"no such enum: \" + name);\r\n};\r\n\r\n/**\r\n * Adds a nested object to this namespace.\r\n * @param {ReflectionObject} object Nested object to add\r\n * @returns {Namespace} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If there is already a nested object with this name\r\n */\r\nNamespace.prototype.add = function add(object) {\r\n\r\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\r\n throw TypeError(\"object must be a valid nested object\");\r\n\r\n if (!this.nested)\r\n this.nested = {};\r\n else {\r\n var prev = this.get(object.name);\r\n if (prev) {\r\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\r\n // replace plain namespace but keep existing nested elements and options\r\n var nested = prev.nestedArray;\r\n for (var i = 0; i < nested.length; ++i)\r\n object.add(nested[i]);\r\n this.remove(prev);\r\n if (!this.nested)\r\n this.nested = {};\r\n object.setOptions(prev.options, true);\r\n\r\n } else\r\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\r\n }\r\n }\r\n this.nested[object.name] = object;\r\n object.onAdd(this);\r\n return clearCache(this);\r\n};\r\n\r\n/**\r\n * Removes a nested object from this namespace.\r\n * @param {ReflectionObject} object Nested object to remove\r\n * @returns {Namespace} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If `object` is not a member of this namespace\r\n */\r\nNamespace.prototype.remove = function remove(object) {\r\n\r\n if (!(object instanceof ReflectionObject))\r\n throw TypeError(\"object must be a ReflectionObject\");\r\n if (object.parent !== this)\r\n throw Error(object + \" is not a member of \" + this);\r\n\r\n delete this.nested[object.name];\r\n if (!Object.keys(this.nested).length)\r\n this.nested = undefined;\r\n\r\n object.onRemove(this);\r\n return clearCache(this);\r\n};\r\n\r\n/**\r\n * Defines additial namespaces within this one if not yet existing.\r\n * @param {string|string[]} path Path to create\r\n * @param {*} [json] Nested types to create from JSON\r\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\r\n */\r\nNamespace.prototype.define = function define(path, json) {\r\n\r\n if (util.isString(path))\r\n path = path.split(\".\");\r\n else if (!Array.isArray(path))\r\n throw TypeError(\"illegal path\");\r\n if (path && path.length && path[0] === \"\")\r\n throw Error(\"path must be relative\");\r\n\r\n var ptr = this;\r\n while (path.length > 0) {\r\n var part = path.shift();\r\n if (ptr.nested && ptr.nested[part]) {\r\n ptr = ptr.nested[part];\r\n if (!(ptr instanceof Namespace))\r\n throw Error(\"path conflicts with non-namespace objects\");\r\n } else\r\n ptr.add(ptr = new Namespace(part));\r\n }\r\n if (json)\r\n ptr.addJSON(json);\r\n return ptr;\r\n};\r\n\r\n/**\r\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\r\n * @returns {Namespace} `this`\r\n */\r\nNamespace.prototype.resolveAll = function resolveAll() {\r\n var nested = this.nestedArray, i = 0;\r\n while (i < nested.length)\r\n if (nested[i] instanceof Namespace)\r\n nested[i++].resolveAll();\r\n else\r\n nested[i++].resolve();\r\n return this.resolve();\r\n};\r\n\r\n/**\r\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\r\n * @param {string|string[]} path Path to look up\r\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\r\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\r\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\r\n */\r\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\r\n\r\n /* istanbul ignore next */\r\n if (typeof filterTypes === \"boolean\") {\r\n parentAlreadyChecked = filterTypes;\r\n filterTypes = undefined;\r\n } else if (filterTypes && !Array.isArray(filterTypes))\r\n filterTypes = [ filterTypes ];\r\n\r\n if (util.isString(path) && path.length) {\r\n if (path === \".\")\r\n return this.root;\r\n path = path.split(\".\");\r\n } else if (!path.length)\r\n return this;\r\n\r\n // Start at root if path is absolute\r\n if (path[0] === \"\")\r\n return this.root.lookup(path.slice(1), filterTypes);\r\n\r\n // Test if the first part matches any nested object, and if so, traverse if path contains more\r\n var found = this.get(path[0]);\r\n if (found) {\r\n if (path.length === 1) {\r\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\r\n return found;\r\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\r\n return found;\r\n\r\n // Otherwise try each nested namespace\r\n } else\r\n for (var i = 0; i < this.nestedArray.length; ++i)\r\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\r\n return found;\r\n\r\n // If there hasn't been a match, try again at the parent\r\n if (this.parent === null || parentAlreadyChecked)\r\n return null;\r\n return this.parent.lookup(path, filterTypes);\r\n};\r\n\r\n/**\r\n * Looks up the reflection object at the specified path, relative to this namespace.\r\n * @name NamespaceBase#lookup\r\n * @function\r\n * @param {string|string[]} path Path to look up\r\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\r\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\r\n * @variation 2\r\n */\r\n// lookup(path: string, [parentAlreadyChecked: boolean])\r\n\r\n/**\r\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\r\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r\n * @param {string|string[]} path Path to look up\r\n * @returns {Type} Looked up type\r\n * @throws {Error} If `path` does not point to a type\r\n */\r\nNamespace.prototype.lookupType = function lookupType(path) {\r\n var found = this.lookup(path, [ Type ]);\r\n if (!found)\r\n throw Error(\"no such type: \" + path);\r\n return found;\r\n};\r\n\r\n/**\r\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\r\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r\n * @param {string|string[]} path Path to look up\r\n * @returns {Enum} Looked up enum\r\n * @throws {Error} If `path` does not point to an enum\r\n */\r\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\r\n var found = this.lookup(path, [ Enum ]);\r\n if (!found)\r\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\r\n return found;\r\n};\r\n\r\n/**\r\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\r\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r\n * @param {string|string[]} path Path to look up\r\n * @returns {Type} Looked up type or enum\r\n * @throws {Error} If `path` does not point to a type or enum\r\n */\r\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\r\n var found = this.lookup(path, [ Type, Enum ]);\r\n if (!found)\r\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\r\n return found;\r\n};\r\n\r\n/**\r\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\r\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r\n * @param {string|string[]} path Path to look up\r\n * @returns {Service} Looked up service\r\n * @throws {Error} If `path` does not point to a service\r\n */\r\nNamespace.prototype.lookupService = function lookupService(path) {\r\n var found = this.lookup(path, [ Service ]);\r\n if (!found)\r\n throw Error(\"no such Service '\" + path + \"' in \" + this);\r\n return found;\r\n};\r\n\r\n// Sets up cyclic dependencies (called in index-light)\r\nNamespace._configure = function(Type_, Service_, Enum_) {\r\n Type = Type_;\r\n Service = Service_;\r\n Enum = Enum_;\r\n};\r\n","\"use strict\";\r\nmodule.exports = ReflectionObject;\r\n\r\nReflectionObject.className = \"ReflectionObject\";\r\n\r\nvar util = require(\"./util\");\r\n\r\nvar Root; // cyclic\r\n\r\n/**\r\n * Constructs a new reflection object instance.\r\n * @classdesc Base class of all reflection objects.\r\n * @constructor\r\n * @param {string} name Object name\r\n * @param {Object.} [options] Declared options\r\n * @abstract\r\n */\r\nfunction ReflectionObject(name, options) {\r\n\r\n if (!util.isString(name))\r\n throw TypeError(\"name must be a string\");\r\n\r\n if (options && !util.isObject(options))\r\n throw TypeError(\"options must be an object\");\r\n\r\n /**\r\n * Options.\r\n * @type {Object.|undefined}\r\n */\r\n this.options = options; // toJSON\r\n\r\n /**\r\n * Parsed Options.\r\n * @type {Array.>|undefined}\r\n */\r\n this.parsedOptions = null;\r\n\r\n /**\r\n * Unique name within its namespace.\r\n * @type {string}\r\n */\r\n this.name = name;\r\n\r\n /**\r\n * Parent namespace.\r\n * @type {Namespace|null}\r\n */\r\n this.parent = null;\r\n\r\n /**\r\n * Whether already resolved or not.\r\n * @type {boolean}\r\n */\r\n this.resolved = false;\r\n\r\n /**\r\n * Comment text, if any.\r\n * @type {string|null}\r\n */\r\n this.comment = null;\r\n\r\n /**\r\n * Defining file name.\r\n * @type {string|null}\r\n */\r\n this.filename = null;\r\n}\r\n\r\nObject.defineProperties(ReflectionObject.prototype, {\r\n\r\n /**\r\n * Reference to the root namespace.\r\n * @name ReflectionObject#root\r\n * @type {Root}\r\n * @readonly\r\n */\r\n root: {\r\n get: function() {\r\n var ptr = this;\r\n while (ptr.parent !== null)\r\n ptr = ptr.parent;\r\n return ptr;\r\n }\r\n },\r\n\r\n /**\r\n * Full name including leading dot.\r\n * @name ReflectionObject#fullName\r\n * @type {string}\r\n * @readonly\r\n */\r\n fullName: {\r\n get: function() {\r\n var path = [ this.name ],\r\n ptr = this.parent;\r\n while (ptr) {\r\n path.unshift(ptr.name);\r\n ptr = ptr.parent;\r\n }\r\n return path.join(\".\");\r\n }\r\n }\r\n});\r\n\r\n/**\r\n * Converts this reflection object to its descriptor representation.\r\n * @returns {Object.} Descriptor\r\n * @abstract\r\n */\r\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\r\n throw Error(); // not implemented, shouldn't happen\r\n};\r\n\r\n/**\r\n * Called when this object is added to a parent.\r\n * @param {ReflectionObject} parent Parent added to\r\n * @returns {undefined}\r\n */\r\nReflectionObject.prototype.onAdd = function onAdd(parent) {\r\n if (this.parent && this.parent !== parent)\r\n this.parent.remove(this);\r\n this.parent = parent;\r\n this.resolved = false;\r\n var root = parent.root;\r\n if (root instanceof Root)\r\n root._handleAdd(this);\r\n};\r\n\r\n/**\r\n * Called when this object is removed from a parent.\r\n * @param {ReflectionObject} parent Parent removed from\r\n * @returns {undefined}\r\n */\r\nReflectionObject.prototype.onRemove = function onRemove(parent) {\r\n var root = parent.root;\r\n if (root instanceof Root)\r\n root._handleRemove(this);\r\n this.parent = null;\r\n this.resolved = false;\r\n};\r\n\r\n/**\r\n * Resolves this objects type references.\r\n * @returns {ReflectionObject} `this`\r\n */\r\nReflectionObject.prototype.resolve = function resolve() {\r\n if (this.resolved)\r\n return this;\r\n if (this.root instanceof Root)\r\n this.resolved = true; // only if part of a root\r\n return this;\r\n};\r\n\r\n/**\r\n * Gets an option value.\r\n * @param {string} name Option name\r\n * @returns {*} Option value or `undefined` if not set\r\n */\r\nReflectionObject.prototype.getOption = function getOption(name) {\r\n if (this.options)\r\n return this.options[name];\r\n return undefined;\r\n};\r\n\r\n/**\r\n * Sets an option.\r\n * @param {string} name Option name\r\n * @param {*} value Option value\r\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\r\n * @returns {ReflectionObject} `this`\r\n */\r\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\r\n if (!ifNotSet || !this.options || this.options[name] === undefined)\r\n (this.options || (this.options = {}))[name] = value;\r\n return this;\r\n};\r\n\r\n/**\r\n * Sets a parsed option.\r\n * @param {string} name parsed Option name\r\n * @param {*} value Option value\r\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\r\n * @returns {ReflectionObject} `this`\r\n */\r\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\r\n if (!this.parsedOptions) {\r\n this.parsedOptions = [];\r\n }\r\n var parsedOptions = this.parsedOptions;\r\n if (propName) {\r\n // If setting a sub property of an option then try to merge it\r\n // with an existing option\r\n var opt = parsedOptions.find(function (opt) {\r\n return Object.prototype.hasOwnProperty.call(opt, name);\r\n });\r\n if (opt) {\r\n // If we found an existing option - just merge the property value\r\n var newValue = opt[name];\r\n util.setProperty(newValue, propName, value);\r\n } else {\r\n // otherwise, create a new option, set it's property and add it to the list\r\n opt = {};\r\n opt[name] = util.setProperty({}, propName, value);\r\n parsedOptions.push(opt);\r\n }\r\n } else {\r\n // Always create a new option when setting the value of the option itself\r\n var newOpt = {};\r\n newOpt[name] = value;\r\n parsedOptions.push(newOpt);\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Sets multiple options.\r\n * @param {Object.} options Options to set\r\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\r\n * @returns {ReflectionObject} `this`\r\n */\r\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\r\n if (options)\r\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\r\n this.setOption(keys[i], options[keys[i]], ifNotSet);\r\n return this;\r\n};\r\n\r\n/**\r\n * Converts this instance to its string representation.\r\n * @returns {string} Class name[, space, full name]\r\n */\r\nReflectionObject.prototype.toString = function toString() {\r\n var className = this.constructor.className,\r\n fullName = this.fullName;\r\n if (fullName.length)\r\n return className + \" \" + fullName;\r\n return className;\r\n};\r\n\r\n// Sets up cyclic dependencies (called in index-light)\r\nReflectionObject._configure = function(Root_) {\r\n Root = Root_;\r\n};\r\n","\"use strict\";\r\nmodule.exports = OneOf;\r\n\r\n// extends ReflectionObject\r\nvar ReflectionObject = require(\"./object\");\r\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\r\n\r\nvar Field = require(\"./field\"),\r\n util = require(\"./util\");\r\n\r\n/**\r\n * Constructs a new oneof instance.\r\n * @classdesc Reflected oneof.\r\n * @extends ReflectionObject\r\n * @constructor\r\n * @param {string} name Oneof name\r\n * @param {string[]|Object.} [fieldNames] Field names\r\n * @param {Object.} [options] Declared options\r\n * @param {string} [comment] Comment associated with this field\r\n */\r\nfunction OneOf(name, fieldNames, options, comment) {\r\n if (!Array.isArray(fieldNames)) {\r\n options = fieldNames;\r\n fieldNames = undefined;\r\n }\r\n ReflectionObject.call(this, name, options);\r\n\r\n /* istanbul ignore if */\r\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\r\n throw TypeError(\"fieldNames must be an Array\");\r\n\r\n /**\r\n * Field names that belong to this oneof.\r\n * @type {string[]}\r\n */\r\n this.oneof = fieldNames || []; // toJSON, marker\r\n\r\n /**\r\n * Fields that belong to this oneof as an array for iteration.\r\n * @type {Field[]}\r\n * @readonly\r\n */\r\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\r\n\r\n /**\r\n * Comment for this field.\r\n * @type {string|null}\r\n */\r\n this.comment = comment;\r\n}\r\n\r\n/**\r\n * Oneof descriptor.\r\n * @interface IOneOf\r\n * @property {Array.} oneof Oneof field names\r\n * @property {Object.} [options] Oneof options\r\n */\r\n\r\n/**\r\n * Constructs a oneof from a oneof descriptor.\r\n * @param {string} name Oneof name\r\n * @param {IOneOf} json Oneof descriptor\r\n * @returns {OneOf} Created oneof\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nOneOf.fromJSON = function fromJSON(name, json) {\r\n return new OneOf(name, json.oneof, json.options, json.comment);\r\n};\r\n\r\n/**\r\n * Converts this oneof to a oneof descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IOneOf} Oneof descriptor\r\n */\r\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"options\" , this.options,\r\n \"oneof\" , this.oneof,\r\n \"comment\" , keepComments ? this.comment : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * Adds the fields of the specified oneof to the parent if not already done so.\r\n * @param {OneOf} oneof The oneof\r\n * @returns {undefined}\r\n * @inner\r\n * @ignore\r\n */\r\nfunction addFieldsToParent(oneof) {\r\n if (oneof.parent)\r\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\r\n if (!oneof.fieldsArray[i].parent)\r\n oneof.parent.add(oneof.fieldsArray[i]);\r\n}\r\n\r\n/**\r\n * Adds a field to this oneof and removes it from its current parent, if any.\r\n * @param {Field} field Field to add\r\n * @returns {OneOf} `this`\r\n */\r\nOneOf.prototype.add = function add(field) {\r\n\r\n /* istanbul ignore if */\r\n if (!(field instanceof Field))\r\n throw TypeError(\"field must be a Field\");\r\n\r\n if (field.parent && field.parent !== this.parent)\r\n field.parent.remove(field);\r\n this.oneof.push(field.name);\r\n this.fieldsArray.push(field);\r\n field.partOf = this; // field.parent remains null\r\n addFieldsToParent(this);\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes a field from this oneof and puts it back to the oneof's parent.\r\n * @param {Field} field Field to remove\r\n * @returns {OneOf} `this`\r\n */\r\nOneOf.prototype.remove = function remove(field) {\r\n\r\n /* istanbul ignore if */\r\n if (!(field instanceof Field))\r\n throw TypeError(\"field must be a Field\");\r\n\r\n var index = this.fieldsArray.indexOf(field);\r\n\r\n /* istanbul ignore if */\r\n if (index < 0)\r\n throw Error(field + \" is not a member of \" + this);\r\n\r\n this.fieldsArray.splice(index, 1);\r\n index = this.oneof.indexOf(field.name);\r\n\r\n /* istanbul ignore else */\r\n if (index > -1) // theoretical\r\n this.oneof.splice(index, 1);\r\n\r\n field.partOf = null;\r\n return this;\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nOneOf.prototype.onAdd = function onAdd(parent) {\r\n ReflectionObject.prototype.onAdd.call(this, parent);\r\n var self = this;\r\n // Collect present fields\r\n for (var i = 0; i < this.oneof.length; ++i) {\r\n var field = parent.get(this.oneof[i]);\r\n if (field && !field.partOf) {\r\n field.partOf = self;\r\n self.fieldsArray.push(field);\r\n }\r\n }\r\n // Add not yet present fields\r\n addFieldsToParent(this);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nOneOf.prototype.onRemove = function onRemove(parent) {\r\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\r\n if ((field = this.fieldsArray[i]).parent)\r\n field.parent.remove(field);\r\n ReflectionObject.prototype.onRemove.call(this, parent);\r\n};\r\n\r\n/**\r\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\r\n * @typedef OneOfDecorator\r\n * @type {function}\r\n * @param {Object} prototype Target prototype\r\n * @param {string} oneofName OneOf name\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * OneOf decorator (TypeScript).\r\n * @function\r\n * @param {...string} fieldNames Field names\r\n * @returns {OneOfDecorator} Decorator function\r\n * @template T extends string\r\n */\r\nOneOf.d = function decorateOneOf() {\r\n var fieldNames = new Array(arguments.length),\r\n index = 0;\r\n while (index < arguments.length)\r\n fieldNames[index] = arguments[index++];\r\n return function oneOfDecorator(prototype, oneofName) {\r\n util.decorateType(prototype.constructor)\r\n .add(new OneOf(oneofName, fieldNames));\r\n Object.defineProperty(prototype, oneofName, {\r\n get: util.oneOfGetter(fieldNames),\r\n set: util.oneOfSetter(fieldNames)\r\n });\r\n };\r\n};\r\n","\"use strict\";\r\nmodule.exports = parse;\r\n\r\nparse.filename = null;\r\nparse.defaults = { keepCase: false };\r\n\r\nvar tokenize = require(\"./tokenize\"),\r\n Root = require(\"./root\"),\r\n Type = require(\"./type\"),\r\n Field = require(\"./field\"),\r\n MapField = require(\"./mapfield\"),\r\n OneOf = require(\"./oneof\"),\r\n Enum = require(\"./enum\"),\r\n Service = require(\"./service\"),\r\n Method = require(\"./method\"),\r\n types = require(\"./types\"),\r\n util = require(\"./util\");\r\n\r\nvar base10Re = /^[1-9][0-9]*$/,\r\n base10NegRe = /^-?[1-9][0-9]*$/,\r\n base16Re = /^0[x][0-9a-fA-F]+$/,\r\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\r\n base8Re = /^0[0-7]+$/,\r\n base8NegRe = /^-?0[0-7]+$/,\r\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\r\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\r\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\r\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\r\n\r\n/**\r\n * Result object returned from {@link parse}.\r\n * @interface IParserResult\r\n * @property {string|undefined} package Package name, if declared\r\n * @property {string[]|undefined} imports Imports, if any\r\n * @property {string[]|undefined} weakImports Weak imports, if any\r\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\r\n * @property {Root} root Populated root instance\r\n */\r\n\r\n/**\r\n * Options modifying the behavior of {@link parse}.\r\n * @interface IParseOptions\r\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\r\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\r\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\r\n */\r\n\r\n/**\r\n * Options modifying the behavior of JSON serialization.\r\n * @interface IToJSONOptions\r\n * @property {boolean} [keepComments=false] Serializes comments.\r\n */\r\n\r\n/**\r\n * Parses the given .proto source and returns an object with the parsed contents.\r\n * @param {string} source Source contents\r\n * @param {Root} root Root to populate\r\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r\n * @returns {IParserResult} Parser result\r\n * @property {string} filename=null Currently processing file name for error reporting, if known\r\n * @property {IParseOptions} defaults Default {@link IParseOptions}\r\n */\r\nfunction parse(source, root, options) {\r\n /* eslint-disable callback-return */\r\n if (!(root instanceof Root)) {\r\n options = root;\r\n root = new Root();\r\n }\r\n if (!options)\r\n options = parse.defaults;\r\n\r\n var preferTrailingComment = options.preferTrailingComment || false;\r\n var tn = tokenize(source, options.alternateCommentMode || false),\r\n next = tn.next,\r\n push = tn.push,\r\n peek = tn.peek,\r\n skip = tn.skip,\r\n cmnt = tn.cmnt;\r\n\r\n var head = true,\r\n pkg,\r\n imports,\r\n weakImports,\r\n syntax,\r\n isProto3 = false;\r\n\r\n var ptr = root;\r\n\r\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\r\n\r\n /* istanbul ignore next */\r\n function illegal(token, name, insideTryCatch) {\r\n var filename = parse.filename;\r\n if (!insideTryCatch)\r\n parse.filename = null;\r\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\r\n }\r\n\r\n function readString() {\r\n var values = [],\r\n token;\r\n do {\r\n /* istanbul ignore if */\r\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\r\n throw illegal(token);\r\n\r\n values.push(next());\r\n skip(token);\r\n token = peek();\r\n } while (token === \"\\\"\" || token === \"'\");\r\n return values.join(\"\");\r\n }\r\n\r\n function readValue(acceptTypeRef) {\r\n var token = next();\r\n switch (token) {\r\n case \"'\":\r\n case \"\\\"\":\r\n push(token);\r\n return readString();\r\n case \"true\": case \"TRUE\":\r\n return true;\r\n case \"false\": case \"FALSE\":\r\n return false;\r\n }\r\n try {\r\n return parseNumber(token, /* insideTryCatch */ true);\r\n } catch (e) {\r\n\r\n /* istanbul ignore else */\r\n if (acceptTypeRef && typeRefRe.test(token))\r\n return token;\r\n\r\n /* istanbul ignore next */\r\n throw illegal(token, \"value\");\r\n }\r\n }\r\n\r\n function readRanges(target, acceptStrings) {\r\n var token, start;\r\n do {\r\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\r\n target.push(readString());\r\n else\r\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\r\n } while (skip(\",\", true));\r\n var dummy = {options: undefined};\r\n dummy.setOption = function(name, value) {\r\n if (this.options === undefined) this.options = {};\r\n this.options[name] = value;\r\n };\r\n ifBlock(\r\n dummy,\r\n function parseRange_block(token) {\r\n /* istanbul ignore else */\r\n if (token === \"option\") {\r\n parseOption(dummy, token); // skip\r\n skip(\";\");\r\n } else\r\n throw illegal(token);\r\n },\r\n function parseRange_line() {\r\n parseInlineOptions(dummy); // skip\r\n });\r\n }\r\n\r\n function parseNumber(token, insideTryCatch) {\r\n var sign = 1;\r\n if (token.charAt(0) === \"-\") {\r\n sign = -1;\r\n token = token.substring(1);\r\n }\r\n switch (token) {\r\n case \"inf\": case \"INF\": case \"Inf\":\r\n return sign * Infinity;\r\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\r\n return NaN;\r\n case \"0\":\r\n return 0;\r\n }\r\n if (base10Re.test(token))\r\n return sign * parseInt(token, 10);\r\n if (base16Re.test(token))\r\n return sign * parseInt(token, 16);\r\n if (base8Re.test(token))\r\n return sign * parseInt(token, 8);\r\n\r\n /* istanbul ignore else */\r\n if (numberRe.test(token))\r\n return sign * parseFloat(token);\r\n\r\n /* istanbul ignore next */\r\n throw illegal(token, \"number\", insideTryCatch);\r\n }\r\n\r\n function parseId(token, acceptNegative) {\r\n switch (token) {\r\n case \"max\": case \"MAX\": case \"Max\":\r\n return 536870911;\r\n case \"0\":\r\n return 0;\r\n }\r\n\r\n /* istanbul ignore if */\r\n if (!acceptNegative && token.charAt(0) === \"-\")\r\n throw illegal(token, \"id\");\r\n\r\n if (base10NegRe.test(token))\r\n return parseInt(token, 10);\r\n if (base16NegRe.test(token))\r\n return parseInt(token, 16);\r\n\r\n /* istanbul ignore else */\r\n if (base8NegRe.test(token))\r\n return parseInt(token, 8);\r\n\r\n /* istanbul ignore next */\r\n throw illegal(token, \"id\");\r\n }\r\n\r\n function parsePackage() {\r\n\r\n /* istanbul ignore if */\r\n if (pkg !== undefined)\r\n throw illegal(\"package\");\r\n\r\n pkg = next();\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(pkg))\r\n throw illegal(pkg, \"name\");\r\n\r\n ptr = ptr.define(pkg);\r\n skip(\";\");\r\n }\r\n\r\n function parseImport() {\r\n var token = peek();\r\n var whichImports;\r\n switch (token) {\r\n case \"weak\":\r\n whichImports = weakImports || (weakImports = []);\r\n next();\r\n break;\r\n case \"public\":\r\n next();\r\n // eslint-disable-next-line no-fallthrough\r\n default:\r\n whichImports = imports || (imports = []);\r\n break;\r\n }\r\n token = readString();\r\n skip(\";\");\r\n whichImports.push(token);\r\n }\r\n\r\n function parseSyntax() {\r\n skip(\"=\");\r\n syntax = readString();\r\n isProto3 = syntax === \"proto3\";\r\n\r\n /* istanbul ignore if */\r\n if (!isProto3 && syntax !== \"proto2\")\r\n throw illegal(syntax, \"syntax\");\r\n\r\n skip(\";\");\r\n }\r\n\r\n function parseCommon(parent, token) {\r\n switch (token) {\r\n\r\n case \"option\":\r\n parseOption(parent, token);\r\n skip(\";\");\r\n return true;\r\n\r\n case \"message\":\r\n parseType(parent, token);\r\n return true;\r\n\r\n case \"enum\":\r\n parseEnum(parent, token);\r\n return true;\r\n\r\n case \"service\":\r\n parseService(parent, token);\r\n return true;\r\n\r\n case \"extend\":\r\n parseExtension(parent, token);\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n function ifBlock(obj, fnIf, fnElse) {\r\n var trailingLine = tn.line;\r\n if (obj) {\r\n if(typeof obj.comment !== \"string\") {\r\n obj.comment = cmnt(); // try block-type comment\r\n }\r\n obj.filename = parse.filename;\r\n }\r\n if (skip(\"{\", true)) {\r\n var token;\r\n while ((token = next()) !== \"}\")\r\n fnIf(token);\r\n skip(\";\", true);\r\n } else {\r\n if (fnElse)\r\n fnElse();\r\n skip(\";\");\r\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\r\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\r\n }\r\n }\r\n\r\n function parseType(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next()))\r\n throw illegal(token, \"type name\");\r\n\r\n var type = new Type(token);\r\n ifBlock(type, function parseType_block(token) {\r\n if (parseCommon(type, token))\r\n return;\r\n\r\n switch (token) {\r\n\r\n case \"map\":\r\n parseMapField(type, token);\r\n break;\r\n\r\n case \"required\":\r\n case \"repeated\":\r\n parseField(type, token);\r\n break;\r\n\r\n case \"optional\":\r\n /* istanbul ignore if */\r\n if (isProto3) {\r\n parseField(type, \"proto3_optional\");\r\n } else {\r\n parseField(type, \"optional\");\r\n }\r\n break;\r\n\r\n case \"oneof\":\r\n parseOneOf(type, token);\r\n break;\r\n\r\n case \"extensions\":\r\n readRanges(type.extensions || (type.extensions = []));\r\n break;\r\n\r\n case \"reserved\":\r\n readRanges(type.reserved || (type.reserved = []), true);\r\n break;\r\n\r\n default:\r\n /* istanbul ignore if */\r\n if (!isProto3 || !typeRefRe.test(token))\r\n throw illegal(token);\r\n\r\n push(token);\r\n parseField(type, \"optional\");\r\n break;\r\n }\r\n });\r\n parent.add(type);\r\n }\r\n\r\n function parseField(parent, rule, extend) {\r\n var type = next();\r\n if (type === \"group\") {\r\n parseGroup(parent, rule);\r\n return;\r\n }\r\n // Type names can consume multiple tokens, in multiple variants:\r\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\r\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\r\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\r\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\r\n // Keep reading tokens until we get a type name with no period at the end,\r\n // and the next token does not start with a period.\r\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\r\n type += next();\r\n }\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(type))\r\n throw illegal(type, \"type\");\r\n\r\n var name = next();\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(name))\r\n throw illegal(name, \"name\");\r\n\r\n name = applyCase(name);\r\n skip(\"=\");\r\n\r\n var field = new Field(name, parseId(next()), type, rule, extend);\r\n ifBlock(field, function parseField_block(token) {\r\n\r\n /* istanbul ignore else */\r\n if (token === \"option\") {\r\n parseOption(field, token);\r\n skip(\";\");\r\n } else\r\n throw illegal(token);\r\n\r\n }, function parseField_line() {\r\n parseInlineOptions(field);\r\n });\r\n\r\n if (rule === \"proto3_optional\") {\r\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\r\n var oneof = new OneOf(\"_\" + name);\r\n field.setOption(\"proto3_optional\", true);\r\n oneof.add(field);\r\n parent.add(oneof);\r\n } else {\r\n parent.add(field);\r\n }\r\n\r\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\r\n // parsing proto2 descriptors without the option, where applicable. This must be done for\r\n // all known packable types and anything that could be an enum (= is not a basic type).\r\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\r\n field.setOption(\"packed\", false, /* ifNotSet */ true);\r\n }\r\n\r\n function parseGroup(parent, rule) {\r\n var name = next();\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(name))\r\n throw illegal(name, \"name\");\r\n\r\n var fieldName = util.lcFirst(name);\r\n if (name === fieldName)\r\n name = util.ucFirst(name);\r\n skip(\"=\");\r\n var id = parseId(next());\r\n var type = new Type(name);\r\n type.group = true;\r\n var field = new Field(fieldName, id, name, rule);\r\n field.filename = parse.filename;\r\n ifBlock(type, function parseGroup_block(token) {\r\n switch (token) {\r\n\r\n case \"option\":\r\n parseOption(type, token);\r\n skip(\";\");\r\n break;\r\n\r\n case \"required\":\r\n case \"repeated\":\r\n parseField(type, token);\r\n break;\r\n\r\n case \"optional\":\r\n /* istanbul ignore if */\r\n if (isProto3) {\r\n parseField(type, \"proto3_optional\");\r\n } else {\r\n parseField(type, \"optional\");\r\n }\r\n break;\r\n\r\n case \"message\":\r\n parseType(type, token);\r\n break;\r\n\r\n case \"enum\":\r\n parseEnum(type, token);\r\n break;\r\n\r\n /* istanbul ignore next */\r\n default:\r\n throw illegal(token); // there are no groups with proto3 semantics\r\n }\r\n });\r\n parent.add(type)\r\n .add(field);\r\n }\r\n\r\n function parseMapField(parent) {\r\n skip(\"<\");\r\n var keyType = next();\r\n\r\n /* istanbul ignore if */\r\n if (types.mapKey[keyType] === undefined)\r\n throw illegal(keyType, \"type\");\r\n\r\n skip(\",\");\r\n var valueType = next();\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(valueType))\r\n throw illegal(valueType, \"type\");\r\n\r\n skip(\">\");\r\n var name = next();\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(name))\r\n throw illegal(name, \"name\");\r\n\r\n skip(\"=\");\r\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\r\n ifBlock(field, function parseMapField_block(token) {\r\n\r\n /* istanbul ignore else */\r\n if (token === \"option\") {\r\n parseOption(field, token);\r\n skip(\";\");\r\n } else\r\n throw illegal(token);\r\n\r\n }, function parseMapField_line() {\r\n parseInlineOptions(field);\r\n });\r\n parent.add(field);\r\n }\r\n\r\n function parseOneOf(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next()))\r\n throw illegal(token, \"name\");\r\n\r\n var oneof = new OneOf(applyCase(token));\r\n ifBlock(oneof, function parseOneOf_block(token) {\r\n if (token === \"option\") {\r\n parseOption(oneof, token);\r\n skip(\";\");\r\n } else {\r\n push(token);\r\n parseField(oneof, \"optional\");\r\n }\r\n });\r\n parent.add(oneof);\r\n }\r\n\r\n function parseEnum(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next()))\r\n throw illegal(token, \"name\");\r\n\r\n var enm = new Enum(token);\r\n ifBlock(enm, function parseEnum_block(token) {\r\n switch(token) {\r\n case \"option\":\r\n parseOption(enm, token);\r\n skip(\";\");\r\n break;\r\n\r\n case \"reserved\":\r\n readRanges(enm.reserved || (enm.reserved = []), true);\r\n break;\r\n\r\n default:\r\n parseEnumValue(enm, token);\r\n }\r\n });\r\n parent.add(enm);\r\n }\r\n\r\n function parseEnumValue(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token))\r\n throw illegal(token, \"name\");\r\n\r\n skip(\"=\");\r\n var value = parseId(next(), true),\r\n dummy = {\r\n options: undefined\r\n };\r\n dummy.setOption = function(name, value) {\r\n if (this.options === undefined)\r\n this.options = {};\r\n this.options[name] = value;\r\n };\r\n ifBlock(dummy, function parseEnumValue_block(token) {\r\n\r\n /* istanbul ignore else */\r\n if (token === \"option\") {\r\n parseOption(dummy, token); // skip\r\n skip(\";\");\r\n } else\r\n throw illegal(token);\r\n\r\n }, function parseEnumValue_line() {\r\n parseInlineOptions(dummy); // skip\r\n });\r\n parent.add(token, value, dummy.comment, dummy.options);\r\n }\r\n\r\n function parseOption(parent, token) {\r\n var isCustom = skip(\"(\", true);\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(token = next()))\r\n throw illegal(token, \"name\");\r\n\r\n var name = token;\r\n var option = name;\r\n var propName;\r\n\r\n if (isCustom) {\r\n skip(\")\");\r\n name = \"(\" + name + \")\";\r\n option = name;\r\n token = peek();\r\n if (fqTypeRefRe.test(token)) {\r\n propName = token.slice(1); //remove '.' before property name\r\n name += token;\r\n next();\r\n }\r\n }\r\n skip(\"=\");\r\n var optionValue = parseOptionValue(parent, name);\r\n setParsedOption(parent, option, optionValue, propName);\r\n }\r\n\r\n function parseOptionValue(parent, name) {\r\n // { a: \"foo\" b { c: \"bar\" } }\r\n if (skip(\"{\", true)) {\r\n var objectResult = {};\r\n\r\n while (!skip(\"}\", true)) {\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next())) {\r\n throw illegal(token, \"name\");\r\n }\r\n if (token === null) {\r\n throw illegal(token, \"end of input\");\r\n }\r\n\r\n var value;\r\n var propName = token;\r\n\r\n skip(\":\", true);\r\n\r\n if (peek() === \"{\")\r\n value = parseOptionValue(parent, name + \".\" + token);\r\n else if (peek() === \"[\") {\r\n // option (my_option) = {\r\n // repeated_value: [ \"foo\", \"bar\" ]\r\n // };\r\n value = [];\r\n var lastValue;\r\n if (skip(\"[\", true)) {\r\n do {\r\n lastValue = readValue(true);\r\n value.push(lastValue);\r\n } while (skip(\",\", true));\r\n skip(\"]\");\r\n if (typeof lastValue !== \"undefined\") {\r\n setOption(parent, name + \".\" + token, lastValue);\r\n }\r\n }\r\n } else {\r\n value = readValue(true);\r\n setOption(parent, name + \".\" + token, value);\r\n }\r\n\r\n var prevValue = objectResult[propName];\r\n\r\n if (prevValue)\r\n value = [].concat(prevValue).concat(value);\r\n\r\n objectResult[propName] = value;\r\n\r\n // Semicolons and commas can be optional\r\n skip(\",\", true);\r\n skip(\";\", true);\r\n }\r\n\r\n return objectResult;\r\n }\r\n\r\n var simpleValue = readValue(true);\r\n setOption(parent, name, simpleValue);\r\n return simpleValue;\r\n // Does not enforce a delimiter to be universal\r\n }\r\n\r\n function setOption(parent, name, value) {\r\n if (parent.setOption)\r\n parent.setOption(name, value);\r\n }\r\n\r\n function setParsedOption(parent, name, value, propName) {\r\n if (parent.setParsedOption)\r\n parent.setParsedOption(name, value, propName);\r\n }\r\n\r\n function parseInlineOptions(parent) {\r\n if (skip(\"[\", true)) {\r\n do {\r\n parseOption(parent, \"option\");\r\n } while (skip(\",\", true));\r\n skip(\"]\");\r\n }\r\n return parent;\r\n }\r\n\r\n function parseService(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next()))\r\n throw illegal(token, \"service name\");\r\n\r\n var service = new Service(token);\r\n ifBlock(service, function parseService_block(token) {\r\n if (parseCommon(service, token))\r\n return;\r\n\r\n /* istanbul ignore else */\r\n if (token === \"rpc\")\r\n parseMethod(service, token);\r\n else\r\n throw illegal(token);\r\n });\r\n parent.add(service);\r\n }\r\n\r\n function parseMethod(parent, token) {\r\n // Get the comment of the preceding line now (if one exists) in case the\r\n // method is defined across multiple lines.\r\n var commentText = cmnt();\r\n\r\n var type = token;\r\n\r\n /* istanbul ignore if */\r\n if (!nameRe.test(token = next()))\r\n throw illegal(token, \"name\");\r\n\r\n var name = token,\r\n requestType, requestStream,\r\n responseType, responseStream;\r\n\r\n skip(\"(\");\r\n if (skip(\"stream\", true))\r\n requestStream = true;\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(token = next()))\r\n throw illegal(token);\r\n\r\n requestType = token;\r\n skip(\")\"); skip(\"returns\"); skip(\"(\");\r\n if (skip(\"stream\", true))\r\n responseStream = true;\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(token = next()))\r\n throw illegal(token);\r\n\r\n responseType = token;\r\n skip(\")\");\r\n\r\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\r\n method.comment = commentText;\r\n ifBlock(method, function parseMethod_block(token) {\r\n\r\n /* istanbul ignore else */\r\n if (token === \"option\") {\r\n parseOption(method, token);\r\n skip(\";\");\r\n } else\r\n throw illegal(token);\r\n\r\n });\r\n parent.add(method);\r\n }\r\n\r\n function parseExtension(parent, token) {\r\n\r\n /* istanbul ignore if */\r\n if (!typeRefRe.test(token = next()))\r\n throw illegal(token, \"reference\");\r\n\r\n var reference = token;\r\n ifBlock(null, function parseExtension_block(token) {\r\n switch (token) {\r\n\r\n case \"required\":\r\n case \"repeated\":\r\n parseField(parent, token, reference);\r\n break;\r\n\r\n case \"optional\":\r\n /* istanbul ignore if */\r\n if (isProto3) {\r\n parseField(parent, \"proto3_optional\", reference);\r\n } else {\r\n parseField(parent, \"optional\", reference);\r\n }\r\n break;\r\n\r\n default:\r\n /* istanbul ignore if */\r\n if (!isProto3 || !typeRefRe.test(token))\r\n throw illegal(token);\r\n push(token);\r\n parseField(parent, \"optional\", reference);\r\n break;\r\n }\r\n });\r\n }\r\n\r\n var token;\r\n while ((token = next()) !== null) {\r\n switch (token) {\r\n\r\n case \"package\":\r\n\r\n /* istanbul ignore if */\r\n if (!head)\r\n throw illegal(token);\r\n\r\n parsePackage();\r\n break;\r\n\r\n case \"import\":\r\n\r\n /* istanbul ignore if */\r\n if (!head)\r\n throw illegal(token);\r\n\r\n parseImport();\r\n break;\r\n\r\n case \"syntax\":\r\n\r\n /* istanbul ignore if */\r\n if (!head)\r\n throw illegal(token);\r\n\r\n parseSyntax();\r\n break;\r\n\r\n case \"option\":\r\n\r\n parseOption(ptr, token);\r\n skip(\";\");\r\n break;\r\n\r\n default:\r\n\r\n /* istanbul ignore else */\r\n if (parseCommon(ptr, token)) {\r\n head = false;\r\n continue;\r\n }\r\n\r\n /* istanbul ignore next */\r\n throw illegal(token);\r\n }\r\n }\r\n\r\n parse.filename = null;\r\n return {\r\n \"package\" : pkg,\r\n \"imports\" : imports,\r\n weakImports : weakImports,\r\n syntax : syntax,\r\n root : root\r\n };\r\n}\r\n\r\n/**\r\n * Parses the given .proto source and returns an object with the parsed contents.\r\n * @name parse\r\n * @function\r\n * @param {string} source Source contents\r\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r\n * @returns {IParserResult} Parser result\r\n * @property {string} filename=null Currently processing file name for error reporting, if known\r\n * @property {IParseOptions} defaults Default {@link IParseOptions}\r\n * @variation 2\r\n */\r\n","\"use strict\";\r\nmodule.exports = Reader;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\nvar BufferReader; // cyclic\r\n\r\nvar LongBits = util.LongBits,\r\n utf8 = util.utf8;\r\n\r\n/* istanbul ignore next */\r\nfunction indexOutOfRange(reader, writeLength) {\r\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\r\n}\r\n\r\n/**\r\n * Constructs a new reader instance using the specified buffer.\r\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\r\n * @constructor\r\n * @param {Uint8Array} buffer Buffer to read from\r\n */\r\nfunction Reader(buffer) {\r\n\r\n /**\r\n * Read buffer.\r\n * @type {Uint8Array}\r\n */\r\n this.buf = buffer;\r\n\r\n /**\r\n * Read buffer position.\r\n * @type {number}\r\n */\r\n this.pos = 0;\r\n\r\n /**\r\n * Read buffer length.\r\n * @type {number}\r\n */\r\n this.len = buffer.length;\r\n}\r\n\r\nvar create_array = typeof Uint8Array !== \"undefined\"\r\n ? function create_typed_array(buffer) {\r\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\r\n return new Reader(buffer);\r\n throw Error(\"illegal buffer\");\r\n }\r\n /* istanbul ignore next */\r\n : function create_array(buffer) {\r\n if (Array.isArray(buffer))\r\n return new Reader(buffer);\r\n throw Error(\"illegal buffer\");\r\n };\r\n\r\nvar create = function create() {\r\n return util.Buffer\r\n ? function create_buffer_setup(buffer) {\r\n return (Reader.create = function create_buffer(buffer) {\r\n return util.Buffer.isBuffer(buffer)\r\n ? new BufferReader(buffer)\r\n /* istanbul ignore next */\r\n : create_array(buffer);\r\n })(buffer);\r\n }\r\n /* istanbul ignore next */\r\n : create_array;\r\n};\r\n\r\n/**\r\n * Creates a new reader using the specified buffer.\r\n * @function\r\n * @param {Uint8Array|Buffer} buffer Buffer to read from\r\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\r\n * @throws {Error} If `buffer` is not a valid buffer\r\n */\r\nReader.create = create();\r\n\r\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\r\n\r\n/**\r\n * Reads a varint as an unsigned 32 bit value.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.uint32 = (function read_uint32_setup() {\r\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\r\n return function read_uint32() {\r\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n\r\n /* istanbul ignore if */\r\n if ((this.pos += 5) > this.len) {\r\n this.pos = this.len;\r\n throw indexOutOfRange(this, 10);\r\n }\r\n return value;\r\n };\r\n})();\r\n\r\n/**\r\n * Reads a varint as a signed 32 bit value.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.int32 = function read_int32() {\r\n return this.uint32() | 0;\r\n};\r\n\r\n/**\r\n * Reads a zig-zag encoded varint as a signed 32 bit value.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.sint32 = function read_sint32() {\r\n var value = this.uint32();\r\n return value >>> 1 ^ -(value & 1) | 0;\r\n};\r\n\r\n/* eslint-disable no-invalid-this */\r\n\r\nfunction readLongVarint() {\r\n // tends to deopt with local vars for octet etc.\r\n var bits = new LongBits(0, 0);\r\n var i = 0;\r\n if (this.len - this.pos > 4) { // fast route (lo)\r\n for (; i < 4; ++i) {\r\n // 1st..4th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n // 5th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n i = 0;\r\n } else {\r\n for (; i < 3; ++i) {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n // 1st..3th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n // 4th\r\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\r\n return bits;\r\n }\r\n if (this.len - this.pos > 4) { // fast route (hi)\r\n for (; i < 5; ++i) {\r\n // 6th..10th\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n } else {\r\n for (; i < 5; ++i) {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n // 6th..10th\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n }\r\n /* istanbul ignore next */\r\n throw Error(\"invalid varint encoding\");\r\n}\r\n\r\n/* eslint-enable no-invalid-this */\r\n\r\n/**\r\n * Reads a varint as a signed 64 bit value.\r\n * @name Reader#int64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a varint as an unsigned 64 bit value.\r\n * @name Reader#uint64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a zig-zag encoded varint as a signed 64 bit value.\r\n * @name Reader#sint64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a varint as a boolean.\r\n * @returns {boolean} Value read\r\n */\r\nReader.prototype.bool = function read_bool() {\r\n return this.uint32() !== 0;\r\n};\r\n\r\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\r\n return (buf[end - 4]\r\n | buf[end - 3] << 8\r\n | buf[end - 2] << 16\r\n | buf[end - 1] << 24) >>> 0;\r\n}\r\n\r\n/**\r\n * Reads fixed 32 bits as an unsigned 32 bit integer.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.fixed32 = function read_fixed32() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n return readFixed32_end(this.buf, this.pos += 4);\r\n};\r\n\r\n/**\r\n * Reads fixed 32 bits as a signed 32 bit integer.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.sfixed32 = function read_sfixed32() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n return readFixed32_end(this.buf, this.pos += 4) | 0;\r\n};\r\n\r\n/* eslint-disable no-invalid-this */\r\n\r\nfunction readFixed64(/* this: Reader */) {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 8 > this.len)\r\n throw indexOutOfRange(this, 8);\r\n\r\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\r\n}\r\n\r\n/* eslint-enable no-invalid-this */\r\n\r\n/**\r\n * Reads fixed 64 bits.\r\n * @name Reader#fixed64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads zig-zag encoded fixed 64 bits.\r\n * @name Reader#sfixed64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a float (32 bit) as a number.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.float = function read_float() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n var value = util.float.readFloatLE(this.buf, this.pos);\r\n this.pos += 4;\r\n return value;\r\n};\r\n\r\n/**\r\n * Reads a double (64 bit float) as a number.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.double = function read_double() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 8 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n var value = util.float.readDoubleLE(this.buf, this.pos);\r\n this.pos += 8;\r\n return value;\r\n};\r\n\r\n/**\r\n * Reads a sequence of bytes preceeded by its length as a varint.\r\n * @returns {Uint8Array} Value read\r\n */\r\nReader.prototype.bytes = function read_bytes() {\r\n var length = this.uint32(),\r\n start = this.pos,\r\n end = this.pos + length;\r\n\r\n /* istanbul ignore if */\r\n if (end > this.len)\r\n throw indexOutOfRange(this, length);\r\n\r\n this.pos += length;\r\n if (Array.isArray(this.buf)) // plain array\r\n return this.buf.slice(start, end);\r\n\r\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\r\n var nativeBuffer = util.Buffer;\r\n return nativeBuffer\r\n ? nativeBuffer.alloc(0)\r\n : new this.buf.constructor(0);\r\n }\r\n return this._slice.call(this.buf, start, end);\r\n};\r\n\r\n/**\r\n * Reads a string preceeded by its byte length as a varint.\r\n * @returns {string} Value read\r\n */\r\nReader.prototype.string = function read_string() {\r\n var bytes = this.bytes();\r\n return utf8.read(bytes, 0, bytes.length);\r\n};\r\n\r\n/**\r\n * Skips the specified number of bytes if specified, otherwise skips a varint.\r\n * @param {number} [length] Length if known, otherwise a varint is assumed\r\n * @returns {Reader} `this`\r\n */\r\nReader.prototype.skip = function skip(length) {\r\n if (typeof length === \"number\") {\r\n /* istanbul ignore if */\r\n if (this.pos + length > this.len)\r\n throw indexOutOfRange(this, length);\r\n this.pos += length;\r\n } else {\r\n do {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n } while (this.buf[this.pos++] & 128);\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Skips the next element of the specified wire type.\r\n * @param {number} wireType Wire type received\r\n * @returns {Reader} `this`\r\n */\r\nReader.prototype.skipType = function(wireType) {\r\n switch (wireType) {\r\n case 0:\r\n this.skip();\r\n break;\r\n case 1:\r\n this.skip(8);\r\n break;\r\n case 2:\r\n this.skip(this.uint32());\r\n break;\r\n case 3:\r\n while ((wireType = this.uint32() & 7) !== 4) {\r\n this.skipType(wireType);\r\n }\r\n break;\r\n case 5:\r\n this.skip(4);\r\n break;\r\n\r\n /* istanbul ignore next */\r\n default:\r\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\r\n }\r\n return this;\r\n};\r\n\r\nReader._configure = function(BufferReader_) {\r\n BufferReader = BufferReader_;\r\n Reader.create = create();\r\n BufferReader._configure();\r\n\r\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\r\n util.merge(Reader.prototype, {\r\n\r\n int64: function read_int64() {\r\n return readLongVarint.call(this)[fn](false);\r\n },\r\n\r\n uint64: function read_uint64() {\r\n return readLongVarint.call(this)[fn](true);\r\n },\r\n\r\n sint64: function read_sint64() {\r\n return readLongVarint.call(this).zzDecode()[fn](false);\r\n },\r\n\r\n fixed64: function read_fixed64() {\r\n return readFixed64.call(this)[fn](true);\r\n },\r\n\r\n sfixed64: function read_sfixed64() {\r\n return readFixed64.call(this)[fn](false);\r\n }\r\n\r\n });\r\n};\r\n","\"use strict\";\r\nmodule.exports = BufferReader;\r\n\r\n// extends Reader\r\nvar Reader = require(\"./reader\");\r\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\n/**\r\n * Constructs a new buffer reader instance.\r\n * @classdesc Wire format reader using node buffers.\r\n * @extends Reader\r\n * @constructor\r\n * @param {Buffer} buffer Buffer to read from\r\n */\r\nfunction BufferReader(buffer) {\r\n Reader.call(this, buffer);\r\n\r\n /**\r\n * Read buffer.\r\n * @name BufferReader#buf\r\n * @type {Buffer}\r\n */\r\n}\r\n\r\nBufferReader._configure = function () {\r\n /* istanbul ignore else */\r\n if (util.Buffer)\r\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBufferReader.prototype.string = function read_string_buffer() {\r\n var len = this.uint32(); // modifies pos\r\n return this.buf.utf8Slice\r\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\r\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\r\n};\r\n\r\n/**\r\n * Reads a sequence of bytes preceeded by its length as a varint.\r\n * @name BufferReader#bytes\r\n * @function\r\n * @returns {Buffer} Value read\r\n */\r\n\r\nBufferReader._configure();\r\n","\"use strict\";\r\nmodule.exports = Root;\r\n\r\n// extends Namespace\r\nvar Namespace = require(\"./namespace\");\r\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\r\n\r\nvar Field = require(\"./field\"),\r\n Enum = require(\"./enum\"),\r\n OneOf = require(\"./oneof\"),\r\n util = require(\"./util\");\r\n\r\nvar Type, // cyclic\r\n parse, // might be excluded\r\n common; // \"\r\n\r\n/**\r\n * Constructs a new root namespace instance.\r\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\r\n * @extends NamespaceBase\r\n * @constructor\r\n * @param {Object.} [options] Top level options\r\n */\r\nfunction Root(options) {\r\n Namespace.call(this, \"\", options);\r\n\r\n /**\r\n * Deferred extension fields.\r\n * @type {Field[]}\r\n */\r\n this.deferred = [];\r\n\r\n /**\r\n * Resolved file names of loaded files.\r\n * @type {string[]}\r\n */\r\n this.files = [];\r\n}\r\n\r\n/**\r\n * Loads a namespace descriptor into a root namespace.\r\n * @param {INamespace} json Nameespace descriptor\r\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\r\n * @returns {Root} Root namespace\r\n */\r\nRoot.fromJSON = function fromJSON(json, root) {\r\n if (!root)\r\n root = new Root();\r\n if (json.options)\r\n root.setOptions(json.options);\r\n return root.addJSON(json.nested);\r\n};\r\n\r\n/**\r\n * Resolves the path of an imported file, relative to the importing origin.\r\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\r\n * @function\r\n * @param {string} origin The file name of the importing file\r\n * @param {string} target The file name being imported\r\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\r\n */\r\nRoot.prototype.resolvePath = util.path.resolve;\r\n\r\n/**\r\n * Fetch content from file path or url\r\n * This method exists so you can override it with your own logic.\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nRoot.prototype.fetch = util.fetch;\r\n\r\n// A symbol-like function to safely signal synchronous loading\r\n/* istanbul ignore next */\r\nfunction SYNC() {} // eslint-disable-line no-empty-function\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\r\n * @param {string|string[]} filename Names of one or multiple files to load\r\n * @param {IParseOptions} options Parse options\r\n * @param {LoadCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nRoot.prototype.load = function load(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = undefined;\r\n }\r\n var self = this;\r\n if (!callback)\r\n return util.asPromise(load, self, filename, options);\r\n\r\n var sync = callback === SYNC; // undocumented\r\n\r\n // Finishes loading by calling the callback (exactly once)\r\n function finish(err, root) {\r\n /* istanbul ignore if */\r\n if (!callback)\r\n return;\r\n if (sync)\r\n throw err;\r\n var cb = callback;\r\n callback = null;\r\n cb(err, root);\r\n }\r\n\r\n // Bundled definition existence checking\r\n function getBundledFileName(filename) {\r\n var idx = filename.lastIndexOf(\"google/protobuf/\");\r\n if (idx > -1) {\r\n var altname = filename.substring(idx);\r\n if (altname in common) return altname;\r\n }\r\n return null;\r\n }\r\n\r\n // Processes a single file\r\n function process(filename, source) {\r\n try {\r\n if (util.isString(source) && source.charAt(0) === \"{\")\r\n source = JSON.parse(source);\r\n if (!util.isString(source))\r\n self.setOptions(source.options).addJSON(source.nested);\r\n else {\r\n parse.filename = filename;\r\n var parsed = parse(source, self, options),\r\n resolved,\r\n i = 0;\r\n if (parsed.imports)\r\n for (; i < parsed.imports.length; ++i)\r\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\r\n fetch(resolved);\r\n if (parsed.weakImports)\r\n for (i = 0; i < parsed.weakImports.length; ++i)\r\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\r\n fetch(resolved, true);\r\n }\r\n } catch (err) {\r\n finish(err);\r\n }\r\n if (!sync && !queued)\r\n finish(null, self); // only once anyway\r\n }\r\n\r\n // Fetches a single file\r\n function fetch(filename, weak) {\r\n filename = getBundledFileName(filename) || filename;\r\n\r\n // Skip if already loaded / attempted\r\n if (self.files.indexOf(filename) > -1)\r\n return;\r\n self.files.push(filename);\r\n\r\n // Shortcut bundled definitions\r\n if (filename in common) {\r\n if (sync)\r\n process(filename, common[filename]);\r\n else {\r\n ++queued;\r\n setTimeout(function() {\r\n --queued;\r\n process(filename, common[filename]);\r\n });\r\n }\r\n return;\r\n }\r\n\r\n // Otherwise fetch from disk or network\r\n if (sync) {\r\n var source;\r\n try {\r\n source = util.fs.readFileSync(filename).toString(\"utf8\");\r\n } catch (err) {\r\n if (!weak)\r\n finish(err);\r\n return;\r\n }\r\n process(filename, source);\r\n } else {\r\n ++queued;\r\n self.fetch(filename, function(err, source) {\r\n --queued;\r\n /* istanbul ignore if */\r\n if (!callback)\r\n return; // terminated meanwhile\r\n if (err) {\r\n /* istanbul ignore else */\r\n if (!weak)\r\n finish(err);\r\n else if (!queued) // can't be covered reliably\r\n finish(null, self);\r\n return;\r\n }\r\n process(filename, source);\r\n });\r\n }\r\n }\r\n var queued = 0;\r\n\r\n // Assembling the root namespace doesn't require working type\r\n // references anymore, so we can load everything in parallel\r\n if (util.isString(filename))\r\n filename = [ filename ];\r\n for (var i = 0, resolved; i < filename.length; ++i)\r\n if (resolved = self.resolvePath(\"\", filename[i]))\r\n fetch(resolved);\r\n\r\n if (sync)\r\n return self;\r\n if (!queued)\r\n finish(null, self);\r\n return undefined;\r\n};\r\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\r\n * @function Root#load\r\n * @param {string|string[]} filename Names of one or multiple files to load\r\n * @param {LoadCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n// function load(filename:string, callback:LoadCallback):undefined\r\n\r\n/**\r\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\r\n * @function Root#load\r\n * @param {string|string[]} filename Names of one or multiple files to load\r\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n// function load(filename:string, [options:IParseOptions]):Promise\r\n\r\n/**\r\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\r\n * @function Root#loadSync\r\n * @param {string|string[]} filename Names of one or multiple files to load\r\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r\n * @returns {Root} Root namespace\r\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\r\n */\r\nRoot.prototype.loadSync = function loadSync(filename, options) {\r\n if (!util.isNode)\r\n throw Error(\"not supported\");\r\n return this.load(filename, options, SYNC);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nRoot.prototype.resolveAll = function resolveAll() {\r\n if (this.deferred.length)\r\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\r\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\r\n }).join(\", \"));\r\n return Namespace.prototype.resolveAll.call(this);\r\n};\r\n\r\n// only uppercased (and thus conflict-free) children are exposed, see below\r\nvar exposeRe = /^[A-Z]/;\r\n\r\n/**\r\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\r\n * @param {Root} root Root instance\r\n * @param {Field} field Declaring extension field witin the declaring type\r\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\r\n * @inner\r\n * @ignore\r\n */\r\nfunction tryHandleExtension(root, field) {\r\n var extendedType = field.parent.lookup(field.extend);\r\n if (extendedType) {\r\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\r\n //do not allow to extend same field twice to prevent the error\r\n if (extendedType.get(sisterField.name)) {\r\n return true;\r\n }\r\n sisterField.declaringField = field;\r\n field.extensionField = sisterField;\r\n extendedType.add(sisterField);\r\n return true;\r\n }\r\n return false;\r\n}\r\n\r\n/**\r\n * Called when any object is added to this root or its sub-namespaces.\r\n * @param {ReflectionObject} object Object added\r\n * @returns {undefined}\r\n * @private\r\n */\r\nRoot.prototype._handleAdd = function _handleAdd(object) {\r\n if (object instanceof Field) {\r\n\r\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\r\n if (!tryHandleExtension(this, object))\r\n this.deferred.push(object);\r\n\r\n } else if (object instanceof Enum) {\r\n\r\n if (exposeRe.test(object.name))\r\n object.parent[object.name] = object.values; // expose enum values as property of its parent\r\n\r\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\r\n\r\n if (object instanceof Type) // Try to handle any deferred extensions\r\n for (var i = 0; i < this.deferred.length;)\r\n if (tryHandleExtension(this, this.deferred[i]))\r\n this.deferred.splice(i, 1);\r\n else\r\n ++i;\r\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\r\n this._handleAdd(object._nestedArray[j]);\r\n if (exposeRe.test(object.name))\r\n object.parent[object.name] = object; // expose namespace as property of its parent\r\n }\r\n\r\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\r\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\r\n // a static module with reflection-based solutions where the condition is met.\r\n};\r\n\r\n/**\r\n * Called when any object is removed from this root or its sub-namespaces.\r\n * @param {ReflectionObject} object Object removed\r\n * @returns {undefined}\r\n * @private\r\n */\r\nRoot.prototype._handleRemove = function _handleRemove(object) {\r\n if (object instanceof Field) {\r\n\r\n if (/* an extension field */ object.extend !== undefined) {\r\n if (/* already handled */ object.extensionField) { // remove its sister field\r\n object.extensionField.parent.remove(object.extensionField);\r\n object.extensionField = null;\r\n } else { // cancel the extension\r\n var index = this.deferred.indexOf(object);\r\n /* istanbul ignore else */\r\n if (index > -1)\r\n this.deferred.splice(index, 1);\r\n }\r\n }\r\n\r\n } else if (object instanceof Enum) {\r\n\r\n if (exposeRe.test(object.name))\r\n delete object.parent[object.name]; // unexpose enum values\r\n\r\n } else if (object instanceof Namespace) {\r\n\r\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\r\n this._handleRemove(object._nestedArray[i]);\r\n\r\n if (exposeRe.test(object.name))\r\n delete object.parent[object.name]; // unexpose namespaces\r\n\r\n }\r\n};\r\n\r\n// Sets up cyclic dependencies (called in index-light)\r\nRoot._configure = function(Type_, parse_, common_) {\r\n Type = Type_;\r\n parse = parse_;\r\n common = common_;\r\n};\r\n","\"use strict\";\r\nmodule.exports = {};\r\n\r\n/**\r\n * Named roots.\r\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\r\n * Can also be used manually to make roots available across modules.\r\n * @name roots\r\n * @type {Object.}\r\n * @example\r\n * // pbjs -r myroot -o compiled.js ...\r\n *\r\n * // in another module:\r\n * require(\"./compiled.js\");\r\n *\r\n * // in any subsequent module:\r\n * var root = protobuf.roots[\"myroot\"];\r\n */\r\n","\"use strict\";\r\n\r\n/**\r\n * Streaming RPC helpers.\r\n * @namespace\r\n */\r\nvar rpc = exports;\r\n\r\n/**\r\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\r\n * @typedef RPCImpl\r\n * @type {function}\r\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\r\n * @param {Uint8Array} requestData Request data\r\n * @param {RPCImplCallback} callback Callback function\r\n * @returns {undefined}\r\n * @example\r\n * function rpcImpl(method, requestData, callback) {\r\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\r\n * throw Error(\"no such method\");\r\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\r\n * callback(err, responseData);\r\n * });\r\n * }\r\n */\r\n\r\n/**\r\n * Node-style callback as used by {@link RPCImpl}.\r\n * @typedef RPCImplCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any, otherwise `null`\r\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\nrpc.Service = require(\"./rpc/service\");\r\n","\"use strict\";\r\nmodule.exports = Service;\r\n\r\nvar util = require(\"../util/minimal\");\r\n\r\n// Extends EventEmitter\r\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\r\n\r\n/**\r\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\r\n *\r\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\r\n * @typedef rpc.ServiceMethodCallback\r\n * @template TRes extends Message\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {TRes} [response] Response message\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\r\n * @typedef rpc.ServiceMethod\r\n * @template TReq extends Message\r\n * @template TRes extends Message\r\n * @type {function}\r\n * @param {TReq|Properties} request Request message or plain object\r\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\r\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\r\n */\r\n\r\n/**\r\n * Constructs a new RPC service instance.\r\n * @classdesc An RPC service as returned by {@link Service#create}.\r\n * @exports rpc.Service\r\n * @extends util.EventEmitter\r\n * @constructor\r\n * @param {RPCImpl} rpcImpl RPC implementation\r\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\r\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\r\n */\r\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\r\n\r\n if (typeof rpcImpl !== \"function\")\r\n throw TypeError(\"rpcImpl must be a function\");\r\n\r\n util.EventEmitter.call(this);\r\n\r\n /**\r\n * RPC implementation. Becomes `null` once the service is ended.\r\n * @type {RPCImpl|null}\r\n */\r\n this.rpcImpl = rpcImpl;\r\n\r\n /**\r\n * Whether requests are length-delimited.\r\n * @type {boolean}\r\n */\r\n this.requestDelimited = Boolean(requestDelimited);\r\n\r\n /**\r\n * Whether responses are length-delimited.\r\n * @type {boolean}\r\n */\r\n this.responseDelimited = Boolean(responseDelimited);\r\n}\r\n\r\n/**\r\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\r\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\r\n * @param {Constructor} requestCtor Request constructor\r\n * @param {Constructor} responseCtor Response constructor\r\n * @param {TReq|Properties} request Request message or plain object\r\n * @param {rpc.ServiceMethodCallback} callback Service callback\r\n * @returns {undefined}\r\n * @template TReq extends Message\r\n * @template TRes extends Message\r\n */\r\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\r\n\r\n if (!request)\r\n throw TypeError(\"request must be specified\");\r\n\r\n var self = this;\r\n if (!callback)\r\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\r\n\r\n if (!self.rpcImpl) {\r\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\r\n return undefined;\r\n }\r\n\r\n try {\r\n return self.rpcImpl(\r\n method,\r\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\r\n function rpcCallback(err, response) {\r\n\r\n if (err) {\r\n self.emit(\"error\", err, method);\r\n return callback(err);\r\n }\r\n\r\n if (response === null) {\r\n self.end(/* endedByRPC */ true);\r\n return undefined;\r\n }\r\n\r\n if (!(response instanceof responseCtor)) {\r\n try {\r\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\r\n } catch (err) {\r\n self.emit(\"error\", err, method);\r\n return callback(err);\r\n }\r\n }\r\n\r\n self.emit(\"data\", response, method);\r\n return callback(null, response);\r\n }\r\n );\r\n } catch (err) {\r\n self.emit(\"error\", err, method);\r\n setTimeout(function() { callback(err); }, 0);\r\n return undefined;\r\n }\r\n};\r\n\r\n/**\r\n * Ends this service and emits the `end` event.\r\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\r\n * @returns {rpc.Service} `this`\r\n */\r\nService.prototype.end = function end(endedByRPC) {\r\n if (this.rpcImpl) {\r\n if (!endedByRPC) // signal end to rpcImpl\r\n this.rpcImpl(null, null, null);\r\n this.rpcImpl = null;\r\n this.emit(\"end\").off();\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = Service;\r\n\r\n// extends Namespace\r\nvar Namespace = require(\"./namespace\");\r\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\r\n\r\nvar Method = require(\"./method\"),\r\n util = require(\"./util\"),\r\n rpc = require(\"./rpc\");\r\n\r\n/**\r\n * Constructs a new service instance.\r\n * @classdesc Reflected service.\r\n * @extends NamespaceBase\r\n * @constructor\r\n * @param {string} name Service name\r\n * @param {Object.} [options] Service options\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nfunction Service(name, options) {\r\n Namespace.call(this, name, options);\r\n\r\n /**\r\n * Service methods.\r\n * @type {Object.}\r\n */\r\n this.methods = {}; // toJSON, marker\r\n\r\n /**\r\n * Cached methods as an array.\r\n * @type {Method[]|null}\r\n * @private\r\n */\r\n this._methodsArray = null;\r\n}\r\n\r\n/**\r\n * Service descriptor.\r\n * @interface IService\r\n * @extends INamespace\r\n * @property {Object.} methods Method descriptors\r\n */\r\n\r\n/**\r\n * Constructs a service from a service descriptor.\r\n * @param {string} name Service name\r\n * @param {IService} json Service descriptor\r\n * @returns {Service} Created service\r\n * @throws {TypeError} If arguments are invalid\r\n */\r\nService.fromJSON = function fromJSON(name, json) {\r\n var service = new Service(name, json.options);\r\n /* istanbul ignore else */\r\n if (json.methods)\r\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\r\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\r\n if (json.nested)\r\n service.addJSON(json.nested);\r\n service.comment = json.comment;\r\n return service;\r\n};\r\n\r\n/**\r\n * Converts this service to a service descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IService} Service descriptor\r\n */\r\nService.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"options\" , inherited && inherited.options || undefined,\r\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\r\n \"nested\" , inherited && inherited.nested || undefined,\r\n \"comment\" , keepComments ? this.comment : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * Methods of this service as an array for iteration.\r\n * @name Service#methodsArray\r\n * @type {Method[]}\r\n * @readonly\r\n */\r\nObject.defineProperty(Service.prototype, \"methodsArray\", {\r\n get: function() {\r\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\r\n }\r\n});\r\n\r\nfunction clearCache(service) {\r\n service._methodsArray = null;\r\n return service;\r\n}\r\n\r\n/**\r\n * @override\r\n */\r\nService.prototype.get = function get(name) {\r\n return this.methods[name]\r\n || Namespace.prototype.get.call(this, name);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nService.prototype.resolveAll = function resolveAll() {\r\n var methods = this.methodsArray;\r\n for (var i = 0; i < methods.length; ++i)\r\n methods[i].resolve();\r\n return Namespace.prototype.resolve.call(this);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nService.prototype.add = function add(object) {\r\n\r\n /* istanbul ignore if */\r\n if (this.get(object.name))\r\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\r\n\r\n if (object instanceof Method) {\r\n this.methods[object.name] = object;\r\n object.parent = this;\r\n return clearCache(this);\r\n }\r\n return Namespace.prototype.add.call(this, object);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nService.prototype.remove = function remove(object) {\r\n if (object instanceof Method) {\r\n\r\n /* istanbul ignore if */\r\n if (this.methods[object.name] !== object)\r\n throw Error(object + \" is not a member of \" + this);\r\n\r\n delete this.methods[object.name];\r\n object.parent = null;\r\n return clearCache(this);\r\n }\r\n return Namespace.prototype.remove.call(this, object);\r\n};\r\n\r\n/**\r\n * Creates a runtime service using the specified rpc implementation.\r\n * @param {RPCImpl} rpcImpl RPC implementation\r\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\r\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\r\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\r\n */\r\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\r\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\r\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\r\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\r\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\r\n m: method,\r\n q: method.resolvedRequestType.ctor,\r\n s: method.resolvedResponseType.ctor\r\n });\r\n }\r\n return rpcService;\r\n};\r\n","\"use strict\";\r\nmodule.exports = tokenize;\r\n\r\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\r\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\r\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\r\n\r\nvar setCommentRe = /^ *[*/]+ */,\r\n setCommentAltRe = /^\\s*\\*?\\/*/,\r\n setCommentSplitRe = /\\n/g,\r\n whitespaceRe = /\\s/,\r\n unescapeRe = /\\\\(.?)/g;\r\n\r\nvar unescapeMap = {\r\n \"0\": \"\\0\",\r\n \"r\": \"\\r\",\r\n \"n\": \"\\n\",\r\n \"t\": \"\\t\"\r\n};\r\n\r\n/**\r\n * Unescapes a string.\r\n * @param {string} str String to unescape\r\n * @returns {string} Unescaped string\r\n * @property {Object.} map Special characters map\r\n * @memberof tokenize\r\n */\r\nfunction unescape(str) {\r\n return str.replace(unescapeRe, function($0, $1) {\r\n switch ($1) {\r\n case \"\\\\\":\r\n case \"\":\r\n return $1;\r\n default:\r\n return unescapeMap[$1] || \"\";\r\n }\r\n });\r\n}\r\n\r\ntokenize.unescape = unescape;\r\n\r\n/**\r\n * Gets the next token and advances.\r\n * @typedef TokenizerHandleNext\r\n * @type {function}\r\n * @returns {string|null} Next token or `null` on eof\r\n */\r\n\r\n/**\r\n * Peeks for the next token.\r\n * @typedef TokenizerHandlePeek\r\n * @type {function}\r\n * @returns {string|null} Next token or `null` on eof\r\n */\r\n\r\n/**\r\n * Pushes a token back to the stack.\r\n * @typedef TokenizerHandlePush\r\n * @type {function}\r\n * @param {string} token Token\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Skips the next token.\r\n * @typedef TokenizerHandleSkip\r\n * @type {function}\r\n * @param {string} expected Expected token\r\n * @param {boolean} [optional=false] If optional\r\n * @returns {boolean} Whether the token matched\r\n * @throws {Error} If the token didn't match and is not optional\r\n */\r\n\r\n/**\r\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\r\n * @typedef TokenizerHandleCmnt\r\n * @type {function}\r\n * @param {number} [line] Line number\r\n * @returns {string|null} Comment text or `null` if none\r\n */\r\n\r\n/**\r\n * Handle object returned from {@link tokenize}.\r\n * @interface ITokenizerHandle\r\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\r\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\r\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\r\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\r\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\r\n * @property {number} line Current line number\r\n */\r\n\r\n/**\r\n * Tokenizes the given .proto source and returns an object with useful utility functions.\r\n * @param {string} source Source contents\r\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\r\n * @returns {ITokenizerHandle} Tokenizer handle\r\n */\r\nfunction tokenize(source, alternateCommentMode) {\r\n /* eslint-disable callback-return */\r\n source = source.toString();\r\n\r\n var offset = 0,\r\n length = source.length,\r\n line = 1,\r\n lastCommentLine = 0,\r\n comments = {};\r\n\r\n var stack = [];\r\n\r\n var stringDelim = null;\r\n\r\n /* istanbul ignore next */\r\n /**\r\n * Creates an error for illegal syntax.\r\n * @param {string} subject Subject\r\n * @returns {Error} Error created\r\n * @inner\r\n */\r\n function illegal(subject) {\r\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\r\n }\r\n\r\n /**\r\n * Reads a string till its end.\r\n * @returns {string} String read\r\n * @inner\r\n */\r\n function readString() {\r\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\r\n re.lastIndex = offset - 1;\r\n var match = re.exec(source);\r\n if (!match)\r\n throw illegal(\"string\");\r\n offset = re.lastIndex;\r\n push(stringDelim);\r\n stringDelim = null;\r\n return unescape(match[1]);\r\n }\r\n\r\n /**\r\n * Gets the character at `pos` within the source.\r\n * @param {number} pos Position\r\n * @returns {string} Character\r\n * @inner\r\n */\r\n function charAt(pos) {\r\n return source.charAt(pos);\r\n }\r\n\r\n /**\r\n * Sets the current comment text.\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @param {boolean} isLeading set if a leading comment\r\n * @returns {undefined}\r\n * @inner\r\n */\r\n function setComment(start, end, isLeading) {\r\n var comment = {\r\n type: source.charAt(start++),\r\n lineEmpty: false,\r\n leading: isLeading,\r\n };\r\n var lookback;\r\n if (alternateCommentMode) {\r\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\r\n } else {\r\n lookback = 3; // \"///\" or \"/**\"\r\n }\r\n var commentOffset = start - lookback,\r\n c;\r\n do {\r\n if (--commentOffset < 0 ||\r\n (c = source.charAt(commentOffset)) === \"\\n\") {\r\n comment.lineEmpty = true;\r\n break;\r\n }\r\n } while (c === \" \" || c === \"\\t\");\r\n var lines = source\r\n .substring(start, end)\r\n .split(setCommentSplitRe);\r\n for (var i = 0; i < lines.length; ++i)\r\n lines[i] = lines[i]\r\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\r\n .trim();\r\n comment.text = lines\r\n .join(\"\\n\")\r\n .trim();\r\n\r\n comments[line] = comment;\r\n lastCommentLine = line;\r\n }\r\n\r\n function isDoubleSlashCommentLine(startOffset) {\r\n var endOffset = findEndOfLine(startOffset);\r\n\r\n // see if remaining line matches comment pattern\r\n var lineText = source.substring(startOffset, endOffset);\r\n var isComment = /^\\s*\\/\\//.test(lineText);\r\n return isComment;\r\n }\r\n\r\n function findEndOfLine(cursor) {\r\n // find end of cursor's line\r\n var endOffset = cursor;\r\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\r\n endOffset++;\r\n }\r\n return endOffset;\r\n }\r\n\r\n /**\r\n * Obtains the next token.\r\n * @returns {string|null} Next token or `null` on eof\r\n * @inner\r\n */\r\n function next() {\r\n if (stack.length > 0)\r\n return stack.shift();\r\n if (stringDelim)\r\n return readString();\r\n var repeat,\r\n prev,\r\n curr,\r\n start,\r\n isDoc,\r\n isLeadingComment = offset === 0;\r\n do {\r\n if (offset === length)\r\n return null;\r\n repeat = false;\r\n while (whitespaceRe.test(curr = charAt(offset))) {\r\n if (curr === \"\\n\") {\r\n isLeadingComment = true;\r\n ++line;\r\n }\r\n if (++offset === length)\r\n return null;\r\n }\r\n\r\n if (charAt(offset) === \"/\") {\r\n if (++offset === length) {\r\n throw illegal(\"comment\");\r\n }\r\n if (charAt(offset) === \"/\") { // Line\r\n if (!alternateCommentMode) {\r\n // check for triple-slash comment\r\n isDoc = charAt(start = offset + 1) === \"/\";\r\n\r\n while (charAt(++offset) !== \"\\n\") {\r\n if (offset === length) {\r\n return null;\r\n }\r\n }\r\n ++offset;\r\n if (isDoc) {\r\n setComment(start, offset - 1, isLeadingComment);\r\n // Trailing comment cannot not be multi-line,\r\n // so leading comment state should be reset to handle potential next comments\r\n isLeadingComment = true;\r\n }\r\n ++line;\r\n repeat = true;\r\n } else {\r\n // check for double-slash comments, consolidating consecutive lines\r\n start = offset;\r\n isDoc = false;\r\n if (isDoubleSlashCommentLine(offset - 1)) {\r\n isDoc = true;\r\n do {\r\n offset = findEndOfLine(offset);\r\n if (offset === length) {\r\n break;\r\n }\r\n offset++;\r\n if (!isLeadingComment) {\r\n // Trailing comment cannot not be multi-line\r\n break;\r\n }\r\n } while (isDoubleSlashCommentLine(offset));\r\n } else {\r\n offset = Math.min(length, findEndOfLine(offset) + 1);\r\n }\r\n if (isDoc) {\r\n setComment(start, offset, isLeadingComment);\r\n isLeadingComment = true;\r\n }\r\n line++;\r\n repeat = true;\r\n }\r\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\r\n // check for /** (regular comment mode) or /* (alternate comment mode)\r\n start = offset + 1;\r\n isDoc = alternateCommentMode || charAt(start) === \"*\";\r\n do {\r\n if (curr === \"\\n\") {\r\n ++line;\r\n }\r\n if (++offset === length) {\r\n throw illegal(\"comment\");\r\n }\r\n prev = curr;\r\n curr = charAt(offset);\r\n } while (prev !== \"*\" || curr !== \"/\");\r\n ++offset;\r\n if (isDoc) {\r\n setComment(start, offset - 2, isLeadingComment);\r\n isLeadingComment = true;\r\n }\r\n repeat = true;\r\n } else {\r\n return \"/\";\r\n }\r\n }\r\n } while (repeat);\r\n\r\n // offset !== length if we got here\r\n\r\n var end = offset;\r\n delimRe.lastIndex = 0;\r\n var delim = delimRe.test(charAt(end++));\r\n if (!delim)\r\n while (end < length && !delimRe.test(charAt(end)))\r\n ++end;\r\n var token = source.substring(offset, offset = end);\r\n if (token === \"\\\"\" || token === \"'\")\r\n stringDelim = token;\r\n return token;\r\n }\r\n\r\n /**\r\n * Pushes a token back to the stack.\r\n * @param {string} token Token\r\n * @returns {undefined}\r\n * @inner\r\n */\r\n function push(token) {\r\n stack.push(token);\r\n }\r\n\r\n /**\r\n * Peeks for the next token.\r\n * @returns {string|null} Token or `null` on eof\r\n * @inner\r\n */\r\n function peek() {\r\n if (!stack.length) {\r\n var token = next();\r\n if (token === null)\r\n return null;\r\n push(token);\r\n }\r\n return stack[0];\r\n }\r\n\r\n /**\r\n * Skips a token.\r\n * @param {string} expected Expected token\r\n * @param {boolean} [optional=false] Whether the token is optional\r\n * @returns {boolean} `true` when skipped, `false` if not\r\n * @throws {Error} When a required token is not present\r\n * @inner\r\n */\r\n function skip(expected, optional) {\r\n var actual = peek(),\r\n equals = actual === expected;\r\n if (equals) {\r\n next();\r\n return true;\r\n }\r\n if (!optional)\r\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\r\n return false;\r\n }\r\n\r\n /**\r\n * Gets a comment.\r\n * @param {number} [trailingLine] Line number if looking for a trailing comment\r\n * @returns {string|null} Comment text\r\n * @inner\r\n */\r\n function cmnt(trailingLine) {\r\n var ret = null;\r\n var comment;\r\n if (trailingLine === undefined) {\r\n comment = comments[line - 1];\r\n delete comments[line - 1];\r\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\r\n ret = comment.leading ? comment.text : null;\r\n }\r\n } else {\r\n /* istanbul ignore else */\r\n if (lastCommentLine < trailingLine) {\r\n peek();\r\n }\r\n comment = comments[trailingLine];\r\n delete comments[trailingLine];\r\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\r\n ret = comment.leading ? null : comment.text;\r\n }\r\n }\r\n return ret;\r\n }\r\n\r\n return Object.defineProperty({\r\n next: next,\r\n peek: peek,\r\n push: push,\r\n skip: skip,\r\n cmnt: cmnt\r\n }, \"line\", {\r\n get: function() { return line; }\r\n });\r\n /* eslint-enable callback-return */\r\n}\r\n","\"use strict\";\r\nmodule.exports = Type;\r\n\r\n// extends Namespace\r\nvar Namespace = require(\"./namespace\");\r\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\r\n\r\nvar Enum = require(\"./enum\"),\r\n OneOf = require(\"./oneof\"),\r\n Field = require(\"./field\"),\r\n MapField = require(\"./mapfield\"),\r\n Service = require(\"./service\"),\r\n Message = require(\"./message\"),\r\n Reader = require(\"./reader\"),\r\n Writer = require(\"./writer\"),\r\n util = require(\"./util\"),\r\n encoder = require(\"./encoder\"),\r\n decoder = require(\"./decoder\"),\r\n verifier = require(\"./verifier\"),\r\n converter = require(\"./converter\"),\r\n wrappers = require(\"./wrappers\");\r\n\r\n/**\r\n * Constructs a new reflected message type instance.\r\n * @classdesc Reflected message type.\r\n * @extends NamespaceBase\r\n * @constructor\r\n * @param {string} name Message name\r\n * @param {Object.} [options] Declared options\r\n */\r\nfunction Type(name, options) {\r\n Namespace.call(this, name, options);\r\n\r\n /**\r\n * Message fields.\r\n * @type {Object.}\r\n */\r\n this.fields = {}; // toJSON, marker\r\n\r\n /**\r\n * Oneofs declared within this namespace, if any.\r\n * @type {Object.}\r\n */\r\n this.oneofs = undefined; // toJSON\r\n\r\n /**\r\n * Extension ranges, if any.\r\n * @type {number[][]}\r\n */\r\n this.extensions = undefined; // toJSON\r\n\r\n /**\r\n * Reserved ranges, if any.\r\n * @type {Array.}\r\n */\r\n this.reserved = undefined; // toJSON\r\n\r\n /*?\r\n * Whether this type is a legacy group.\r\n * @type {boolean|undefined}\r\n */\r\n this.group = undefined; // toJSON\r\n\r\n /**\r\n * Cached fields by id.\r\n * @type {Object.|null}\r\n * @private\r\n */\r\n this._fieldsById = null;\r\n\r\n /**\r\n * Cached fields as an array.\r\n * @type {Field[]|null}\r\n * @private\r\n */\r\n this._fieldsArray = null;\r\n\r\n /**\r\n * Cached oneofs as an array.\r\n * @type {OneOf[]|null}\r\n * @private\r\n */\r\n this._oneofsArray = null;\r\n\r\n /**\r\n * Cached constructor.\r\n * @type {Constructor<{}>}\r\n * @private\r\n */\r\n this._ctor = null;\r\n}\r\n\r\nObject.defineProperties(Type.prototype, {\r\n\r\n /**\r\n * Message fields by id.\r\n * @name Type#fieldsById\r\n * @type {Object.}\r\n * @readonly\r\n */\r\n fieldsById: {\r\n get: function() {\r\n\r\n /* istanbul ignore if */\r\n if (this._fieldsById)\r\n return this._fieldsById;\r\n\r\n this._fieldsById = {};\r\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\r\n var field = this.fields[names[i]],\r\n id = field.id;\r\n\r\n /* istanbul ignore if */\r\n if (this._fieldsById[id])\r\n throw Error(\"duplicate id \" + id + \" in \" + this);\r\n\r\n this._fieldsById[id] = field;\r\n }\r\n return this._fieldsById;\r\n }\r\n },\r\n\r\n /**\r\n * Fields of this message as an array for iteration.\r\n * @name Type#fieldsArray\r\n * @type {Field[]}\r\n * @readonly\r\n */\r\n fieldsArray: {\r\n get: function() {\r\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\r\n }\r\n },\r\n\r\n /**\r\n * Oneofs of this message as an array for iteration.\r\n * @name Type#oneofsArray\r\n * @type {OneOf[]}\r\n * @readonly\r\n */\r\n oneofsArray: {\r\n get: function() {\r\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\r\n }\r\n },\r\n\r\n /**\r\n * The registered constructor, if any registered, otherwise a generic constructor.\r\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\r\n * @name Type#ctor\r\n * @type {Constructor<{}>}\r\n */\r\n ctor: {\r\n get: function() {\r\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\r\n },\r\n set: function(ctor) {\r\n\r\n // Ensure proper prototype\r\n var prototype = ctor.prototype;\r\n if (!(prototype instanceof Message)) {\r\n (ctor.prototype = new Message()).constructor = ctor;\r\n util.merge(ctor.prototype, prototype);\r\n }\r\n\r\n // Classes and messages reference their reflected type\r\n ctor.$type = ctor.prototype.$type = this;\r\n\r\n // Mix in static methods\r\n util.merge(ctor, Message, true);\r\n\r\n this._ctor = ctor;\r\n\r\n // Messages have non-enumerable default values on their prototype\r\n var i = 0;\r\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\r\n this._fieldsArray[i].resolve(); // ensures a proper value\r\n\r\n // Messages have non-enumerable getters and setters for each virtual oneof field\r\n var ctorProperties = {};\r\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\r\n ctorProperties[this._oneofsArray[i].resolve().name] = {\r\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\r\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\r\n };\r\n if (i)\r\n Object.defineProperties(ctor.prototype, ctorProperties);\r\n }\r\n }\r\n});\r\n\r\n/**\r\n * Generates a constructor function for the specified type.\r\n * @param {Type} mtype Message type\r\n * @returns {Codegen} Codegen instance\r\n */\r\nType.generateConstructor = function generateConstructor(mtype) {\r\n /* eslint-disable no-unexpected-multiline */\r\n var gen = util.codegen([\"p\"], mtype.name);\r\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\r\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\r\n if ((field = mtype._fieldsArray[i]).map) gen\r\n (\"this%s={}\", util.safeProp(field.name));\r\n else if (field.repeated) gen\r\n (\"this%s=[]\", util.safeProp(field.name));\r\n return gen\r\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\r\n * @property {Object.} fields Field descriptors\r\n * @property {number[][]} [extensions] Extension ranges\r\n * @property {Array.} [reserved] Reserved ranges\r\n * @property {boolean} [group=false] Whether a legacy group or not\r\n */\r\n\r\n/**\r\n * Creates a message type from a message type descriptor.\r\n * @param {string} name Message name\r\n * @param {IType} json Message type descriptor\r\n * @returns {Type} Created message type\r\n */\r\nType.fromJSON = function fromJSON(name, json) {\r\n var type = new Type(name, json.options);\r\n type.extensions = json.extensions;\r\n type.reserved = json.reserved;\r\n var names = Object.keys(json.fields),\r\n i = 0;\r\n for (; i < names.length; ++i)\r\n type.add(\r\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\r\n ? MapField.fromJSON\r\n : Field.fromJSON )(names[i], json.fields[names[i]])\r\n );\r\n if (json.oneofs)\r\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\r\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\r\n if (json.nested)\r\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\r\n var nested = json.nested[names[i]];\r\n type.add( // most to least likely\r\n ( nested.id !== undefined\r\n ? Field.fromJSON\r\n : nested.fields !== undefined\r\n ? Type.fromJSON\r\n : nested.values !== undefined\r\n ? Enum.fromJSON\r\n : nested.methods !== undefined\r\n ? Service.fromJSON\r\n : Namespace.fromJSON )(names[i], nested)\r\n );\r\n }\r\n if (json.extensions && json.extensions.length)\r\n type.extensions = json.extensions;\r\n if (json.reserved && json.reserved.length)\r\n type.reserved = json.reserved;\r\n if (json.group)\r\n type.group = true;\r\n if (json.comment)\r\n type.comment = json.comment;\r\n return type;\r\n};\r\n\r\n/**\r\n * Converts this message type to a message type descriptor.\r\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r\n * @returns {IType} Message type descriptor\r\n */\r\nType.prototype.toJSON = function toJSON(toJSONOptions) {\r\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\r\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r\n return util.toObject([\r\n \"options\" , inherited && inherited.options || undefined,\r\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\r\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\r\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\r\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\r\n \"group\" , this.group || undefined,\r\n \"nested\" , inherited && inherited.nested || undefined,\r\n \"comment\" , keepComments ? this.comment : undefined\r\n ]);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nType.prototype.resolveAll = function resolveAll() {\r\n var fields = this.fieldsArray, i = 0;\r\n while (i < fields.length)\r\n fields[i++].resolve();\r\n var oneofs = this.oneofsArray; i = 0;\r\n while (i < oneofs.length)\r\n oneofs[i++].resolve();\r\n return Namespace.prototype.resolveAll.call(this);\r\n};\r\n\r\n/**\r\n * @override\r\n */\r\nType.prototype.get = function get(name) {\r\n return this.fields[name]\r\n || this.oneofs && this.oneofs[name]\r\n || this.nested && this.nested[name]\r\n || null;\r\n};\r\n\r\n/**\r\n * Adds a nested object to this type.\r\n * @param {ReflectionObject} object Nested object to add\r\n * @returns {Type} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\r\n */\r\nType.prototype.add = function add(object) {\r\n\r\n if (this.get(object.name))\r\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\r\n\r\n if (object instanceof Field && object.extend === undefined) {\r\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\r\n // The root object takes care of adding distinct sister-fields to the respective extended\r\n // type instead.\r\n\r\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\r\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\r\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\r\n if (this.isReservedId(object.id))\r\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\r\n if (this.isReservedName(object.name))\r\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\r\n\r\n if (object.parent)\r\n object.parent.remove(object);\r\n this.fields[object.name] = object;\r\n object.message = this;\r\n object.onAdd(this);\r\n return clearCache(this);\r\n }\r\n if (object instanceof OneOf) {\r\n if (!this.oneofs)\r\n this.oneofs = {};\r\n this.oneofs[object.name] = object;\r\n object.onAdd(this);\r\n return clearCache(this);\r\n }\r\n return Namespace.prototype.add.call(this, object);\r\n};\r\n\r\n/**\r\n * Removes a nested object from this type.\r\n * @param {ReflectionObject} object Nested object to remove\r\n * @returns {Type} `this`\r\n * @throws {TypeError} If arguments are invalid\r\n * @throws {Error} If `object` is not a member of this type\r\n */\r\nType.prototype.remove = function remove(object) {\r\n if (object instanceof Field && object.extend === undefined) {\r\n // See Type#add for the reason why extension fields are excluded here.\r\n\r\n /* istanbul ignore if */\r\n if (!this.fields || this.fields[object.name] !== object)\r\n throw Error(object + \" is not a member of \" + this);\r\n\r\n delete this.fields[object.name];\r\n object.parent = null;\r\n object.onRemove(this);\r\n return clearCache(this);\r\n }\r\n if (object instanceof OneOf) {\r\n\r\n /* istanbul ignore if */\r\n if (!this.oneofs || this.oneofs[object.name] !== object)\r\n throw Error(object + \" is not a member of \" + this);\r\n\r\n delete this.oneofs[object.name];\r\n object.parent = null;\r\n object.onRemove(this);\r\n return clearCache(this);\r\n }\r\n return Namespace.prototype.remove.call(this, object);\r\n};\r\n\r\n/**\r\n * Tests if the specified id is reserved.\r\n * @param {number} id Id to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nType.prototype.isReservedId = function isReservedId(id) {\r\n return Namespace.isReservedId(this.reserved, id);\r\n};\r\n\r\n/**\r\n * Tests if the specified name is reserved.\r\n * @param {string} name Name to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nType.prototype.isReservedName = function isReservedName(name) {\r\n return Namespace.isReservedName(this.reserved, name);\r\n};\r\n\r\n/**\r\n * Creates a new message of this type using the specified properties.\r\n * @param {Object.} [properties] Properties to set\r\n * @returns {Message<{}>} Message instance\r\n */\r\nType.prototype.create = function create(properties) {\r\n return new this.ctor(properties);\r\n};\r\n\r\n/**\r\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\r\n * @returns {Type} `this`\r\n */\r\nType.prototype.setup = function setup() {\r\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\r\n // multiple times (V8, soft-deopt prototype-check).\r\n\r\n var fullName = this.fullName,\r\n types = [];\r\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\r\n types.push(this._fieldsArray[i].resolve().resolvedType);\r\n\r\n // Replace setup methods with type-specific generated functions\r\n this.encode = encoder(this)({\r\n Writer : Writer,\r\n types : types,\r\n util : util\r\n });\r\n this.decode = decoder(this)({\r\n Reader : Reader,\r\n types : types,\r\n util : util\r\n });\r\n this.verify = verifier(this)({\r\n types : types,\r\n util : util\r\n });\r\n this.fromObject = converter.fromObject(this)({\r\n types : types,\r\n util : util\r\n });\r\n this.toObject = converter.toObject(this)({\r\n types : types,\r\n util : util\r\n });\r\n\r\n // Inject custom wrappers for common types\r\n var wrapper = wrappers[fullName];\r\n if (wrapper) {\r\n var originalThis = Object.create(this);\r\n // if (wrapper.fromObject) {\r\n originalThis.fromObject = this.fromObject;\r\n this.fromObject = wrapper.fromObject.bind(originalThis);\r\n // }\r\n // if (wrapper.toObject) {\r\n originalThis.toObject = this.toObject;\r\n this.toObject = wrapper.toObject.bind(originalThis);\r\n // }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\r\n * @param {Message<{}>|Object.} message Message instance or plain object\r\n * @param {Writer} [writer] Writer to encode to\r\n * @returns {Writer} writer\r\n */\r\nType.prototype.encode = function encode_setup(message, writer) {\r\n return this.setup().encode(message, writer); // overrides this method\r\n};\r\n\r\n/**\r\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\r\n * @param {Message<{}>|Object.} message Message instance or plain object\r\n * @param {Writer} [writer] Writer to encode to\r\n * @returns {Writer} writer\r\n */\r\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\r\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\r\n};\r\n\r\n/**\r\n * Decodes a message of this type.\r\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\r\n * @param {number} [length] Length of the message, if known beforehand\r\n * @returns {Message<{}>} Decoded message\r\n * @throws {Error} If the payload is not a reader or valid buffer\r\n * @throws {util.ProtocolError<{}>} If required fields are missing\r\n */\r\nType.prototype.decode = function decode_setup(reader, length) {\r\n return this.setup().decode(reader, length); // overrides this method\r\n};\r\n\r\n/**\r\n * Decodes a message of this type preceeded by its byte length as a varint.\r\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\r\n * @returns {Message<{}>} Decoded message\r\n * @throws {Error} If the payload is not a reader or valid buffer\r\n * @throws {util.ProtocolError} If required fields are missing\r\n */\r\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\r\n if (!(reader instanceof Reader))\r\n reader = Reader.create(reader);\r\n return this.decode(reader, reader.uint32());\r\n};\r\n\r\n/**\r\n * Verifies that field values are valid and that required fields are present.\r\n * @param {Object.} message Plain object to verify\r\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\r\n */\r\nType.prototype.verify = function verify_setup(message) {\r\n return this.setup().verify(message); // overrides this method\r\n};\r\n\r\n/**\r\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\r\n * @param {Object.} object Plain object to convert\r\n * @returns {Message<{}>} Message instance\r\n */\r\nType.prototype.fromObject = function fromObject(object) {\r\n return this.setup().fromObject(object);\r\n};\r\n\r\n/**\r\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\r\n * @interface IConversionOptions\r\n * @property {Function} [longs] Long conversion type.\r\n * Valid values are `String` and `Number` (the global types).\r\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\r\n * @property {Function} [enums] Enum value conversion type.\r\n * Only valid value is `String` (the global type).\r\n * Defaults to copy the present value, which is the numeric id.\r\n * @property {Function} [bytes] Bytes value conversion type.\r\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\r\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\r\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\r\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\r\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\r\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\r\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\r\n */\r\n\r\n/**\r\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\r\n * @param {Message<{}>} message Message instance\r\n * @param {IConversionOptions} [options] Conversion options\r\n * @returns {Object.} Plain object\r\n */\r\nType.prototype.toObject = function toObject(message, options) {\r\n return this.setup().toObject(message, options);\r\n};\r\n\r\n/**\r\n * Decorator function as returned by {@link Type.d} (TypeScript).\r\n * @typedef TypeDecorator\r\n * @type {function}\r\n * @param {Constructor} target Target constructor\r\n * @returns {undefined}\r\n * @template T extends Message\r\n */\r\n\r\n/**\r\n * Type decorator (TypeScript).\r\n * @param {string} [typeName] Type name, defaults to the constructor's name\r\n * @returns {TypeDecorator} Decorator function\r\n * @template T extends Message\r\n */\r\nType.d = function decorateType(typeName) {\r\n return function typeDecorator(target) {\r\n util.decorateType(target, typeName);\r\n };\r\n};\r\n","\"use strict\";\r\n\r\n/**\r\n * Common type constants.\r\n * @namespace\r\n */\r\nvar types = exports;\r\n\r\nvar util = require(\"./util\");\r\n\r\nvar s = [\r\n \"double\", // 0\r\n \"float\", // 1\r\n \"int32\", // 2\r\n \"uint32\", // 3\r\n \"sint32\", // 4\r\n \"fixed32\", // 5\r\n \"sfixed32\", // 6\r\n \"int64\", // 7\r\n \"uint64\", // 8\r\n \"sint64\", // 9\r\n \"fixed64\", // 10\r\n \"sfixed64\", // 11\r\n \"bool\", // 12\r\n \"string\", // 13\r\n \"bytes\" // 14\r\n];\r\n\r\nfunction bake(values, offset) {\r\n var i = 0, o = {};\r\n offset |= 0;\r\n while (i < values.length) o[s[i + offset]] = values[i++];\r\n return o;\r\n}\r\n\r\n/**\r\n * Basic type wire types.\r\n * @type {Object.}\r\n * @const\r\n * @property {number} double=1 Fixed64 wire type\r\n * @property {number} float=5 Fixed32 wire type\r\n * @property {number} int32=0 Varint wire type\r\n * @property {number} uint32=0 Varint wire type\r\n * @property {number} sint32=0 Varint wire type\r\n * @property {number} fixed32=5 Fixed32 wire type\r\n * @property {number} sfixed32=5 Fixed32 wire type\r\n * @property {number} int64=0 Varint wire type\r\n * @property {number} uint64=0 Varint wire type\r\n * @property {number} sint64=0 Varint wire type\r\n * @property {number} fixed64=1 Fixed64 wire type\r\n * @property {number} sfixed64=1 Fixed64 wire type\r\n * @property {number} bool=0 Varint wire type\r\n * @property {number} string=2 Ldelim wire type\r\n * @property {number} bytes=2 Ldelim wire type\r\n */\r\ntypes.basic = bake([\r\n /* double */ 1,\r\n /* float */ 5,\r\n /* int32 */ 0,\r\n /* uint32 */ 0,\r\n /* sint32 */ 0,\r\n /* fixed32 */ 5,\r\n /* sfixed32 */ 5,\r\n /* int64 */ 0,\r\n /* uint64 */ 0,\r\n /* sint64 */ 0,\r\n /* fixed64 */ 1,\r\n /* sfixed64 */ 1,\r\n /* bool */ 0,\r\n /* string */ 2,\r\n /* bytes */ 2\r\n]);\r\n\r\n/**\r\n * Basic type defaults.\r\n * @type {Object.}\r\n * @const\r\n * @property {number} double=0 Double default\r\n * @property {number} float=0 Float default\r\n * @property {number} int32=0 Int32 default\r\n * @property {number} uint32=0 Uint32 default\r\n * @property {number} sint32=0 Sint32 default\r\n * @property {number} fixed32=0 Fixed32 default\r\n * @property {number} sfixed32=0 Sfixed32 default\r\n * @property {number} int64=0 Int64 default\r\n * @property {number} uint64=0 Uint64 default\r\n * @property {number} sint64=0 Sint32 default\r\n * @property {number} fixed64=0 Fixed64 default\r\n * @property {number} sfixed64=0 Sfixed64 default\r\n * @property {boolean} bool=false Bool default\r\n * @property {string} string=\"\" String default\r\n * @property {Array.} bytes=Array(0) Bytes default\r\n * @property {null} message=null Message default\r\n */\r\ntypes.defaults = bake([\r\n /* double */ 0,\r\n /* float */ 0,\r\n /* int32 */ 0,\r\n /* uint32 */ 0,\r\n /* sint32 */ 0,\r\n /* fixed32 */ 0,\r\n /* sfixed32 */ 0,\r\n /* int64 */ 0,\r\n /* uint64 */ 0,\r\n /* sint64 */ 0,\r\n /* fixed64 */ 0,\r\n /* sfixed64 */ 0,\r\n /* bool */ false,\r\n /* string */ \"\",\r\n /* bytes */ util.emptyArray,\r\n /* message */ null\r\n]);\r\n\r\n/**\r\n * Basic long type wire types.\r\n * @type {Object.}\r\n * @const\r\n * @property {number} int64=0 Varint wire type\r\n * @property {number} uint64=0 Varint wire type\r\n * @property {number} sint64=0 Varint wire type\r\n * @property {number} fixed64=1 Fixed64 wire type\r\n * @property {number} sfixed64=1 Fixed64 wire type\r\n */\r\ntypes.long = bake([\r\n /* int64 */ 0,\r\n /* uint64 */ 0,\r\n /* sint64 */ 0,\r\n /* fixed64 */ 1,\r\n /* sfixed64 */ 1\r\n], 7);\r\n\r\n/**\r\n * Allowed types for map keys with their associated wire type.\r\n * @type {Object.}\r\n * @const\r\n * @property {number} int32=0 Varint wire type\r\n * @property {number} uint32=0 Varint wire type\r\n * @property {number} sint32=0 Varint wire type\r\n * @property {number} fixed32=5 Fixed32 wire type\r\n * @property {number} sfixed32=5 Fixed32 wire type\r\n * @property {number} int64=0 Varint wire type\r\n * @property {number} uint64=0 Varint wire type\r\n * @property {number} sint64=0 Varint wire type\r\n * @property {number} fixed64=1 Fixed64 wire type\r\n * @property {number} sfixed64=1 Fixed64 wire type\r\n * @property {number} bool=0 Varint wire type\r\n * @property {number} string=2 Ldelim wire type\r\n */\r\ntypes.mapKey = bake([\r\n /* int32 */ 0,\r\n /* uint32 */ 0,\r\n /* sint32 */ 0,\r\n /* fixed32 */ 5,\r\n /* sfixed32 */ 5,\r\n /* int64 */ 0,\r\n /* uint64 */ 0,\r\n /* sint64 */ 0,\r\n /* fixed64 */ 1,\r\n /* sfixed64 */ 1,\r\n /* bool */ 0,\r\n /* string */ 2\r\n], 2);\r\n\r\n/**\r\n * Allowed types for packed repeated fields with their associated wire type.\r\n * @type {Object.}\r\n * @const\r\n * @property {number} double=1 Fixed64 wire type\r\n * @property {number} float=5 Fixed32 wire type\r\n * @property {number} int32=0 Varint wire type\r\n * @property {number} uint32=0 Varint wire type\r\n * @property {number} sint32=0 Varint wire type\r\n * @property {number} fixed32=5 Fixed32 wire type\r\n * @property {number} sfixed32=5 Fixed32 wire type\r\n * @property {number} int64=0 Varint wire type\r\n * @property {number} uint64=0 Varint wire type\r\n * @property {number} sint64=0 Varint wire type\r\n * @property {number} fixed64=1 Fixed64 wire type\r\n * @property {number} sfixed64=1 Fixed64 wire type\r\n * @property {number} bool=0 Varint wire type\r\n */\r\ntypes.packed = bake([\r\n /* double */ 1,\r\n /* float */ 5,\r\n /* int32 */ 0,\r\n /* uint32 */ 0,\r\n /* sint32 */ 0,\r\n /* fixed32 */ 5,\r\n /* sfixed32 */ 5,\r\n /* int64 */ 0,\r\n /* uint64 */ 0,\r\n /* sint64 */ 0,\r\n /* fixed64 */ 1,\r\n /* sfixed64 */ 1,\r\n /* bool */ 0\r\n]);\r\n","\"use strict\";\r\n\r\n/**\r\n * Various utility functions.\r\n * @namespace\r\n */\r\nvar util = module.exports = require(\"./util/minimal\");\r\n\r\nvar roots = require(\"./roots\");\r\n\r\nvar Type, // cyclic\r\n Enum;\r\n\r\nutil.codegen = require(\"@protobufjs/codegen\");\r\nutil.fetch = require(\"@protobufjs/fetch\");\r\nutil.path = require(\"@protobufjs/path\");\r\n\r\n/**\r\n * Node's fs module if available.\r\n * @type {Object.}\r\n */\r\nutil.fs = util.inquire(\"fs\");\r\n\r\n/**\r\n * Converts an object's values to an array.\r\n * @param {Object.} object Object to convert\r\n * @returns {Array.<*>} Converted array\r\n */\r\nutil.toArray = function toArray(object) {\r\n if (object) {\r\n var keys = Object.keys(object),\r\n array = new Array(keys.length),\r\n index = 0;\r\n while (index < keys.length)\r\n array[index] = object[keys[index++]];\r\n return array;\r\n }\r\n return [];\r\n};\r\n\r\n/**\r\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\r\n * @param {Array.<*>} array Array to convert\r\n * @returns {Object.} Converted object\r\n */\r\nutil.toObject = function toObject(array) {\r\n var object = {},\r\n index = 0;\r\n while (index < array.length) {\r\n var key = array[index++],\r\n val = array[index++];\r\n if (val !== undefined)\r\n object[key] = val;\r\n }\r\n return object;\r\n};\r\n\r\nvar safePropBackslashRe = /\\\\/g,\r\n safePropQuoteRe = /\"/g;\r\n\r\n/**\r\n * Tests whether the specified name is a reserved word in JS.\r\n * @param {string} name Name to test\r\n * @returns {boolean} `true` if reserved, otherwise `false`\r\n */\r\nutil.isReserved = function isReserved(name) {\r\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\r\n};\r\n\r\n/**\r\n * Returns a safe property accessor for the specified property name.\r\n * @param {string} prop Property name\r\n * @returns {string} Safe accessor\r\n */\r\nutil.safeProp = function safeProp(prop) {\r\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\r\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\r\n return \".\" + prop;\r\n};\r\n\r\n/**\r\n * Converts the first character of a string to upper case.\r\n * @param {string} str String to convert\r\n * @returns {string} Converted string\r\n */\r\nutil.ucFirst = function ucFirst(str) {\r\n return str.charAt(0).toUpperCase() + str.substring(1);\r\n};\r\n\r\nvar camelCaseRe = /_([a-z])/g;\r\n\r\n/**\r\n * Converts a string to camel case.\r\n * @param {string} str String to convert\r\n * @returns {string} Converted string\r\n */\r\nutil.camelCase = function camelCase(str) {\r\n return str.substring(0, 1)\r\n + str.substring(1)\r\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\r\n};\r\n\r\n/**\r\n * Compares reflected fields by id.\r\n * @param {Field} a First field\r\n * @param {Field} b Second field\r\n * @returns {number} Comparison value\r\n */\r\nutil.compareFieldsById = function compareFieldsById(a, b) {\r\n return a.id - b.id;\r\n};\r\n\r\n/**\r\n * Decorator helper for types (TypeScript).\r\n * @param {Constructor} ctor Constructor function\r\n * @param {string} [typeName] Type name, defaults to the constructor's name\r\n * @returns {Type} Reflected type\r\n * @template T extends Message\r\n * @property {Root} root Decorators root\r\n */\r\nutil.decorateType = function decorateType(ctor, typeName) {\r\n\r\n /* istanbul ignore if */\r\n if (ctor.$type) {\r\n if (typeName && ctor.$type.name !== typeName) {\r\n util.decorateRoot.remove(ctor.$type);\r\n ctor.$type.name = typeName;\r\n util.decorateRoot.add(ctor.$type);\r\n }\r\n return ctor.$type;\r\n }\r\n\r\n /* istanbul ignore next */\r\n if (!Type)\r\n Type = require(\"./type\");\r\n\r\n var type = new Type(typeName || ctor.name);\r\n util.decorateRoot.add(type);\r\n type.ctor = ctor; // sets up .encode, .decode etc.\r\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\r\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\r\n return type;\r\n};\r\n\r\nvar decorateEnumIndex = 0;\r\n\r\n/**\r\n * Decorator helper for enums (TypeScript).\r\n * @param {Object} object Enum object\r\n * @returns {Enum} Reflected enum\r\n */\r\nutil.decorateEnum = function decorateEnum(object) {\r\n\r\n /* istanbul ignore if */\r\n if (object.$type)\r\n return object.$type;\r\n\r\n /* istanbul ignore next */\r\n if (!Enum)\r\n Enum = require(\"./enum\");\r\n\r\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\r\n util.decorateRoot.add(enm);\r\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\r\n return enm;\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\r\n * @param {Object.} dst Destination object\r\n * @param {string} path dot '.' delimited path of the property to set\r\n * @param {Object} value the value to set\r\n * @returns {Object.} Destination object\r\n */\r\nutil.setProperty = function setProperty(dst, path, value) {\r\n function setProp(dst, path, value) {\r\n var part = path.shift();\r\n if (part === \"__proto__\" || part === \"prototype\") {\r\n return dst;\r\n }\r\n if (path.length > 0) {\r\n dst[part] = setProp(dst[part] || {}, path, value);\r\n } else {\r\n var prevValue = dst[part];\r\n if (prevValue)\r\n value = [].concat(prevValue).concat(value);\r\n dst[part] = value;\r\n }\r\n return dst;\r\n }\r\n\r\n if (typeof dst !== \"object\")\r\n throw TypeError(\"dst must be an object\");\r\n if (!path)\r\n throw TypeError(\"path must be specified\");\r\n\r\n path = path.split(\".\");\r\n return setProp(dst, path, value);\r\n};\r\n\r\n/**\r\n * Decorator root (TypeScript).\r\n * @name util.decorateRoot\r\n * @type {Root}\r\n * @readonly\r\n */\r\nObject.defineProperty(util, \"decorateRoot\", {\r\n get: function() {\r\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(\"./root\"))());\r\n }\r\n});\r\n","\"use strict\";\r\nmodule.exports = LongBits;\r\n\r\nvar util = require(\"../util/minimal\");\r\n\r\n/**\r\n * Constructs new long bits.\r\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\r\n * @memberof util\r\n * @constructor\r\n * @param {number} lo Low 32 bits, unsigned\r\n * @param {number} hi High 32 bits, unsigned\r\n */\r\nfunction LongBits(lo, hi) {\r\n\r\n // note that the casts below are theoretically unnecessary as of today, but older statically\r\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\r\n\r\n /**\r\n * Low bits.\r\n * @type {number}\r\n */\r\n this.lo = lo >>> 0;\r\n\r\n /**\r\n * High bits.\r\n * @type {number}\r\n */\r\n this.hi = hi >>> 0;\r\n}\r\n\r\n/**\r\n * Zero bits.\r\n * @memberof util.LongBits\r\n * @type {util.LongBits}\r\n */\r\nvar zero = LongBits.zero = new LongBits(0, 0);\r\n\r\nzero.toNumber = function() { return 0; };\r\nzero.zzEncode = zero.zzDecode = function() { return this; };\r\nzero.length = function() { return 1; };\r\n\r\n/**\r\n * Zero hash.\r\n * @memberof util.LongBits\r\n * @type {string}\r\n */\r\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\r\n\r\n/**\r\n * Constructs new long bits from the specified number.\r\n * @param {number} value Value\r\n * @returns {util.LongBits} Instance\r\n */\r\nLongBits.fromNumber = function fromNumber(value) {\r\n if (value === 0)\r\n return zero;\r\n var sign = value < 0;\r\n if (sign)\r\n value = -value;\r\n var lo = value >>> 0,\r\n hi = (value - lo) / 4294967296 >>> 0;\r\n if (sign) {\r\n hi = ~hi >>> 0;\r\n lo = ~lo >>> 0;\r\n if (++lo > 4294967295) {\r\n lo = 0;\r\n if (++hi > 4294967295)\r\n hi = 0;\r\n }\r\n }\r\n return new LongBits(lo, hi);\r\n};\r\n\r\n/**\r\n * Constructs new long bits from a number, long or string.\r\n * @param {Long|number|string} value Value\r\n * @returns {util.LongBits} Instance\r\n */\r\nLongBits.from = function from(value) {\r\n if (typeof value === \"number\")\r\n return LongBits.fromNumber(value);\r\n if (util.isString(value)) {\r\n /* istanbul ignore else */\r\n if (util.Long)\r\n value = util.Long.fromString(value);\r\n else\r\n return LongBits.fromNumber(parseInt(value, 10));\r\n }\r\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\r\n};\r\n\r\n/**\r\n * Converts this long bits to a possibly unsafe JavaScript number.\r\n * @param {boolean} [unsigned=false] Whether unsigned or not\r\n * @returns {number} Possibly unsafe number\r\n */\r\nLongBits.prototype.toNumber = function toNumber(unsigned) {\r\n if (!unsigned && this.hi >>> 31) {\r\n var lo = ~this.lo + 1 >>> 0,\r\n hi = ~this.hi >>> 0;\r\n if (!lo)\r\n hi = hi + 1 >>> 0;\r\n return -(lo + hi * 4294967296);\r\n }\r\n return this.lo + this.hi * 4294967296;\r\n};\r\n\r\n/**\r\n * Converts this long bits to a long.\r\n * @param {boolean} [unsigned=false] Whether unsigned or not\r\n * @returns {Long} Long\r\n */\r\nLongBits.prototype.toLong = function toLong(unsigned) {\r\n return util.Long\r\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\r\n /* istanbul ignore next */\r\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\r\n};\r\n\r\nvar charCodeAt = String.prototype.charCodeAt;\r\n\r\n/**\r\n * Constructs new long bits from the specified 8 characters long hash.\r\n * @param {string} hash Hash\r\n * @returns {util.LongBits} Bits\r\n */\r\nLongBits.fromHash = function fromHash(hash) {\r\n if (hash === zeroHash)\r\n return zero;\r\n return new LongBits(\r\n ( charCodeAt.call(hash, 0)\r\n | charCodeAt.call(hash, 1) << 8\r\n | charCodeAt.call(hash, 2) << 16\r\n | charCodeAt.call(hash, 3) << 24) >>> 0\r\n ,\r\n ( charCodeAt.call(hash, 4)\r\n | charCodeAt.call(hash, 5) << 8\r\n | charCodeAt.call(hash, 6) << 16\r\n | charCodeAt.call(hash, 7) << 24) >>> 0\r\n );\r\n};\r\n\r\n/**\r\n * Converts this long bits to a 8 characters long hash.\r\n * @returns {string} Hash\r\n */\r\nLongBits.prototype.toHash = function toHash() {\r\n return String.fromCharCode(\r\n this.lo & 255,\r\n this.lo >>> 8 & 255,\r\n this.lo >>> 16 & 255,\r\n this.lo >>> 24 ,\r\n this.hi & 255,\r\n this.hi >>> 8 & 255,\r\n this.hi >>> 16 & 255,\r\n this.hi >>> 24\r\n );\r\n};\r\n\r\n/**\r\n * Zig-zag encodes this long bits.\r\n * @returns {util.LongBits} `this`\r\n */\r\nLongBits.prototype.zzEncode = function zzEncode() {\r\n var mask = this.hi >> 31;\r\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\r\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Zig-zag decodes this long bits.\r\n * @returns {util.LongBits} `this`\r\n */\r\nLongBits.prototype.zzDecode = function zzDecode() {\r\n var mask = -(this.lo & 1);\r\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\r\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Calculates the length of this longbits when encoded as a varint.\r\n * @returns {number} Length\r\n */\r\nLongBits.prototype.length = function length() {\r\n var part0 = this.lo,\r\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\r\n part2 = this.hi >>> 24;\r\n return part2 === 0\r\n ? part1 === 0\r\n ? part0 < 16384\r\n ? part0 < 128 ? 1 : 2\r\n : part0 < 2097152 ? 3 : 4\r\n : part1 < 16384\r\n ? part1 < 128 ? 5 : 6\r\n : part1 < 2097152 ? 7 : 8\r\n : part2 < 128 ? 9 : 10;\r\n};\r\n","\"use strict\";\r\nvar util = exports;\r\n\r\n// used to return a Promise where callback is omitted\r\nutil.asPromise = require(\"@protobufjs/aspromise\");\r\n\r\n// converts to / from base64 encoded strings\r\nutil.base64 = require(\"@protobufjs/base64\");\r\n\r\n// base class of rpc.Service\r\nutil.EventEmitter = require(\"@protobufjs/eventemitter\");\r\n\r\n// float handling accross browsers\r\nutil.float = require(\"@protobufjs/float\");\r\n\r\n// requires modules optionally and hides the call from bundlers\r\nutil.inquire = require(\"@protobufjs/inquire\");\r\n\r\n// converts to / from utf8 encoded strings\r\nutil.utf8 = require(\"@protobufjs/utf8\");\r\n\r\n// provides a node-like buffer pool in the browser\r\nutil.pool = require(\"@protobufjs/pool\");\r\n\r\n// utility to work with the low and high bits of a 64 bit value\r\nutil.LongBits = require(\"./longbits\");\r\n\r\n/**\r\n * Whether running within node or not.\r\n * @memberof util\r\n * @type {boolean}\r\n */\r\nutil.isNode = Boolean(typeof global !== \"undefined\"\r\n && global\r\n && global.process\r\n && global.process.versions\r\n && global.process.versions.node);\r\n\r\n/**\r\n * Global object reference.\r\n * @memberof util\r\n * @type {Object}\r\n */\r\nutil.global = util.isNode && global\r\n || typeof window !== \"undefined\" && window\r\n || typeof self !== \"undefined\" && self\r\n || this; // eslint-disable-line no-invalid-this\r\n\r\n/**\r\n * An immuable empty array.\r\n * @memberof util\r\n * @type {Array.<*>}\r\n * @const\r\n */\r\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\r\n\r\n/**\r\n * An immutable empty object.\r\n * @type {Object}\r\n * @const\r\n */\r\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\r\n\r\n/**\r\n * Tests if the specified value is an integer.\r\n * @function\r\n * @param {*} value Value to test\r\n * @returns {boolean} `true` if the value is an integer\r\n */\r\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\r\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\r\n};\r\n\r\n/**\r\n * Tests if the specified value is a string.\r\n * @param {*} value Value to test\r\n * @returns {boolean} `true` if the value is a string\r\n */\r\nutil.isString = function isString(value) {\r\n return typeof value === \"string\" || value instanceof String;\r\n};\r\n\r\n/**\r\n * Tests if the specified value is a non-null object.\r\n * @param {*} value Value to test\r\n * @returns {boolean} `true` if the value is a non-null object\r\n */\r\nutil.isObject = function isObject(value) {\r\n return value && typeof value === \"object\";\r\n};\r\n\r\n/**\r\n * Checks if a property on a message is considered to be present.\r\n * This is an alias of {@link util.isSet}.\r\n * @function\r\n * @param {Object} obj Plain object or message instance\r\n * @param {string} prop Property name\r\n * @returns {boolean} `true` if considered to be present, otherwise `false`\r\n */\r\nutil.isset =\r\n\r\n/**\r\n * Checks if a property on a message is considered to be present.\r\n * @param {Object} obj Plain object or message instance\r\n * @param {string} prop Property name\r\n * @returns {boolean} `true` if considered to be present, otherwise `false`\r\n */\r\nutil.isSet = function isSet(obj, prop) {\r\n var value = obj[prop];\r\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\r\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\r\n return false;\r\n};\r\n\r\n/**\r\n * Any compatible Buffer instance.\r\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\r\n * @interface Buffer\r\n * @extends Uint8Array\r\n */\r\n\r\n/**\r\n * Node's Buffer class if available.\r\n * @type {Constructor}\r\n */\r\nutil.Buffer = (function() {\r\n try {\r\n var Buffer = util.inquire(\"buffer\").Buffer;\r\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\r\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\r\n } catch (e) {\r\n /* istanbul ignore next */\r\n return null;\r\n }\r\n})();\r\n\r\n// Internal alias of or polyfull for Buffer.from.\r\nutil._Buffer_from = null;\r\n\r\n// Internal alias of or polyfill for Buffer.allocUnsafe.\r\nutil._Buffer_allocUnsafe = null;\r\n\r\n/**\r\n * Creates a new buffer of whatever type supported by the environment.\r\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\r\n * @returns {Uint8Array|Buffer} Buffer\r\n */\r\nutil.newBuffer = function newBuffer(sizeOrArray) {\r\n /* istanbul ignore next */\r\n return typeof sizeOrArray === \"number\"\r\n ? util.Buffer\r\n ? util._Buffer_allocUnsafe(sizeOrArray)\r\n : new util.Array(sizeOrArray)\r\n : util.Buffer\r\n ? util._Buffer_from(sizeOrArray)\r\n : typeof Uint8Array === \"undefined\"\r\n ? sizeOrArray\r\n : new Uint8Array(sizeOrArray);\r\n};\r\n\r\n/**\r\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\r\n * @type {Constructor}\r\n */\r\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\r\n\r\n/**\r\n * Any compatible Long instance.\r\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\r\n * @interface Long\r\n * @property {number} low Low bits\r\n * @property {number} high High bits\r\n * @property {boolean} unsigned Whether unsigned or not\r\n */\r\n\r\n/**\r\n * Long.js's Long class if available.\r\n * @type {Constructor}\r\n */\r\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\r\n || /* istanbul ignore next */ util.global.Long\r\n || util.inquire(\"long\");\r\n\r\n/**\r\n * Regular expression used to verify 2 bit (`bool`) map keys.\r\n * @type {RegExp}\r\n * @const\r\n */\r\nutil.key2Re = /^true|false|0|1$/;\r\n\r\n/**\r\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\r\n * @type {RegExp}\r\n * @const\r\n */\r\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\r\n\r\n/**\r\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\r\n * @type {RegExp}\r\n * @const\r\n */\r\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\r\n\r\n/**\r\n * Converts a number or long to an 8 characters long hash string.\r\n * @param {Long|number} value Value to convert\r\n * @returns {string} Hash\r\n */\r\nutil.longToHash = function longToHash(value) {\r\n return value\r\n ? util.LongBits.from(value).toHash()\r\n : util.LongBits.zeroHash;\r\n};\r\n\r\n/**\r\n * Converts an 8 characters long hash string to a long or number.\r\n * @param {string} hash Hash\r\n * @param {boolean} [unsigned=false] Whether unsigned or not\r\n * @returns {Long|number} Original value\r\n */\r\nutil.longFromHash = function longFromHash(hash, unsigned) {\r\n var bits = util.LongBits.fromHash(hash);\r\n if (util.Long)\r\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\r\n return bits.toNumber(Boolean(unsigned));\r\n};\r\n\r\n/**\r\n * Merges the properties of the source object into the destination object.\r\n * @memberof util\r\n * @param {Object.} dst Destination object\r\n * @param {Object.} src Source object\r\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\r\n * @returns {Object.} Destination object\r\n */\r\nfunction merge(dst, src, ifNotSet) { // used by converters\r\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\r\n if (dst[keys[i]] === undefined || !ifNotSet)\r\n dst[keys[i]] = src[keys[i]];\r\n return dst;\r\n}\r\n\r\nutil.merge = merge;\r\n\r\n/**\r\n * Converts the first character of a string to lower case.\r\n * @param {string} str String to convert\r\n * @returns {string} Converted string\r\n */\r\nutil.lcFirst = function lcFirst(str) {\r\n return str.charAt(0).toLowerCase() + str.substring(1);\r\n};\r\n\r\n/**\r\n * Creates a custom error constructor.\r\n * @memberof util\r\n * @param {string} name Error name\r\n * @returns {Constructor} Custom error constructor\r\n */\r\nfunction newError(name) {\r\n\r\n function CustomError(message, properties) {\r\n\r\n if (!(this instanceof CustomError))\r\n return new CustomError(message, properties);\r\n\r\n // Error.call(this, message);\r\n // ^ just returns a new error instance because the ctor can be called as a function\r\n\r\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\r\n\r\n /* istanbul ignore next */\r\n if (Error.captureStackTrace) // node\r\n Error.captureStackTrace(this, CustomError);\r\n else\r\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\r\n\r\n if (properties)\r\n merge(this, properties);\r\n }\r\n\r\n CustomError.prototype = Object.create(Error.prototype, {\r\n constructor: {\r\n value: CustomError,\r\n writable: true,\r\n enumerable: false,\r\n configurable: true,\r\n },\r\n name: {\r\n get: function get() { return name; },\r\n set: undefined,\r\n enumerable: false,\r\n // configurable: false would accurately preserve the behavior of\r\n // the original, but I'm guessing that was not intentional.\r\n // For an actual error subclass, this property would\r\n // be configurable.\r\n configurable: true,\r\n },\r\n toString: {\r\n value: function value() { return this.name + \": \" + this.message; },\r\n writable: true,\r\n enumerable: false,\r\n configurable: true,\r\n },\r\n });\r\n\r\n return CustomError;\r\n}\r\n\r\nutil.newError = newError;\r\n\r\n/**\r\n * Constructs a new protocol error.\r\n * @classdesc Error subclass indicating a protocol specifc error.\r\n * @memberof util\r\n * @extends Error\r\n * @template T extends Message\r\n * @constructor\r\n * @param {string} message Error message\r\n * @param {Object.} [properties] Additional properties\r\n * @example\r\n * try {\r\n * MyMessage.decode(someBuffer); // throws if required fields are missing\r\n * } catch (e) {\r\n * if (e instanceof ProtocolError && e.instance)\r\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\r\n * }\r\n */\r\nutil.ProtocolError = newError(\"ProtocolError\");\r\n\r\n/**\r\n * So far decoded message instance.\r\n * @name util.ProtocolError#instance\r\n * @type {Message}\r\n */\r\n\r\n/**\r\n * A OneOf getter as returned by {@link util.oneOfGetter}.\r\n * @typedef OneOfGetter\r\n * @type {function}\r\n * @returns {string|undefined} Set field name, if any\r\n */\r\n\r\n/**\r\n * Builds a getter for a oneof's present field name.\r\n * @param {string[]} fieldNames Field names\r\n * @returns {OneOfGetter} Unbound getter\r\n */\r\nutil.oneOfGetter = function getOneOf(fieldNames) {\r\n var fieldMap = {};\r\n for (var i = 0; i < fieldNames.length; ++i)\r\n fieldMap[fieldNames[i]] = 1;\r\n\r\n /**\r\n * @returns {string|undefined} Set field name, if any\r\n * @this Object\r\n * @ignore\r\n */\r\n return function() { // eslint-disable-line consistent-return\r\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\r\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\r\n return keys[i];\r\n };\r\n};\r\n\r\n/**\r\n * A OneOf setter as returned by {@link util.oneOfSetter}.\r\n * @typedef OneOfSetter\r\n * @type {function}\r\n * @param {string|undefined} value Field name\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Builds a setter for a oneof's present field name.\r\n * @param {string[]} fieldNames Field names\r\n * @returns {OneOfSetter} Unbound setter\r\n */\r\nutil.oneOfSetter = function setOneOf(fieldNames) {\r\n\r\n /**\r\n * @param {string} name Field name\r\n * @returns {undefined}\r\n * @this Object\r\n * @ignore\r\n */\r\n return function(name) {\r\n for (var i = 0; i < fieldNames.length; ++i)\r\n if (fieldNames[i] !== name)\r\n delete this[fieldNames[i]];\r\n };\r\n};\r\n\r\n/**\r\n * Default conversion options used for {@link Message#toJSON} implementations.\r\n *\r\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\r\n *\r\n * - Longs become strings\r\n * - Enums become string keys\r\n * - Bytes become base64 encoded strings\r\n * - (Sub-)Messages become plain objects\r\n * - Maps become plain objects with all string keys\r\n * - Repeated fields become arrays\r\n * - NaN and Infinity for float and double fields become strings\r\n *\r\n * @type {IConversionOptions}\r\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\r\n */\r\nutil.toJSONOptions = {\r\n longs: String,\r\n enums: String,\r\n bytes: String,\r\n json: true\r\n};\r\n\r\n// Sets up buffer utility according to the environment (called in index-minimal)\r\nutil._configure = function() {\r\n var Buffer = util.Buffer;\r\n /* istanbul ignore if */\r\n if (!Buffer) {\r\n util._Buffer_from = util._Buffer_allocUnsafe = null;\r\n return;\r\n }\r\n // because node 4.x buffers are incompatible & immutable\r\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\r\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\r\n /* istanbul ignore next */\r\n function Buffer_from(value, encoding) {\r\n return new Buffer(value, encoding);\r\n };\r\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\r\n /* istanbul ignore next */\r\n function Buffer_allocUnsafe(size) {\r\n return new Buffer(size);\r\n };\r\n};\r\n","\"use strict\";\r\nmodule.exports = verifier;\r\n\r\nvar Enum = require(\"./enum\"),\r\n util = require(\"./util\");\r\n\r\nfunction invalid(field, expected) {\r\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\r\n}\r\n\r\n/**\r\n * Generates a partial value verifier.\r\n * @param {Codegen} gen Codegen instance\r\n * @param {Field} field Reflected field\r\n * @param {number} fieldIndex Field index\r\n * @param {string} ref Variable reference\r\n * @returns {Codegen} Codegen instance\r\n * @ignore\r\n */\r\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\r\n /* eslint-disable no-unexpected-multiline */\r\n if (field.resolvedType) {\r\n if (field.resolvedType instanceof Enum) { gen\r\n (\"switch(%s){\", ref)\r\n (\"default:\")\r\n (\"return%j\", invalid(field, \"enum value\"));\r\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\r\n (\"case %i:\", field.resolvedType.values[keys[j]]);\r\n gen\r\n (\"break\")\r\n (\"}\");\r\n } else {\r\n gen\r\n (\"{\")\r\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\r\n (\"if(e)\")\r\n (\"return%j+e\", field.name + \".\")\r\n (\"}\");\r\n }\r\n } else {\r\n switch (field.type) {\r\n case \"int32\":\r\n case \"uint32\":\r\n case \"sint32\":\r\n case \"fixed32\":\r\n case \"sfixed32\": gen\r\n (\"if(!util.isInteger(%s))\", ref)\r\n (\"return%j\", invalid(field, \"integer\"));\r\n break;\r\n case \"int64\":\r\n case \"uint64\":\r\n case \"sint64\":\r\n case \"fixed64\":\r\n case \"sfixed64\": gen\r\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\r\n (\"return%j\", invalid(field, \"integer|Long\"));\r\n break;\r\n case \"float\":\r\n case \"double\": gen\r\n (\"if(typeof %s!==\\\"number\\\")\", ref)\r\n (\"return%j\", invalid(field, \"number\"));\r\n break;\r\n case \"bool\": gen\r\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\r\n (\"return%j\", invalid(field, \"boolean\"));\r\n break;\r\n case \"string\": gen\r\n (\"if(!util.isString(%s))\", ref)\r\n (\"return%j\", invalid(field, \"string\"));\r\n break;\r\n case \"bytes\": gen\r\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\r\n (\"return%j\", invalid(field, \"buffer\"));\r\n break;\r\n }\r\n }\r\n return gen;\r\n /* eslint-enable no-unexpected-multiline */\r\n}\r\n\r\n/**\r\n * Generates a partial key verifier.\r\n * @param {Codegen} gen Codegen instance\r\n * @param {Field} field Reflected field\r\n * @param {string} ref Variable reference\r\n * @returns {Codegen} Codegen instance\r\n * @ignore\r\n */\r\nfunction genVerifyKey(gen, field, ref) {\r\n /* eslint-disable no-unexpected-multiline */\r\n switch (field.keyType) {\r\n case \"int32\":\r\n case \"uint32\":\r\n case \"sint32\":\r\n case \"fixed32\":\r\n case \"sfixed32\": gen\r\n (\"if(!util.key32Re.test(%s))\", ref)\r\n (\"return%j\", invalid(field, \"integer key\"));\r\n break;\r\n case \"int64\":\r\n case \"uint64\":\r\n case \"sint64\":\r\n case \"fixed64\":\r\n case \"sfixed64\": gen\r\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\r\n (\"return%j\", invalid(field, \"integer|Long key\"));\r\n break;\r\n case \"bool\": gen\r\n (\"if(!util.key2Re.test(%s))\", ref)\r\n (\"return%j\", invalid(field, \"boolean key\"));\r\n break;\r\n }\r\n return gen;\r\n /* eslint-enable no-unexpected-multiline */\r\n}\r\n\r\n/**\r\n * Generates a verifier specific to the specified message type.\r\n * @param {Type} mtype Message type\r\n * @returns {Codegen} Codegen instance\r\n */\r\nfunction verifier(mtype) {\r\n /* eslint-disable no-unexpected-multiline */\r\n\r\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\r\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\r\n (\"return%j\", \"object expected\");\r\n var oneofs = mtype.oneofsArray,\r\n seenFirstField = {};\r\n if (oneofs.length) gen\r\n (\"var p={}\");\r\n\r\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\r\n var field = mtype._fieldsArray[i].resolve(),\r\n ref = \"m\" + util.safeProp(field.name);\r\n\r\n if (field.optional) gen\r\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\r\n\r\n // map fields\r\n if (field.map) { gen\r\n (\"if(!util.isObject(%s))\", ref)\r\n (\"return%j\", invalid(field, \"object\"))\r\n (\"var k=Object.keys(%s)\", ref)\r\n (\"for(var i=0;i}\r\n * @const\r\n */\r\nvar wrappers = exports;\r\n\r\nvar Message = require(\"./message\");\r\n\r\n/**\r\n * From object converter part of an {@link IWrapper}.\r\n * @typedef WrapperFromObjectConverter\r\n * @type {function}\r\n * @param {Object.} object Plain object\r\n * @returns {Message<{}>} Message instance\r\n * @this Type\r\n */\r\n\r\n/**\r\n * To object converter part of an {@link IWrapper}.\r\n * @typedef WrapperToObjectConverter\r\n * @type {function}\r\n * @param {Message<{}>} message Message instance\r\n * @param {IConversionOptions} [options] Conversion options\r\n * @returns {Object.} Plain object\r\n * @this Type\r\n */\r\n\r\n/**\r\n * Common type wrapper part of {@link wrappers}.\r\n * @interface IWrapper\r\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\r\n * @property {WrapperToObjectConverter} [toObject] To object converter\r\n */\r\n\r\n// Custom wrapper for Any\r\nwrappers[\".google.protobuf.Any\"] = {\r\n\r\n fromObject: function(object) {\r\n\r\n // unwrap value type if mapped\r\n if (object && object[\"@type\"]) {\r\n // Only use fully qualified type name after the last '/'\r\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\r\n var type = this.lookup(name);\r\n /* istanbul ignore else */\r\n if (type) {\r\n // type_url does not accept leading \".\"\r\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\r\n object[\"@type\"].slice(1) : object[\"@type\"];\r\n // type_url prefix is optional, but path seperator is required\r\n if (type_url.indexOf(\"/\") === -1) {\r\n type_url = \"/\" + type_url;\r\n }\r\n return this.create({\r\n type_url: type_url,\r\n value: type.encode(type.fromObject(object)).finish()\r\n });\r\n }\r\n }\r\n\r\n return this.fromObject(object);\r\n },\r\n\r\n toObject: function(message, options) {\r\n\r\n // Default prefix\r\n var googleApi = \"type.googleapis.com/\";\r\n var prefix = \"\";\r\n var name = \"\";\r\n\r\n // decode value if requested and unmapped\r\n if (options && options.json && message.type_url && message.value) {\r\n // Only use fully qualified type name after the last '/'\r\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\r\n // Separate the prefix used\r\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\r\n var type = this.lookup(name);\r\n /* istanbul ignore else */\r\n if (type)\r\n message = type.decode(message.value);\r\n }\r\n\r\n // wrap value if unmapped\r\n if (!(message instanceof this.ctor) && message instanceof Message) {\r\n var object = message.$type.toObject(message, options);\r\n var messageName = message.$type.fullName[0] === \".\" ?\r\n message.$type.fullName.slice(1) : message.$type.fullName;\r\n // Default to type.googleapis.com prefix if no prefix is used\r\n if (prefix === \"\") {\r\n prefix = googleApi;\r\n }\r\n name = prefix + messageName;\r\n object[\"@type\"] = name;\r\n return object;\r\n }\r\n\r\n return this.toObject(message, options);\r\n }\r\n};\r\n","\"use strict\";\r\nmodule.exports = Writer;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\nvar BufferWriter; // cyclic\r\n\r\nvar LongBits = util.LongBits,\r\n base64 = util.base64,\r\n utf8 = util.utf8;\r\n\r\n/**\r\n * Constructs a new writer operation instance.\r\n * @classdesc Scheduled writer operation.\r\n * @constructor\r\n * @param {function(*, Uint8Array, number)} fn Function to call\r\n * @param {number} len Value byte length\r\n * @param {*} val Value to write\r\n * @ignore\r\n */\r\nfunction Op(fn, len, val) {\r\n\r\n /**\r\n * Function to call.\r\n * @type {function(Uint8Array, number, *)}\r\n */\r\n this.fn = fn;\r\n\r\n /**\r\n * Value byte length.\r\n * @type {number}\r\n */\r\n this.len = len;\r\n\r\n /**\r\n * Next operation.\r\n * @type {Writer.Op|undefined}\r\n */\r\n this.next = undefined;\r\n\r\n /**\r\n * Value to write.\r\n * @type {*}\r\n */\r\n this.val = val; // type varies\r\n}\r\n\r\n/* istanbul ignore next */\r\nfunction noop() {} // eslint-disable-line no-empty-function\r\n\r\n/**\r\n * Constructs a new writer state instance.\r\n * @classdesc Copied writer state.\r\n * @memberof Writer\r\n * @constructor\r\n * @param {Writer} writer Writer to copy state from\r\n * @ignore\r\n */\r\nfunction State(writer) {\r\n\r\n /**\r\n * Current head.\r\n * @type {Writer.Op}\r\n */\r\n this.head = writer.head;\r\n\r\n /**\r\n * Current tail.\r\n * @type {Writer.Op}\r\n */\r\n this.tail = writer.tail;\r\n\r\n /**\r\n * Current buffer length.\r\n * @type {number}\r\n */\r\n this.len = writer.len;\r\n\r\n /**\r\n * Next state.\r\n * @type {State|null}\r\n */\r\n this.next = writer.states;\r\n}\r\n\r\n/**\r\n * Constructs a new writer instance.\r\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\r\n * @constructor\r\n */\r\nfunction Writer() {\r\n\r\n /**\r\n * Current length.\r\n * @type {number}\r\n */\r\n this.len = 0;\r\n\r\n /**\r\n * Operations head.\r\n * @type {Object}\r\n */\r\n this.head = new Op(noop, 0, 0);\r\n\r\n /**\r\n * Operations tail\r\n * @type {Object}\r\n */\r\n this.tail = this.head;\r\n\r\n /**\r\n * Linked forked states.\r\n * @type {Object|null}\r\n */\r\n this.states = null;\r\n\r\n // When a value is written, the writer calculates its byte length and puts it into a linked\r\n // list of operations to perform when finish() is called. This both allows us to allocate\r\n // buffers of the exact required size and reduces the amount of work we have to do compared\r\n // to first calculating over objects and then encoding over objects. In our case, the encoding\r\n // part is just a linked list walk calling operations with already prepared values.\r\n}\r\n\r\nvar create = function create() {\r\n return util.Buffer\r\n ? function create_buffer_setup() {\r\n return (Writer.create = function create_buffer() {\r\n return new BufferWriter();\r\n })();\r\n }\r\n /* istanbul ignore next */\r\n : function create_array() {\r\n return new Writer();\r\n };\r\n};\r\n\r\n/**\r\n * Creates a new writer.\r\n * @function\r\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\r\n */\r\nWriter.create = create();\r\n\r\n/**\r\n * Allocates a buffer of the specified size.\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\nWriter.alloc = function alloc(size) {\r\n return new util.Array(size);\r\n};\r\n\r\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\r\n/* istanbul ignore else */\r\nif (util.Array !== Array)\r\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\r\n\r\n/**\r\n * Pushes a new operation to the queue.\r\n * @param {function(Uint8Array, number, *)} fn Function to call\r\n * @param {number} len Value byte length\r\n * @param {number} val Value to write\r\n * @returns {Writer} `this`\r\n * @private\r\n */\r\nWriter.prototype._push = function push(fn, len, val) {\r\n this.tail = this.tail.next = new Op(fn, len, val);\r\n this.len += len;\r\n return this;\r\n};\r\n\r\nfunction writeByte(val, buf, pos) {\r\n buf[pos] = val & 255;\r\n}\r\n\r\nfunction writeVarint32(val, buf, pos) {\r\n while (val > 127) {\r\n buf[pos++] = val & 127 | 128;\r\n val >>>= 7;\r\n }\r\n buf[pos] = val;\r\n}\r\n\r\n/**\r\n * Constructs a new varint writer operation instance.\r\n * @classdesc Scheduled varint writer operation.\r\n * @extends Op\r\n * @constructor\r\n * @param {number} len Value byte length\r\n * @param {number} val Value to write\r\n * @ignore\r\n */\r\nfunction VarintOp(len, val) {\r\n this.len = len;\r\n this.next = undefined;\r\n this.val = val;\r\n}\r\n\r\nVarintOp.prototype = Object.create(Op.prototype);\r\nVarintOp.prototype.fn = writeVarint32;\r\n\r\n/**\r\n * Writes an unsigned 32 bit value as a varint.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.uint32 = function write_uint32(value) {\r\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\r\n // uint32 is by far the most frequently used operation and benefits significantly from this.\r\n this.len += (this.tail = this.tail.next = new VarintOp(\r\n (value = value >>> 0)\r\n < 128 ? 1\r\n : value < 16384 ? 2\r\n : value < 2097152 ? 3\r\n : value < 268435456 ? 4\r\n : 5,\r\n value)).len;\r\n return this;\r\n};\r\n\r\n/**\r\n * Writes a signed 32 bit value as a varint.\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.int32 = function write_int32(value) {\r\n return value < 0\r\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\r\n : this.uint32(value);\r\n};\r\n\r\n/**\r\n * Writes a 32 bit value as a varint, zig-zag encoded.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.sint32 = function write_sint32(value) {\r\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\r\n};\r\n\r\nfunction writeVarint64(val, buf, pos) {\r\n while (val.hi) {\r\n buf[pos++] = val.lo & 127 | 128;\r\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\r\n val.hi >>>= 7;\r\n }\r\n while (val.lo > 127) {\r\n buf[pos++] = val.lo & 127 | 128;\r\n val.lo = val.lo >>> 7;\r\n }\r\n buf[pos++] = val.lo;\r\n}\r\n\r\n/**\r\n * Writes an unsigned 64 bit value as a varint.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.uint64 = function write_uint64(value) {\r\n var bits = LongBits.from(value);\r\n return this._push(writeVarint64, bits.length(), bits);\r\n};\r\n\r\n/**\r\n * Writes a signed 64 bit value as a varint.\r\n * @function\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.int64 = Writer.prototype.uint64;\r\n\r\n/**\r\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.sint64 = function write_sint64(value) {\r\n var bits = LongBits.from(value).zzEncode();\r\n return this._push(writeVarint64, bits.length(), bits);\r\n};\r\n\r\n/**\r\n * Writes a boolish value as a varint.\r\n * @param {boolean} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.bool = function write_bool(value) {\r\n return this._push(writeByte, 1, value ? 1 : 0);\r\n};\r\n\r\nfunction writeFixed32(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\n/**\r\n * Writes an unsigned 32 bit value as fixed 32 bits.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.fixed32 = function write_fixed32(value) {\r\n return this._push(writeFixed32, 4, value >>> 0);\r\n};\r\n\r\n/**\r\n * Writes a signed 32 bit value as fixed 32 bits.\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\r\n\r\n/**\r\n * Writes an unsigned 64 bit value as fixed 64 bits.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.fixed64 = function write_fixed64(value) {\r\n var bits = LongBits.from(value);\r\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\r\n};\r\n\r\n/**\r\n * Writes a signed 64 bit value as fixed 64 bits.\r\n * @function\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\r\n\r\n/**\r\n * Writes a float (32 bit).\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.float = function write_float(value) {\r\n return this._push(util.float.writeFloatLE, 4, value);\r\n};\r\n\r\n/**\r\n * Writes a double (64 bit float).\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.double = function write_double(value) {\r\n return this._push(util.float.writeDoubleLE, 8, value);\r\n};\r\n\r\nvar writeBytes = util.Array.prototype.set\r\n ? function writeBytes_set(val, buf, pos) {\r\n buf.set(val, pos); // also works for plain array values\r\n }\r\n /* istanbul ignore next */\r\n : function writeBytes_for(val, buf, pos) {\r\n for (var i = 0; i < val.length; ++i)\r\n buf[pos + i] = val[i];\r\n };\r\n\r\n/**\r\n * Writes a sequence of bytes.\r\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.bytes = function write_bytes(value) {\r\n var len = value.length >>> 0;\r\n if (!len)\r\n return this._push(writeByte, 1, 0);\r\n if (util.isString(value)) {\r\n var buf = Writer.alloc(len = base64.length(value));\r\n base64.decode(value, buf, 0);\r\n value = buf;\r\n }\r\n return this.uint32(len)._push(writeBytes, len, value);\r\n};\r\n\r\n/**\r\n * Writes a string.\r\n * @param {string} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.string = function write_string(value) {\r\n var len = utf8.length(value);\r\n return len\r\n ? this.uint32(len)._push(utf8.write, len, value)\r\n : this._push(writeByte, 1, 0);\r\n};\r\n\r\n/**\r\n * Forks this writer's state by pushing it to a stack.\r\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.fork = function fork() {\r\n this.states = new State(this);\r\n this.head = this.tail = new Op(noop, 0, 0);\r\n this.len = 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Resets this instance to the last state.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.reset = function reset() {\r\n if (this.states) {\r\n this.head = this.states.head;\r\n this.tail = this.states.tail;\r\n this.len = this.states.len;\r\n this.states = this.states.next;\r\n } else {\r\n this.head = this.tail = new Op(noop, 0, 0);\r\n this.len = 0;\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.ldelim = function ldelim() {\r\n var head = this.head,\r\n tail = this.tail,\r\n len = this.len;\r\n this.reset().uint32(len);\r\n if (len) {\r\n this.tail.next = head.next; // skip noop\r\n this.tail = tail;\r\n this.len += len;\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Finishes the write operation.\r\n * @returns {Uint8Array} Finished buffer\r\n */\r\nWriter.prototype.finish = function finish() {\r\n var head = this.head.next, // skip noop\r\n buf = this.constructor.alloc(this.len),\r\n pos = 0;\r\n while (head) {\r\n head.fn(head.val, buf, pos);\r\n pos += head.len;\r\n head = head.next;\r\n }\r\n // this.head = this.tail = null;\r\n return buf;\r\n};\r\n\r\nWriter._configure = function(BufferWriter_) {\r\n BufferWriter = BufferWriter_;\r\n Writer.create = create();\r\n BufferWriter._configure();\r\n};\r\n","\"use strict\";\r\nmodule.exports = BufferWriter;\r\n\r\n// extends Writer\r\nvar Writer = require(\"./writer\");\r\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\n/**\r\n * Constructs a new buffer writer instance.\r\n * @classdesc Wire format writer using node buffers.\r\n * @extends Writer\r\n * @constructor\r\n */\r\nfunction BufferWriter() {\r\n Writer.call(this);\r\n}\r\n\r\nBufferWriter._configure = function () {\r\n /**\r\n * Allocates a buffer of the specified size.\r\n * @function\r\n * @param {number} size Buffer size\r\n * @returns {Buffer} Buffer\r\n */\r\n BufferWriter.alloc = util._Buffer_allocUnsafe;\r\n\r\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\r\n ? function writeBytesBuffer_set(val, buf, pos) {\r\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\r\n // also works for plain array values\r\n }\r\n /* istanbul ignore next */\r\n : function writeBytesBuffer_copy(val, buf, pos) {\r\n if (val.copy) // Buffer values\r\n val.copy(buf, pos, 0, val.length);\r\n else for (var i = 0; i < val.length;) // plain array values\r\n buf[pos++] = val[i++];\r\n };\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\r\n if (util.isString(value))\r\n value = util._Buffer_from(value, \"base64\");\r\n var len = value.length >>> 0;\r\n this.uint32(len);\r\n if (len)\r\n this._push(BufferWriter.writeBytesBuffer, len, value);\r\n return this;\r\n};\r\n\r\nfunction writeStringBuffer(val, buf, pos) {\r\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\r\n util.utf8.write(val, buf, pos);\r\n else if (buf.utf8Write)\r\n buf.utf8Write(val, pos);\r\n else\r\n buf.write(val, pos);\r\n}\r\n\r\n/**\r\n * @override\r\n */\r\nBufferWriter.prototype.string = function write_string_buffer(value) {\r\n var len = util.Buffer.byteLength(value);\r\n this.uint32(len);\r\n if (len)\r\n this._push(writeStringBuffer, len, value);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Finishes the write operation.\r\n * @name BufferWriter#finish\r\n * @function\r\n * @returns {Buffer} Finished buffer\r\n */\r\n\r\nBufferWriter._configure();\r\n","/*!\n * MIT License\n * \n * Copyright (c) 2017-2022 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n'use strict';\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","__webpack_require__.amdO = {};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map","/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc';\nconst N1 = Math.pow(2, 7);\nconst N2 = Math.pow(2, 14);\nconst N3 = Math.pow(2, 21);\nconst N4 = Math.pow(2, 28);\nconst N5 = Math.pow(2, 35);\nconst N6 = Math.pow(2, 42);\nconst N7 = Math.pow(2, 49);\n/** Most significant bit of a byte */\nconst MSB = 0x80;\n/** Rest of the bits in a byte */\nconst REST = 0x7f;\nexport function encodingLength(value) {\n if (value < N1) {\n return 1;\n }\n if (value < N2) {\n return 2;\n }\n if (value < N3) {\n return 3;\n }\n if (value < N4) {\n return 4;\n }\n if (value < N5) {\n return 5;\n }\n if (value < N6) {\n return 6;\n }\n if (value < N7) {\n return 7;\n }\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint');\n }\n return 8;\n}\nexport function encodeUint8Array(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 1: {\n buf[offset++] = (value & 0xFF);\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function encodeUint8ArrayList(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 1: {\n buf.set(offset++, (value & 0xFF));\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function decodeUint8Array(buf, offset) {\n let b = buf[offset];\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 1];\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 2];\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 3];\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 4];\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 5];\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 6];\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 7];\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function decodeUint8ArrayList(buf, offset) {\n let b = buf.get(offset);\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 1);\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 2);\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 3);\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 4);\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 5);\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 6);\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 7);\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function encode(value, buf, offset = 0) {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value));\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset);\n }\n else {\n return encodeUint8ArrayList(value, buf, offset);\n }\n}\nexport function decode(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset);\n }\n else {\n return decodeUint8ArrayList(buf, offset);\n }\n}\n//# sourceMappingURL=index.js.map","const f32 = new Float32Array([-0]);\nconst f8b = new Uint8Array(f32.buffer);\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[0];\n buf[pos + 1] = f8b[1];\n buf[pos + 2] = f8b[2];\n buf[pos + 3] = f8b[3];\n}\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[3];\n buf[pos + 1] = f8b[2];\n buf[pos + 2] = f8b[1];\n buf[pos + 3] = f8b[0];\n}\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE(buf, pos) {\n f8b[0] = buf[pos];\n f8b[1] = buf[pos + 1];\n f8b[2] = buf[pos + 2];\n f8b[3] = buf[pos + 3];\n return f32[0];\n}\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE(buf, pos) {\n f8b[3] = buf[pos];\n f8b[2] = buf[pos + 1];\n f8b[1] = buf[pos + 2];\n f8b[0] = buf[pos + 3];\n return f32[0];\n}\nconst f64 = new Float64Array([-0]);\nconst d8b = new Uint8Array(f64.buffer);\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[0];\n buf[pos + 1] = d8b[1];\n buf[pos + 2] = d8b[2];\n buf[pos + 3] = d8b[3];\n buf[pos + 4] = d8b[4];\n buf[pos + 5] = d8b[5];\n buf[pos + 6] = d8b[6];\n buf[pos + 7] = d8b[7];\n}\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[7];\n buf[pos + 1] = d8b[6];\n buf[pos + 2] = d8b[5];\n buf[pos + 3] = d8b[4];\n buf[pos + 4] = d8b[3];\n buf[pos + 5] = d8b[2];\n buf[pos + 6] = d8b[1];\n buf[pos + 7] = d8b[0];\n}\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE(buf, pos) {\n d8b[0] = buf[pos];\n d8b[1] = buf[pos + 1];\n d8b[2] = buf[pos + 2];\n d8b[3] = buf[pos + 3];\n d8b[4] = buf[pos + 4];\n d8b[5] = buf[pos + 5];\n d8b[6] = buf[pos + 6];\n d8b[7] = buf[pos + 7];\n return f64[0];\n}\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE(buf, pos) {\n d8b[7] = buf[pos];\n d8b[6] = buf[pos + 1];\n d8b[5] = buf[pos + 2];\n d8b[4] = buf[pos + 3];\n d8b[3] = buf[pos + 4];\n d8b[2] = buf[pos + 5];\n d8b[1] = buf[pos + 6];\n d8b[0] = buf[pos + 7];\n return f64[0];\n}\n//# sourceMappingURL=float.js.map","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n lo;\n hi;\n constructor(lo, hi) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n /**\n * Low bits\n */\n this.lo = lo | 0;\n /**\n * High bits\n */\n this.hi = hi | 0;\n }\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber(unsigned = false) {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n }\n /**\n * Converts this long bits to a bigint\n */\n toBigInt(unsigned = false) {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n));\n }\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n /**\n * Converts this long bits to a string\n */\n toString(unsigned = false) {\n return this.toBigInt(unsigned).toString();\n }\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode() {\n const mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = (this.lo << 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode() {\n const mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = (this.hi >>> 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length() {\n const part0 = this.lo;\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;\n const part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt(value) {\n if (value === 0n) {\n return zero;\n }\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value));\n }\n const negative = value < 0n;\n if (negative) {\n value = -value;\n }\n let hi = value >> 32n;\n let lo = value - (hi << 32n);\n if (negative) {\n hi = ~hi | 0n;\n lo = ~lo | 0n;\n if (++lo > TWO_32) {\n lo = 0n;\n if (++hi > TWO_32) {\n hi = 0n;\n }\n }\n }\n return new LongBits(Number(lo), Number(hi));\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber(value) {\n if (value === 0) {\n return zero;\n }\n const sign = value < 0;\n if (sign) {\n value = -value;\n }\n let lo = value >>> 0;\n let hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295) {\n hi = 0;\n }\n }\n }\n return new LongBits(lo, hi);\n }\n /**\n * Constructs new long bits from a number, long or string\n */\n static from(value) {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value);\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value);\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value));\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n }\n}\nconst zero = new LongBits(0, 0);\nzero.toBigInt = function () { return 0n; };\nzero.zzEncode = zero.zzDecode = function () { return this; };\nzero.length = function () { return 1; };\nconst TWO_32 = 4294967296n;\n//# sourceMappingURL=longbits.js.map","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length(string) {\n let len = 0;\n let c = 0;\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i);\n if (c < 128) {\n len += 1;\n }\n else if (c < 2048) {\n len += 2;\n }\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i;\n len += 4;\n }\n else {\n len += 3;\n }\n }\n return len;\n}\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read(buffer, start, end) {\n const len = end - start;\n if (len < 1) {\n return '';\n }\n let parts;\n const chunk = [];\n let i = 0; // char offset\n let t; // temporary\n while (start < end) {\n t = buffer[start++];\n if (t < 128) {\n chunk[i++] = t;\n }\n else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\n }\n else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\n chunk[i++] = 0xD800 + (t >> 10);\n chunk[i++] = 0xDC00 + (t & 1023);\n }\n else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\n }\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n }\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write(string, buffer, offset) {\n const start = offset;\n let c1; // character 1\n let c2; // character 2\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i);\n if (c1 < 128) {\n buffer[offset++] = c1;\n }\n else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192;\n buffer[offset++] = c1 & 63 | 128;\n }\n else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\n ++i;\n buffer[offset++] = c1 >> 18 | 240;\n buffer[offset++] = c1 >> 12 & 63 | 128;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n else {\n buffer[offset++] = c1 >> 12 | 224;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n }\n return offset - start;\n}\n//# sourceMappingURL=utf8.js.map","import { decodeUint8Array, encodingLength } from 'uint8-varint';\nimport { readFloatLE, readDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport * as utf8 from './utf8.js';\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);\n}\nfunction readFixed32End(buf, end) {\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0;\n}\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader {\n buf;\n pos;\n len;\n _slice = Uint8Array.prototype.subarray;\n constructor(buffer) {\n /**\n * Read buffer\n */\n this.buf = buffer;\n /**\n * Read buffer position\n */\n this.pos = 0;\n /**\n * Read buffer length\n */\n this.len = buffer.length;\n }\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32() {\n let value = 4294967295;\n value = (this.buf[this.pos] & 127) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n }\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32() {\n const value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n }\n /**\n * Reads a varint as a boolean\n */\n bool() {\n return this.uint32() !== 0;\n }\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4);\n return res;\n }\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4) | 0;\n return res;\n }\n /**\n * Reads a float (32 bit) as a number\n */\n float() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n }\n /**\n * Reads a double (64 bit float) as a number\n */\n double() {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n }\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes() {\n const length = this.uint32();\n const start = this.pos;\n const end = this.pos + length;\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end);\n }\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string() {\n const bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n }\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip(length) {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n }\n else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n } while ((this.buf[this.pos++] & 128) !== 0);\n }\n return this;\n }\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);\n }\n return this;\n }\n readLongVarint() {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0);\n let i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n i = 0;\n }\n else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n throw Error('invalid varint encoding');\n }\n readFixed64() {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8);\n }\n const lo = readFixed32End(this.buf, this.pos += 4);\n const hi = readFixed32End(this.buf, this.pos += 4);\n return new LongBits(lo, hi);\n }\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64() {\n return this.readLongVarint().toBigInt();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number() {\n return this.readLongVarint().toNumber();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String() {\n return this.readLongVarint().toString();\n }\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64() {\n return this.readLongVarint().toBigInt(true);\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number() {\n const value = decodeUint8Array(this.buf, this.pos);\n this.pos += encodingLength(value);\n return value;\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String() {\n return this.readLongVarint().toString(true);\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64() {\n return this.readLongVarint().zzDecode().toBigInt();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number() {\n return this.readLongVarint().zzDecode().toNumber();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String() {\n return this.readLongVarint().zzDecode().toString();\n }\n /**\n * Reads fixed 64 bits\n */\n fixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String() {\n return this.readFixed64().toString();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String() {\n return this.readFixed64().toString();\n }\n}\nexport function createReader(buf) {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());\n}\n//# sourceMappingURL=reader.js.map","import { createReader } from './utils/reader.js';\nexport function decodeMessage(buf, codec, opts) {\n const reader = createReader(buf);\n return codec.decode(reader, undefined, opts);\n}\n//# sourceMappingURL=decode.js.map","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nexport function fromString(str) {\n return new TextEncoder().encode(str);\n}\nexport function toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from '../bytes.js';\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet }) {\n const { encode, decode } = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map","import { from } from './base.js';\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map","import { fromString, toString } from '../bytes.js';\nimport { from } from './base.js';\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n});\n//# sourceMappingURL=identity.js.map","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 0x0200;\nexport function encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nexport function decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map","import { coerce } from '../bytes.js';\nexport const name = 'raw';\nexport const code = 0x55;\nexport function encode(node) {\n return coerce(node);\n}\nexport function decode(data) {\n return coerce(data);\n}\n//# sourceMappingURL=raw.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n return [code, varint.decode.bytes];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes } from '../bytes.js';\nimport * as varint from '../varint.js';\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0x0;\nconst name = 'identity';\nconst encode = coerce;\nfunction digest(input) {\n return Digest.create(code, encode(input));\n}\nexport const identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map","import * as Digest from './digest.js';\nexport function from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map","/* global crypto */\nimport { from } from './hasher.js';\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import { base32 } from './bases/base32.js';\nimport { base58btc } from './bases/base58.js';\nimport { coerce } from './bytes.js';\nimport * as Digest from './hashes/digest.js';\nimport * as varint from './varint.js';\n// This way TS will also expose all the types from module\nexport * from './link/interface.js';\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","import * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base2 from './bases/base2.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base8 from './bases/base8.js';\nimport * as identityBase from './bases/identity.js';\nimport * as json from './codecs/json.js';\nimport * as raw from './codecs/raw.js';\nimport * as identity from './hashes/identity.js';\nimport * as sha2 from './hashes/sha2.js';\nimport { CID, hasher, digest, varint, bytes } from './index.js';\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };\nexport const hashes = { ...sha2, ...identity };\nexport const codecs = { raw, json };\nexport { CID, hasher, digest, varint, bytes };\n//# sourceMappingURL=basics.js.map","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '#alloc';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;\n//# sourceMappingURL=bases.js.map","import bases, {} from './util/bases.js';\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map","import { encodeUint8Array, encodingLength } from 'uint8-varint';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { writeFloatLE, writeDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport pool from './pool.js';\nimport * as utf8 from './utf8.js';\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n fn;\n /**\n * Value byte length\n */\n len;\n /**\n * Next operation\n */\n next;\n /**\n * Value to write\n */\n val;\n constructor(fn, len, val) {\n this.fn = fn;\n this.len = len;\n this.next = undefined;\n this.val = val; // type varies\n }\n}\n/* istanbul ignore next */\nfunction noop() { } // eslint-disable-line no-empty-function\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n head;\n /**\n * Current tail\n */\n tail;\n /**\n * Current buffer length\n */\n len;\n /**\n * Next state\n */\n next;\n constructor(writer) {\n this.head = writer.head;\n this.tail = writer.tail;\n this.len = writer.len;\n this.next = writer.states;\n }\n}\nconst bufferPool = pool();\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc(size) {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size);\n }\n return bufferPool(size);\n}\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter {\n /**\n * Current length\n */\n len;\n /**\n * Operations head\n */\n head;\n /**\n * Operations tail\n */\n tail;\n /**\n * Linked forked states\n */\n states;\n constructor() {\n this.len = 0;\n this.head = new Op(noop, 0, 0);\n this.tail = this.head;\n this.states = null;\n }\n /**\n * Pushes a new operation to the queue\n */\n _push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n }\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5, value)).len;\n return this;\n }\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n }\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value) {\n return this._push(encodeUint8Array, encodingLength(value), value);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value) {\n return this.uint64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value) {\n return this.uint64(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value) {\n return this.uint64Number(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value) {\n return this.uint64String(value);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value) {\n const bits = LongBits.fromBigInt(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value) {\n const bits = LongBits.fromNumber(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value) {\n return this.sint64(BigInt(value));\n }\n /**\n * Writes a boolish value as a varint\n */\n bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n }\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n }\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value) {\n return this.fixed32(value);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value) {\n const bits = LongBits.fromNumber(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value) {\n return this.fixed64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value) {\n return this.fixed64(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value) {\n return this.fixed64Number(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value) {\n return this.fixed64String(value);\n }\n /**\n * Writes a float (32 bit)\n */\n float(value) {\n return this._push(writeFloatLE, 4, value);\n }\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double(value) {\n return this._push(writeDoubleLE, 8, value);\n }\n /**\n * Writes a sequence of bytes\n */\n bytes(value) {\n const len = value.length >>> 0;\n if (len === 0) {\n return this._push(writeByte, 1, 0);\n }\n return this.uint32(len)._push(writeBytes, len, value);\n }\n /**\n * Writes a string\n */\n string(value) {\n const len = utf8.length(value);\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n }\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n }\n /**\n * Resets this instance to the last state\n */\n reset() {\n if (this.states != null) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n }\n else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n }\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim() {\n const head = this.head;\n const tail = this.tail;\n const len = this.len;\n this.reset().uint32(len);\n if (len !== 0) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n }\n /**\n * Finishes the write operation\n */\n finish() {\n let head = this.head.next; // skip noop\n const buf = alloc(this.len);\n let pos = 0;\n while (head != null) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n }\n}\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n next;\n constructor(len, val) {\n super(writeVarint32, len, val);\n this.next = undefined;\n }\n}\nfunction writeVarint64(val, buf, pos) {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\nfunction writeFixed32(val, buf, pos) {\n buf[pos] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\nfunction writeBytes(val, buf, pos) {\n buf.set(val, pos);\n}\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value) {\n const len = value.length >>> 0;\n this.uint32(len);\n if (len > 0) {\n this._push(writeBytesBuffer, len, value);\n }\n return this;\n };\n Uint8ArrayWriter.prototype.string = function (value) {\n const len = globalThis.Buffer.byteLength(value);\n this.uint32(len);\n if (len > 0) {\n this._push(writeStringBuffer, len, value);\n }\n return this;\n };\n}\nfunction writeBytesBuffer(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos);\n // @ts-expect-error buf isn't a Uint8Array?\n }\n else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos);\n }\n else {\n buf.set(uint8ArrayFromString(val), pos);\n }\n}\n/**\n * Creates a new writer\n */\nexport function createWriter() {\n return new Uint8ArrayWriter();\n}\n//# sourceMappingURL=writer.js.map","import { allocUnsafe } from 'uint8arrays/alloc';\n/**\n * A general purpose buffer pool\n */\nexport default function pool(size) {\n const SIZE = size ?? 8192;\n const MAX = SIZE >>> 1;\n let slab;\n let offset = SIZE;\n return function poolAlloc(size) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size);\n }\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE);\n offset = 0;\n }\n const buf = slab.subarray(offset, offset += size);\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1;\n }\n return buf;\n };\n}\n//# sourceMappingURL=pool.js.map","import { createWriter } from './utils/writer.js';\nexport function encodeMessage(message, codec) {\n const w = createWriter();\n codec.encode(message, w, {\n lengthDelimited: false\n });\n return w.finish();\n}\n//# sourceMappingURL=encode.js.map","// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport var CODEC_TYPES;\n(function (CODEC_TYPES) {\n CODEC_TYPES[CODEC_TYPES[\"VARINT\"] = 0] = \"VARINT\";\n CODEC_TYPES[CODEC_TYPES[\"BIT64\"] = 1] = \"BIT64\";\n CODEC_TYPES[CODEC_TYPES[\"LENGTH_DELIMITED\"] = 2] = \"LENGTH_DELIMITED\";\n CODEC_TYPES[CODEC_TYPES[\"START_GROUP\"] = 3] = \"START_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"END_GROUP\"] = 4] = \"END_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"BIT32\"] = 5] = \"BIT32\";\n})(CODEC_TYPES || (CODEC_TYPES = {}));\nexport function createCodec(name, type, encode, decode) {\n return {\n name,\n type,\n encode,\n decode\n };\n}\n//# sourceMappingURL=codec.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterRequest;\n(function (FilterRequest) {\n let ContentFilter;\n (function (ContentFilter) {\n let _codec;\n ContentFilter.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(10);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ContentFilter.encode = (obj) => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n ContentFilter.decode = (buf, opts) => {\n return decodeMessage(buf, ContentFilter.codec(), opts);\n };\n })(ContentFilter = FilterRequest.ContentFilter || (FilterRequest.ContentFilter = {}));\n let _codec;\n FilterRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.subscribe != null && obj.subscribe !== false)) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n w.uint32(26);\n FilterRequest.ContentFilter.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscribe: false,\n topic: '',\n contentFilters: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n case 3: {\n if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {\n throw new CodeError('decode error - map field \"contentFilters\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.contentFilters.push(FilterRequest.ContentFilter.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.contentFilters$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRequest.encode = (obj) => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n FilterRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRequest.codec(), opts);\n };\n})(FilterRequest || (FilterRequest = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(10);\n WakuMessage.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var FilterRpc;\n(function (FilterRpc) {\n let _codec;\n FilterRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n FilterRequest.codec().encode(obj.request, w);\n }\n if (obj.push != null) {\n w.uint32(26);\n MessagePush.codec().encode(obj.push, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = FilterRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.push = MessagePush.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.push\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRpc.encode = (obj) => {\n return encodeMessage(obj, FilterRpc.codec());\n };\n FilterRpc.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRpc.codec(), opts);\n };\n})(FilterRpc || (FilterRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var TopicOnlyMessage;\n(function (TopicOnlyMessage) {\n let _codec;\n TopicOnlyMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n TopicOnlyMessage.encode = (obj) => {\n return encodeMessage(obj, TopicOnlyMessage.codec());\n };\n TopicOnlyMessage.decode = (buf, opts) => {\n return decodeMessage(buf, TopicOnlyMessage.codec(), opts);\n };\n})(TopicOnlyMessage || (TopicOnlyMessage = {}));\n//# sourceMappingURL=topic_only_message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, enumeration, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterSubscribeRequest;\n(function (FilterSubscribeRequest) {\n let FilterSubscribeType;\n (function (FilterSubscribeType) {\n FilterSubscribeType[\"SUBSCRIBER_PING\"] = \"SUBSCRIBER_PING\";\n FilterSubscribeType[\"SUBSCRIBE\"] = \"SUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE\"] = \"UNSUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE_ALL\"] = \"UNSUBSCRIBE_ALL\";\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let __FilterSubscribeTypeValues;\n (function (__FilterSubscribeTypeValues) {\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBER_PING\"] = 0] = \"SUBSCRIBER_PING\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBE\"] = 1] = \"SUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE\"] = 2] = \"UNSUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE_ALL\"] = 3] = \"UNSUBSCRIBE_ALL\";\n })(__FilterSubscribeTypeValues || (__FilterSubscribeTypeValues = {}));\n (function (FilterSubscribeType) {\n FilterSubscribeType.codec = () => {\n return enumeration(__FilterSubscribeTypeValues);\n };\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let _codec;\n FilterSubscribeRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.filterSubscribeType != null && __FilterSubscribeTypeValues[obj.filterSubscribeType] !== 0) {\n w.uint32(16);\n FilterSubscribeRequest.FilterSubscribeType.codec().encode(obj.filterSubscribeType, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(82);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentTopics != null) {\n for (const value of obj.contentTopics) {\n w.uint32(90);\n w.string(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n filterSubscribeType: FilterSubscribeType.SUBSCRIBER_PING,\n contentTopics: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.filterSubscribeType = FilterSubscribeRequest.FilterSubscribeType.codec().decode(reader);\n break;\n }\n case 10: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 11: {\n if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {\n throw new CodeError('decode error - map field \"contentTopics\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.contentTopics.push(reader.string());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeRequest.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeRequest.codec());\n };\n FilterSubscribeRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeRequest.codec(), opts);\n };\n})(FilterSubscribeRequest || (FilterSubscribeRequest = {}));\nexport var FilterSubscribeResponse;\n(function (FilterSubscribeResponse) {\n let _codec;\n FilterSubscribeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if ((obj.statusCode != null && obj.statusCode !== 0)) {\n w.uint32(80);\n w.uint32(obj.statusCode);\n }\n if (obj.statusDesc != null) {\n w.uint32(90);\n w.string(obj.statusDesc);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n statusCode: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 10: {\n obj.statusCode = reader.uint32();\n break;\n }\n case 11: {\n obj.statusDesc = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeResponse.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeResponse.codec());\n };\n FilterSubscribeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeResponse.codec(), opts);\n };\n})(FilterSubscribeResponse || (FilterSubscribeResponse = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.wakuMessage != null) {\n w.uint32(10);\n WakuMessage.codec().encode(obj.wakuMessage, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(18);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.wakuMessage = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.wakuMessage\n });\n break;\n }\n case 2: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter_v2.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var PushRequest;\n(function (PushRequest) {\n let _codec;\n PushRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.pubsubTopic != null && obj.pubsubTopic !== '')) {\n w.uint32(10);\n w.string(obj.pubsubTopic);\n }\n if (obj.message != null) {\n w.uint32(18);\n WakuMessage.codec().encode(obj.message, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n pubsubTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 2: {\n obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.message\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRequest.encode = (obj) => {\n return encodeMessage(obj, PushRequest.codec());\n };\n PushRequest.decode = (buf, opts) => {\n return decodeMessage(buf, PushRequest.codec(), opts);\n };\n})(PushRequest || (PushRequest = {}));\nexport var PushResponse;\n(function (PushResponse) {\n let _codec;\n PushResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.isSuccess != null && obj.isSuccess !== false)) {\n w.uint32(8);\n w.bool(obj.isSuccess);\n }\n if (obj.info != null) {\n w.uint32(18);\n w.string(obj.info);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n isSuccess: false\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.isSuccess = reader.bool();\n break;\n }\n case 2: {\n obj.info = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushResponse.encode = (obj) => {\n return encodeMessage(obj, PushResponse.codec());\n };\n PushResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PushResponse.codec(), opts);\n };\n})(PushResponse || (PushResponse = {}));\nexport var PushRpc;\n(function (PushRpc) {\n let _codec;\n PushRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n PushRequest.codec().encode(obj.request, w);\n }\n if (obj.response != null) {\n w.uint32(26);\n PushResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = PushRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.response = PushResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRpc.encode = (obj) => {\n return encodeMessage(obj, PushRpc.codec());\n };\n PushRpc.decode = (buf, opts) => {\n return decodeMessage(buf, PushRpc.codec(), opts);\n };\n})(PushRpc || (PushRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=light_push.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, enumeration, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var Index;\n(function (Index) {\n let _codec;\n Index.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.digest != null && obj.digest.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.digest);\n }\n if ((obj.receiverTime != null && obj.receiverTime !== 0n)) {\n w.uint32(16);\n w.sint64(obj.receiverTime);\n }\n if ((obj.senderTime != null && obj.senderTime !== 0n)) {\n w.uint32(24);\n w.sint64(obj.senderTime);\n }\n if ((obj.pubsubTopic != null && obj.pubsubTopic !== '')) {\n w.uint32(34);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n digest: uint8ArrayAlloc(0),\n receiverTime: 0n,\n senderTime: 0n,\n pubsubTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.digest = reader.bytes();\n break;\n }\n case 2: {\n obj.receiverTime = reader.sint64();\n break;\n }\n case 3: {\n obj.senderTime = reader.sint64();\n break;\n }\n case 4: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Index.encode = (obj) => {\n return encodeMessage(obj, Index.codec());\n };\n Index.decode = (buf, opts) => {\n return decodeMessage(buf, Index.codec(), opts);\n };\n})(Index || (Index = {}));\nexport var PagingInfo;\n(function (PagingInfo) {\n let Direction;\n (function (Direction) {\n Direction[\"BACKWARD\"] = \"BACKWARD\";\n Direction[\"FORWARD\"] = \"FORWARD\";\n })(Direction = PagingInfo.Direction || (PagingInfo.Direction = {}));\n let __DirectionValues;\n (function (__DirectionValues) {\n __DirectionValues[__DirectionValues[\"BACKWARD\"] = 0] = \"BACKWARD\";\n __DirectionValues[__DirectionValues[\"FORWARD\"] = 1] = \"FORWARD\";\n })(__DirectionValues || (__DirectionValues = {}));\n (function (Direction) {\n Direction.codec = () => {\n return enumeration(__DirectionValues);\n };\n })(Direction = PagingInfo.Direction || (PagingInfo.Direction = {}));\n let _codec;\n PagingInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.pageSize != null) {\n w.uint32(8);\n w.uint64(obj.pageSize);\n }\n if (obj.cursor != null) {\n w.uint32(18);\n Index.codec().encode(obj.cursor, w);\n }\n if (obj.direction != null) {\n w.uint32(24);\n PagingInfo.Direction.codec().encode(obj.direction, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.pageSize = reader.uint64();\n break;\n }\n case 2: {\n obj.cursor = Index.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.cursor\n });\n break;\n }\n case 3: {\n obj.direction = PagingInfo.Direction.codec().decode(reader);\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PagingInfo.encode = (obj) => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n PagingInfo.decode = (buf, opts) => {\n return decodeMessage(buf, PagingInfo.codec(), opts);\n };\n})(PagingInfo || (PagingInfo = {}));\nexport var ContentFilter;\n(function (ContentFilter) {\n let _codec;\n ContentFilter.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(10);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ContentFilter.encode = (obj) => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n ContentFilter.decode = (buf, opts) => {\n return decodeMessage(buf, ContentFilter.codec(), opts);\n };\n})(ContentFilter || (ContentFilter = {}));\nexport var HistoryQuery;\n(function (HistoryQuery) {\n let _codec;\n HistoryQuery.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.pubsubTopic != null) {\n w.uint32(18);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n w.uint32(26);\n ContentFilter.codec().encode(value, w);\n }\n }\n if (obj.pagingInfo != null) {\n w.uint32(34);\n PagingInfo.codec().encode(obj.pagingInfo, w);\n }\n if (obj.startTime != null) {\n w.uint32(40);\n w.sint64(obj.startTime);\n }\n if (obj.endTime != null) {\n w.uint32(48);\n w.sint64(obj.endTime);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentFilters: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 2: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 3: {\n if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {\n throw new CodeError('decode error - map field \"contentFilters\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.contentFilters.push(ContentFilter.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.contentFilters$\n }));\n break;\n }\n case 4: {\n obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.pagingInfo\n });\n break;\n }\n case 5: {\n obj.startTime = reader.sint64();\n break;\n }\n case 6: {\n obj.endTime = reader.sint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n HistoryQuery.encode = (obj) => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n HistoryQuery.decode = (buf, opts) => {\n return decodeMessage(buf, HistoryQuery.codec(), opts);\n };\n})(HistoryQuery || (HistoryQuery = {}));\nexport var HistoryResponse;\n(function (HistoryResponse) {\n let HistoryError;\n (function (HistoryError) {\n HistoryError[\"NONE\"] = \"NONE\";\n HistoryError[\"INVALID_CURSOR\"] = \"INVALID_CURSOR\";\n HistoryError[\"TOO_MANY_REQUESTS\"] = \"TOO_MANY_REQUESTS\";\n HistoryError[\"SERVICE_UNAVAILABLE\"] = \"SERVICE_UNAVAILABLE\";\n })(HistoryError = HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));\n let __HistoryErrorValues;\n (function (__HistoryErrorValues) {\n __HistoryErrorValues[__HistoryErrorValues[\"NONE\"] = 0] = \"NONE\";\n __HistoryErrorValues[__HistoryErrorValues[\"INVALID_CURSOR\"] = 1] = \"INVALID_CURSOR\";\n __HistoryErrorValues[__HistoryErrorValues[\"TOO_MANY_REQUESTS\"] = 429] = \"TOO_MANY_REQUESTS\";\n __HistoryErrorValues[__HistoryErrorValues[\"SERVICE_UNAVAILABLE\"] = 503] = \"SERVICE_UNAVAILABLE\";\n })(__HistoryErrorValues || (__HistoryErrorValues = {}));\n (function (HistoryError) {\n HistoryError.codec = () => {\n return enumeration(__HistoryErrorValues);\n };\n })(HistoryError = HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));\n let _codec;\n HistoryResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(18);\n WakuMessage.codec().encode(value, w);\n }\n }\n if (obj.pagingInfo != null) {\n w.uint32(26);\n PagingInfo.codec().encode(obj.pagingInfo, w);\n }\n if (obj.error != null && __HistoryErrorValues[obj.error] !== 0) {\n w.uint32(32);\n HistoryResponse.HistoryError.codec().encode(obj.error, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messages: [],\n error: HistoryError.NONE\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 2: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n case 3: {\n obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.pagingInfo\n });\n break;\n }\n case 4: {\n obj.error = HistoryResponse.HistoryError.codec().decode(reader);\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n HistoryResponse.encode = (obj) => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n HistoryResponse.decode = (buf, opts) => {\n return decodeMessage(buf, HistoryResponse.codec(), opts);\n };\n})(HistoryResponse || (HistoryResponse = {}));\nexport var HistoryRpc;\n(function (HistoryRpc) {\n let _codec;\n HistoryRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.query != null) {\n w.uint32(18);\n HistoryQuery.codec().encode(obj.query, w);\n }\n if (obj.response != null) {\n w.uint32(26);\n HistoryResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.query = HistoryQuery.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.query\n });\n break;\n }\n case 3: {\n obj.response = HistoryResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n HistoryRpc.encode = (obj) => {\n return encodeMessage(obj, HistoryRpc.codec());\n };\n HistoryRpc.decode = (buf, opts) => {\n return decodeMessage(buf, HistoryRpc.codec(), opts);\n };\n})(HistoryRpc || (HistoryRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=store.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var PeerInfo;\n(function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.enr != null) {\n w.uint32(10);\n w.bytes(obj.enr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.enr = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return encodeMessage(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return decodeMessage(buf, PeerInfo.codec(), opts);\n };\n})(PeerInfo || (PeerInfo = {}));\nexport var PeerExchangeQuery;\n(function (PeerExchangeQuery) {\n let _codec;\n PeerExchangeQuery.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.numPeers != null) {\n w.uint32(8);\n w.uint64(obj.numPeers);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.numPeers = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeQuery.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeQuery.codec());\n };\n PeerExchangeQuery.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeQuery.codec(), opts);\n };\n})(PeerExchangeQuery || (PeerExchangeQuery = {}));\nexport var PeerExchangeResponse;\n(function (PeerExchangeResponse) {\n let _codec;\n PeerExchangeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerInfos != null) {\n for (const value of obj.peerInfos) {\n w.uint32(10);\n PeerInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peerInfos: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.peerInfos != null && obj.peerInfos.length === opts.limits.peerInfos) {\n throw new CodeError('decode error - map field \"peerInfos\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.peerInfos.push(PeerInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.peerInfos$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeResponse.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeResponse.codec());\n };\n PeerExchangeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeResponse.codec(), opts);\n };\n})(PeerExchangeResponse || (PeerExchangeResponse = {}));\nexport var PeerExchangeRPC;\n(function (PeerExchangeRPC) {\n let _codec;\n PeerExchangeRPC.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.query != null) {\n w.uint32(10);\n PeerExchangeQuery.codec().encode(obj.query, w);\n }\n if (obj.response != null) {\n w.uint32(18);\n PeerExchangeResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.query = PeerExchangeQuery.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.query\n });\n break;\n }\n case 2: {\n obj.response = PeerExchangeResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeRPC.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeRPC.codec());\n };\n PeerExchangeRPC.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeRPC.codec(), opts);\n };\n})(PeerExchangeRPC || (PeerExchangeRPC = {}));\n//# sourceMappingURL=peer_exchange.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var WakuMetadataRequest;\n(function (WakuMetadataRequest) {\n let _codec;\n WakuMetadataRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new CodeError('decode error - map field \"shards\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataRequest.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataRequest.codec());\n };\n WakuMetadataRequest.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataRequest.codec(), opts);\n };\n})(WakuMetadataRequest || (WakuMetadataRequest = {}));\nexport var WakuMetadataResponse;\n(function (WakuMetadataResponse) {\n let _codec;\n WakuMetadataResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new CodeError('decode error - map field \"shards\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataResponse.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataResponse.codec());\n };\n WakuMetadataResponse.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataResponse.codec(), opts);\n };\n})(WakuMetadataResponse || (WakuMetadataResponse = {}));\n//# sourceMappingURL=metadata.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function enumeration(v) {\n function findValue(val) {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value');\n }\n return v[val];\n }\n const encode = function enumEncode(val, writer) {\n const enumValue = findValue(val);\n writer.int32(enumValue);\n };\n const decode = function enumDecode(reader) {\n const val = reader.int32();\n return findValue(val);\n };\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode);\n}\n//# sourceMappingURL=enum.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function message(encode, decode) {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode);\n}\n//# sourceMappingURL=message.js.map","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\nexport { decodeMessage } from './decode.js';\nexport { encodeMessage } from './encode.js';\nexport { enumeration } from './codecs/enum.js';\nexport { message } from './codecs/message.js';\nexport { createReader as reader } from './utils/reader.js';\nexport { createWriter as writer } from './utils/writer.js';\nexport class CodeError extends Error {\n code;\n constructor(message, code, options) {\n super(message, options);\n this.code = code;\n }\n}\n//# sourceMappingURL=index.js.map","export function isDefined(value) {\n return Boolean(value);\n}\n//# sourceMappingURL=is_defined.js.map","export function groupByContentTopic(values) {\n const groupedDecoders = new Map();\n values.forEach((value) => {\n let decs = groupedDecoders.get(value.contentTopic);\n if (!decs) {\n groupedDecoders.set(value.contentTopic, []);\n decs = groupedDecoders.get(value.contentTopic);\n }\n decs.push(value);\n });\n return groupedDecoders;\n}\n//# sourceMappingURL=group_by.js.map","const FRAME_RATE = 60;\n/**\n * Function that transforms IReceiver subscription to iterable stream of data.\n * @param receiver - object that allows to be subscribed to;\n * @param decoder - parameter to be passed to receiver for subscription;\n * @param options - options for receiver for subscription;\n * @param iteratorOptions - optional configuration for iterator;\n * @returns iterator and stop function to terminate it.\n */\nexport async function toAsyncIterator(receiver, decoder, iteratorOptions) {\n const iteratorDelay = iteratorOptions?.iteratorDelay ?? FRAME_RATE;\n const messages = [];\n let unsubscribe;\n unsubscribe = await receiver.subscribe(decoder, (message) => {\n messages.push(message);\n });\n const isWithTimeout = Number.isInteger(iteratorOptions?.timeoutMs);\n const timeoutMs = iteratorOptions?.timeoutMs ?? 0;\n const startTime = Date.now();\n async function* iterator() {\n while (true) {\n if (isWithTimeout && Date.now() - startTime >= timeoutMs) {\n return;\n }\n await wait(iteratorDelay);\n const message = messages.shift();\n if (!unsubscribe && messages.length === 0) {\n return message;\n }\n if (!message && unsubscribe) {\n continue;\n }\n yield message;\n }\n }\n return {\n iterator: iterator(),\n async stop() {\n if (unsubscribe) {\n await unsubscribe();\n unsubscribe = undefined;\n }\n }\n };\n}\nfunction wait(ms) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n//# sourceMappingURL=to_async_iterator.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Choice: a ? b : c\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","export var Protocols;\n(function (Protocols) {\n Protocols[\"Relay\"] = \"relay\";\n Protocols[\"Store\"] = \"store\";\n Protocols[\"LightPush\"] = \"lightpush\";\n Protocols[\"Filter\"] = \"filter\";\n})(Protocols || (Protocols = {}));\nexport var ProtocolError;\n(function (ProtocolError) {\n /** Could not determine the origin of the fault. Best to check connectivity and try again */\n ProtocolError[\"GENERIC_FAIL\"] = \"Generic error\";\n /**\n * Failure to protobuf encode the message. This is not recoverable and needs\n * further investigation.\n */\n ProtocolError[\"ENCODE_FAILED\"] = \"Failed to encode\";\n /**\n * Failure to protobuf decode the message. May be due to a remote peer issue,\n * ensuring that messages are sent via several peer enable mitigation of this error.\n */\n ProtocolError[\"DECODE_FAILED\"] = \"Failed to decode\";\n /**\n * The message payload is empty, making the message invalid. Ensure that a non-empty\n * payload is set on the outgoing message.\n */\n ProtocolError[\"EMPTY_PAYLOAD\"] = \"Payload is empty\";\n /**\n * The message size is above the maximum message size allowed on the Waku Network.\n * Compressing the message or using an alternative strategy for large messages is recommended.\n */\n ProtocolError[\"SIZE_TOO_BIG\"] = \"Size is too big\";\n /**\n * The PubsubTopic passed to the send function is not configured on the Waku node.\n * Please ensure that the PubsubTopic is used when initializing the Waku node.\n */\n ProtocolError[\"TOPIC_NOT_CONFIGURED\"] = \"Topic not configured\";\n /**\n * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.\n * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.\n */\n ProtocolError[\"TOPIC_DECODER_MISMATCH\"] = \"Topic decoder mismatch\";\n /**\n * Failure to find a peer with suitable protocols. This may due to a connection issue.\n * Mitigation can be: retrying after a given time period, display connectivity issue\n * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`\n * on the connection manager before retrying.\n */\n ProtocolError[\"NO_PEER_AVAILABLE\"] = \"No peer available\";\n /**\n * Failure to find a stream to the peer. This may be because the connection with the peer is not still alive.\n * Mitigation can be: retrying after a given time period, or mitigation for `NO_PEER_AVAILABLE` can be used.\n */\n ProtocolError[\"NO_STREAM_AVAILABLE\"] = \"No stream available\";\n /**\n * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"REMOTE_PEER_FAULT\"] = \"Remote peer fault\";\n /**\n * The remote peer rejected the message. Information provided by the remote peer\n * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"REMOTE_PEER_REJECTED\"] = \"Remote peer rejected\";\n /**\n * The protocol request timed out without a response. This may be due to a connection issue.\n * Mitigation can be: retrying after a given time period\n */\n ProtocolError[\"REQUEST_TIMEOUT\"] = \"Request timeout\";\n})(ProtocolError || (ProtocolError = {}));\n//# sourceMappingURL=protocols.js.map","export var PageDirection;\n(function (PageDirection) {\n PageDirection[\"BACKWARD\"] = \"backward\";\n PageDirection[\"FORWARD\"] = \"forward\";\n})(PageDirection || (PageDirection = {}));\n//# sourceMappingURL=store.js.map","export var Tags;\n(function (Tags) {\n Tags[\"BOOTSTRAP\"] = \"bootstrap\";\n Tags[\"PEER_EXCHANGE\"] = \"peer-exchange\";\n Tags[\"LOCAL\"] = \"local-peer-cache\";\n})(Tags || (Tags = {}));\nexport var EPeersByDiscoveryEvents;\n(function (EPeersByDiscoveryEvents) {\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_BOOTSTRAP\"] = \"peer:discovery:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_PEER_EXCHANGE\"] = \"peer:discovery:peer-exchange\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_BOOTSTRAP\"] = \"peer:connected:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_PEER_EXCHANGE\"] = \"peer:connected:peer-exchange\";\n})(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));\nexport var EConnectionStateEvents;\n(function (EConnectionStateEvents) {\n EConnectionStateEvents[\"CONNECTION_STATUS\"] = \"waku:connection\";\n})(EConnectionStateEvents || (EConnectionStateEvents = {}));\n//# sourceMappingURL=connection_manager.js.map","/**\n * DefaultPubsubTopic is the default gossipsub topic to use for Waku.\n */\nexport const DefaultPubsubTopic = \"/waku/2/default-waku/proto\";\n/**\n * The default cluster ID for The Waku Network\n */\nexport const DEFAULT_CLUSTER_ID = 1;\n//# sourceMappingURL=constants.js.map","import bases, {} from './util/bases.js';\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map","import { fromString } from \"uint8arrays/from-string\";\nimport { toString } from \"uint8arrays/to-string\";\n/**\n * Convert input to a byte array.\n *\n * Handles both `0x` prefixed and non-prefixed strings.\n */\nexport function hexToBytes(hex) {\n if (typeof hex === \"string\") {\n const _hex = hex.replace(/^0x/i, \"\");\n return fromString(_hex.toLowerCase(), \"base16\");\n }\n return hex;\n}\nexport function numberToBytes(value) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof value === \"number\") {\n view.setFloat64(0, value, false);\n }\n else {\n view.setBigInt64(0, value, false);\n }\n return new Uint8Array(buffer);\n}\n/**\n * Convert byte array to hex string (no `0x` prefix).\n */\nexport const bytesToHex = (bytes) => toString(bytes, \"base16\");\n/**\n * Decode byte array to utf-8 string.\n */\nexport const bytesToUtf8 = (b) => toString(b, \"utf8\");\n/**\n * Encode utf-8 string to byte array.\n */\nexport const utf8ToBytes = (s) => fromString(s, \"utf8\");\n/**\n * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`\n */\nexport function concat(byteArrays, totalLength) {\n const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);\n const res = new Uint8Array(len);\n let offset = 0;\n for (const bytes of byteArrays) {\n res.set(bytes, offset);\n offset += bytes.length;\n }\n return res;\n}\n//# sourceMappingURL=index.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { DEFAULT_CLUSTER_ID } from \"@waku/interfaces\";\nimport { concat, utf8ToBytes } from \"../bytes/index.js\";\nexport const singleShardInfoToPubsubTopic = (shardInfo) => {\n if (shardInfo.shard === undefined)\n throw new Error(\"Invalid shard\");\n return `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${shardInfo.shard}`;\n};\nexport const singleShardInfosToShardInfo = (singleShardInfos) => {\n if (singleShardInfos.length === 0)\n throw new Error(\"Invalid shard\");\n const clusterIds = singleShardInfos.map((shardInfo) => shardInfo.clusterId);\n if (new Set(clusterIds).size !== 1) {\n throw new Error(\"Passed shard infos have different clusterIds\");\n }\n const shards = singleShardInfos\n .map((shardInfo) => shardInfo.shard)\n .filter((shard) => shard !== undefined);\n return {\n clusterId: singleShardInfos[0].clusterId,\n shards\n };\n};\nexport const shardInfoToPubsubTopics = (shardInfo) => {\n if (\"contentTopics\" in shardInfo && shardInfo.contentTopics) {\n // Autosharding: explicitly defined content topics\n return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));\n }\n else if (\"shards\" in shardInfo) {\n // Static sharding\n if (shardInfo.shards === undefined)\n throw new Error(\"Invalid shard\");\n return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${index}`)));\n }\n else if (\"application\" in shardInfo && \"version\" in shardInfo) {\n // Autosharding: single shard from application and version\n return [\n contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`, shardInfo.clusterId)\n ];\n }\n else {\n throw new Error(\"Missing required configuration in shard parameters\");\n }\n};\nexport const pubsubTopicToSingleShardInfo = (pubsubTopics) => {\n const parts = pubsubTopics.split(\"/\");\n if (parts.length != 6 ||\n parts[1] !== \"waku\" ||\n parts[2] !== \"2\" ||\n parts[3] !== \"rs\")\n throw new Error(\"Invalid pubsub topic\");\n const clusterId = parseInt(parts[4]);\n const shard = parseInt(parts[5]);\n if (isNaN(clusterId) || isNaN(shard))\n throw new Error(\"Invalid clusterId or shard\");\n return {\n clusterId,\n shard\n };\n};\n//TODO: move part of BaseProtocol instead of utils\n// return `ProtocolError.TOPIC_NOT_CONFIGURED` instead of throwing\nexport function ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {\n if (!configuredTopics.includes(pubsubTopic)) {\n throw new Error(`Pubsub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);\n }\n}\n/**\n * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/\n * @param contentTopic String to validate\n * @returns Object with each content topic field as an attribute\n */\nexport function ensureValidContentTopic(contentTopic) {\n const parts = contentTopic.split(\"/\");\n if (parts.length < 5 || parts.length > 6) {\n throw Error(\"Content topic format is invalid\");\n }\n // Validate generation field if present\n let generation = 0;\n if (parts.length == 6) {\n generation = parseInt(parts[1]);\n if (isNaN(generation)) {\n throw new Error(\"Invalid generation field in content topic\");\n }\n if (generation > 0) {\n throw new Error(\"Generation greater than 0 is not supported\");\n }\n }\n // Validate remaining fields\n const fields = parts.splice(-4);\n // Validate application field\n if (fields[0].length == 0) {\n throw new Error(\"Application field cannot be empty\");\n }\n // Validate version field\n if (fields[1].length == 0) {\n throw new Error(\"Version field cannot be empty\");\n }\n // Validate topic name field\n if (fields[2].length == 0) {\n throw new Error(\"Topic name field cannot be empty\");\n }\n // Validate encoding field\n if (fields[3].length == 0) {\n throw new Error(\"Encoding field cannot be empty\");\n }\n return {\n generation,\n application: fields[0],\n version: fields[1],\n topicName: fields[2],\n encoding: fields[3]\n };\n}\n/**\n * Given a string, determines which autoshard index to use for its pubsub topic.\n * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm\n */\nexport function contentTopicToShardIndex(contentTopic, networkShards = 8) {\n const { application, version } = ensureValidContentTopic(contentTopic);\n const digest = sha256(concat([utf8ToBytes(application), utf8ToBytes(version)]));\n const dataview = new DataView(digest.buffer.slice(-8));\n return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));\n}\nexport function contentTopicToPubsubTopic(contentTopic, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n if (!contentTopic) {\n throw Error(\"Content topic must be specified\");\n }\n const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);\n return `/waku/2/rs/${clusterId}/${shardIndex}`;\n}\n/**\n * Given an array of content topics, groups them together by their Pubsub topic as derived using the algorithm for autosharding.\n * If any of the content topics are not properly formatted, the function will throw an error.\n */\nexport function contentTopicsByPubsubTopic(contentTopics, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n const groupedContentTopics = new Map();\n for (const contentTopic of contentTopics) {\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic, clusterId, networkShards);\n let topics = groupedContentTopics.get(pubsubTopic);\n if (!topics) {\n groupedContentTopics.set(pubsubTopic, []);\n topics = groupedContentTopics.get(pubsubTopic);\n }\n topics.push(contentTopic);\n }\n return groupedContentTopics;\n}\n/**\n * Used when creating encoders/decoders to determine which pubsub topic to use\n */\nexport function determinePubsubTopic(contentTopic, pubsubTopicShardInfo) {\n if (typeof pubsubTopicShardInfo == \"string\") {\n return pubsubTopicShardInfo;\n }\n return pubsubTopicShardInfo?.shard !== undefined\n ? singleShardInfoToPubsubTopic(pubsubTopicShardInfo)\n : contentTopicToPubsubTopic(contentTopic, pubsubTopicShardInfo?.clusterId ?? DEFAULT_CLUSTER_ID);\n}\n/**\n * Validates sharding configuration and sets defaults where possible.\n * @returns Validated sharding parameters, with any missing values set to defaults\n */\nexport const ensureShardingConfigured = (shardInfo) => {\n const clusterId = shardInfo.clusterId ?? DEFAULT_CLUSTER_ID;\n const shards = \"shards\" in shardInfo ? shardInfo.shards : [];\n const contentTopics = \"contentTopics\" in shardInfo ? shardInfo.contentTopics : [];\n const [application, version] = \"application\" in shardInfo && \"version\" in shardInfo\n ? [shardInfo.application, shardInfo.version]\n : [undefined, undefined];\n const isShardsConfigured = shards && shards.length > 0;\n const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;\n const isApplicationVersionConfigured = application && version;\n if (isShardsConfigured) {\n return {\n shardingParams: { clusterId, shards },\n shardInfo: { clusterId, shards },\n pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })\n };\n }\n if (isContentTopicsConfigured) {\n const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));\n const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));\n return {\n shardingParams: { clusterId, contentTopics },\n shardInfo: { clusterId, shards },\n pubsubTopics\n };\n }\n if (isApplicationVersionConfigured) {\n const pubsubTopic = contentTopicToPubsubTopic(`/${application}/${version}/default/default`, clusterId);\n return {\n shardingParams: { clusterId, application, version },\n shardInfo: {\n clusterId,\n shards: [pubsubTopicToSingleShardInfo(pubsubTopic).shard]\n },\n pubsubTopics: [pubsubTopic]\n };\n }\n throw new Error(\"Missing minimum required configuration options for static sharding or autosharding.\");\n};\n//# sourceMappingURL=sharding.js.map","export const decodeRelayShard = (bytes) => {\n // explicitly converting to Uint8Array to avoid Buffer\n // https://github.com/libp2p/js-libp2p/issues/2146\n bytes = new Uint8Array(bytes);\n if (bytes.length < 3)\n throw new Error(\"Insufficient data\");\n const view = new DataView(bytes.buffer);\n const clusterId = view.getUint16(0);\n const shards = [];\n if (bytes.length === 130) {\n // rsv format (Bit Vector)\n for (let i = 0; i < 1024; i++) {\n const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (i % 8);\n if (view.getUint8(byteIndex) & (1 << bitIndex)) {\n shards.push(i);\n }\n }\n }\n else {\n // rs format (Index List)\n const numIndices = view.getUint8(2);\n for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {\n if (offset + 1 >= bytes.length)\n throw new Error(\"Unexpected end of data\");\n shards.push(view.getUint16(offset));\n }\n }\n return { clusterId, shards };\n};\nexport const encodeRelayShard = (shardInfo) => {\n const { clusterId, shards } = shardInfo;\n const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;\n const buffer = new ArrayBuffer(totalLength);\n const view = new DataView(buffer);\n view.setUint16(0, clusterId);\n if (shards.length >= 64) {\n // rsv format (Bit Vector)\n for (const index of shards) {\n const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (index % 8);\n view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));\n }\n }\n else {\n // rs format (Index List)\n view.setUint8(2, shards.length);\n for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {\n view.setUint16(offset, shards[i]);\n }\n }\n return new Uint8Array(buffer);\n};\n//# sourceMappingURL=relay_shard_codec.js.map","import debug from \"debug\";\nconst APP_NAME = \"waku\";\nexport class Logger {\n _info;\n _warn;\n _error;\n static createDebugNamespace(level, prefix) {\n return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;\n }\n constructor(prefix) {\n this._info = debug(Logger.createDebugNamespace(\"info\", prefix));\n this._warn = debug(Logger.createDebugNamespace(\"warn\", prefix));\n this._error = debug(Logger.createDebugNamespace(\"error\", prefix));\n }\n get info() {\n return this._info;\n }\n get warn() {\n return this._warn;\n }\n get error() {\n return this._error;\n }\n log(level, ...args) {\n const logger = this[level];\n logger(...args);\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_message as proto } from \"@waku/proto\";\nimport { determinePubsubTopic, Logger } from \"@waku/utils\";\nconst log = new Logger(\"message:version-0\");\nconst OneMillion = BigInt(1_000_000);\nexport const Version = 0;\nexport { proto };\nexport class DecodedMessage {\n pubsubTopic;\n proto;\n constructor(pubsubTopic, proto) {\n this.pubsubTopic = pubsubTopic;\n this.proto = proto;\n }\n get ephemeral() {\n return Boolean(this.proto.ephemeral);\n }\n get payload() {\n return this.proto.payload;\n }\n get contentTopic() {\n return this.proto.contentTopic;\n }\n get _rawTimestamp() {\n return this.proto.timestamp;\n }\n get timestamp() {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n return;\n }\n catch (e) {\n return;\n }\n }\n get meta() {\n return this.proto.meta;\n }\n get version() {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n return this.proto.version ?? 0;\n }\n get rateLimitProof() {\n return this.proto.rateLimitProof;\n }\n}\nexport class Encoder {\n contentTopic;\n ephemeral;\n pubsubTopic;\n metaSetter;\n constructor(contentTopic, ephemeral = false, pubsubTopic, metaSetter) {\n this.contentTopic = contentTopic;\n this.ephemeral = ephemeral;\n this.pubsubTopic = pubsubTopic;\n this.metaSetter = metaSetter;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n async toWire(message) {\n return proto.WakuMessage.encode(await this.toProtoObj(message));\n }\n async toProtoObj(message) {\n const timestamp = message.timestamp ?? new Date();\n const protoMessage = {\n payload: message.payload,\n version: Version,\n contentTopic: this.contentTopic,\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n meta: undefined,\n rateLimitProof: message.rateLimitProof,\n ephemeral: this.ephemeral\n };\n if (this.metaSetter) {\n const meta = this.metaSetter(protoMessage);\n return { ...protoMessage, meta };\n }\n return protoMessage;\n }\n}\n/**\n * Creates an encoder that encode messages without Waku level encryption or signature.\n *\n * An encoder is used to encode messages in the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format to be sent over the Waku network. The resulting encoder can then be\n * pass to { @link @waku/interfaces!ISender.send } to automatically encode outgoing\n * messages.\n */\nexport function createEncoder({ pubsubTopic, pubsubTopicShardInfo, contentTopic, ephemeral, metaSetter }) {\n return new Encoder(contentTopic, ephemeral, determinePubsubTopic(contentTopic, pubsubTopic ?? pubsubTopicShardInfo), metaSetter);\n}\nexport class Decoder {\n pubsubTopic;\n contentTopic;\n constructor(pubsubTopic, contentTopic) {\n this.pubsubTopic = pubsubTopic;\n this.contentTopic = contentTopic;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n fromWireToProtoObj(bytes) {\n const protoMessage = proto.WakuMessage.decode(bytes);\n return Promise.resolve({\n payload: protoMessage.payload,\n contentTopic: protoMessage.contentTopic,\n version: protoMessage.version ?? undefined,\n timestamp: protoMessage.timestamp ?? undefined,\n meta: protoMessage.meta ?? undefined,\n rateLimitProof: protoMessage.rateLimitProof ?? undefined,\n ephemeral: protoMessage.ephemeral ?? false\n });\n }\n async fromProtoObj(pubsubTopic, proto) {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n if (proto.version ?? 0 !== Version) {\n log.error(\"Failed to decode due to incorrect version, expected:\", Version, \", actual:\", proto.version);\n return Promise.resolve(undefined);\n }\n return new DecodedMessage(pubsubTopic, proto);\n }\n}\n/**\n * Creates a decoder that decode messages without Waku level encryption.\n *\n * A decoder is used to decode messages from the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format when received from the Waku network. The resulting decoder can then be\n * pass to { @link @waku/interfaces!IReceiver.subscribe } to automatically decode incoming\n * messages.\n *\n * @param contentTopic The resulting decoder will only decode messages with this content topic.\n */\nexport function createDecoder(contentTopic, pubsubTopicShardInfo) {\n return new Decoder(determinePubsubTopic(contentTopic, pubsubTopicShardInfo), contentTopic);\n}\n//# sourceMappingURL=version_0.js.map","/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction all(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = [];\n for await (const entry of source) {\n arr.push(entry);\n }\n return arr;\n })();\n }\n const arr = [];\n for (const entry of source) {\n arr.push(entry);\n }\n return arr;\n}\nexport default all;\n//# sourceMappingURL=index.js.map","import { allocUnsafe } from '#alloc';\nimport { asUint8Array } from '#util/as-uint8array';\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}\n//# sourceMappingURL=concat.js.map","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map","/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc';\nimport { concat } from 'uint8arrays/concat';\nimport { equals } from 'uint8arrays/equals';\nconst symbol = Symbol.for('@achingbrain/uint8arraylist');\nfunction findBufAndOffset(bufs, index) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds');\n }\n let offset = 0;\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength;\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n };\n }\n offset = bufEnd;\n }\n throw new RangeError('index is out of bounds');\n}\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList(value) {\n return Boolean(value?.[symbol]);\n}\nexport class Uint8ArrayList {\n bufs;\n length;\n [symbol] = true;\n constructor(...data) {\n this.bufs = [];\n this.length = 0;\n if (data.length > 0) {\n this.appendAll(data);\n }\n }\n *[Symbol.iterator]() {\n yield* this.bufs;\n }\n get byteLength() {\n return this.length;\n }\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append(...bufs) {\n this.appendAll(bufs);\n }\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll(bufs) {\n let length = 0;\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.push(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.push(...buf.bufs);\n }\n else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend(...bufs) {\n this.prependAll(bufs);\n }\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll(bufs) {\n let length = 0;\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.unshift(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.unshift(...buf.bufs);\n }\n else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Read the value at `index`\n */\n get(index) {\n const res = findBufAndOffset(this.bufs, index);\n return res.buf[res.index];\n }\n /**\n * Set the value at `index` to `value`\n */\n set(index, value) {\n const res = findBufAndOffset(this.bufs, index);\n res.buf[res.index] = value;\n }\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i]);\n }\n }\n else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i));\n }\n }\n else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n /**\n * Remove bytes from the front of the pool\n */\n consume(bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes);\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return;\n }\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = [];\n this.length = 0;\n return;\n }\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength;\n this.length -= this.bufs[0].byteLength;\n this.bufs.shift();\n }\n else {\n this.bufs[0] = this.bufs[0].subarray(bytes);\n this.length -= bytes;\n break;\n }\n }\n }\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n return concat(bufs, length);\n }\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n if (bufs.length === 1) {\n return bufs[0];\n }\n return concat(bufs, length);\n }\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n const list = new Uint8ArrayList();\n list.length = length;\n // don't loop, just set the bufs\n list.bufs = [...bufs];\n return list;\n }\n _subList(beginInclusive, endExclusive) {\n beginInclusive = beginInclusive ?? 0;\n endExclusive = endExclusive ?? this.length;\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive;\n }\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive;\n }\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds');\n }\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 };\n }\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length };\n }\n const bufs = [];\n let offset = 0;\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i];\n const bufStart = offset;\n const bufEnd = bufStart + buf.byteLength;\n // for next loop\n offset = bufEnd;\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue;\n }\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n const start = beginInclusive - bufStart;\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));\n break;\n }\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf);\n continue;\n }\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart));\n continue;\n }\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart));\n break;\n }\n // slice started before this buffer and ends after it\n bufs.push(buf);\n }\n return { bufs, length: endExclusive - beginInclusive };\n }\n indexOf(search, offset = 0) {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array');\n }\n const needle = search instanceof Uint8Array ? search : search.subarray();\n offset = Number(offset ?? 0);\n if (isNaN(offset)) {\n offset = 0;\n }\n if (offset < 0) {\n offset = this.length + offset;\n }\n if (offset < 0) {\n offset = 0;\n }\n if (search.length === 0) {\n return offset > this.length ? this.length : offset;\n }\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M = needle.byteLength;\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long');\n }\n // radix\n const radix = 256;\n const rightmostPositions = new Int32Array(radix);\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1;\n }\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j;\n }\n // Return offset of first match, -1 if no match\n const right = rightmostPositions;\n const lastIndex = this.byteLength - needle.byteLength;\n const lastPatIndex = needle.byteLength - 1;\n let skip;\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0;\n for (let j = lastPatIndex; j >= 0; j--) {\n const char = this.get(i + j);\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char]);\n break;\n }\n }\n if (skip === 0) {\n return i;\n }\n }\n return -1;\n }\n getInt8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt8(0);\n }\n setInt8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt8(0, value);\n this.write(buf, byteOffset);\n }\n getInt16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt16(0, littleEndian);\n }\n setInt16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getInt32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt32(0, littleEndian);\n }\n setInt32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigInt64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigInt64(0, littleEndian);\n }\n setBigInt64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigInt64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint8(0);\n }\n setUint8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint8(0, value);\n this.write(buf, byteOffset);\n }\n getUint16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint16(0, littleEndian);\n }\n setUint16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint32(0, littleEndian);\n }\n setUint32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigUint64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigUint64(0, littleEndian);\n }\n setBigUint64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigUint64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat32(0, littleEndian);\n }\n setFloat32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat64(0, littleEndian);\n }\n setFloat64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (!(other instanceof Uint8ArrayList)) {\n return false;\n }\n if (other.bufs.length !== this.bufs.length) {\n return false;\n }\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false;\n }\n }\n return true;\n }\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays(bufs, length) {\n const list = new Uint8ArrayList();\n list.bufs = bufs;\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);\n }\n list.length = length;\n return list;\n }\n}\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n//# sourceMappingURL=index.js.map","export function isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\n//# sourceMappingURL=utils.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { isAsyncIterable } from './utils.js';\nconst defaultEncoder = (length) => {\n const lengthLength = varint.encodingLength(length);\n const lengthBuf = allocUnsafe(lengthLength);\n varint.encode(length, lengthBuf);\n defaultEncoder.bytes = lengthLength;\n return lengthBuf;\n};\ndefaultEncoder.bytes = 0;\nexport function encode(source, options) {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n function* maybeYield(chunk) {\n // length + data\n const length = encodeLength(chunk.byteLength);\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length;\n }\n else {\n yield* length;\n }\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk;\n }\n else {\n yield* chunk;\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n }\n return (function* () {\n for (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n}\nencode.single = (chunk, options) => {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n return new Uint8ArrayList(encodeLength(chunk.byteLength), chunk);\n};\n//# sourceMappingURL=encode.js.map","/* eslint max-depth: [\"error\", 6] */\nimport errCode from 'err-code';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { isAsyncIterable } from './utils.js';\n// Maximum length of the length section of the message\nexport const MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nexport const MAX_DATA_LENGTH = 1024 * 1024 * 4;\nvar ReadMode;\n(function (ReadMode) {\n ReadMode[ReadMode[\"LENGTH\"] = 0] = \"LENGTH\";\n ReadMode[ReadMode[\"DATA\"] = 1] = \"DATA\";\n})(ReadMode || (ReadMode = {}));\nconst defaultDecoder = (buf) => {\n const length = varint.decode(buf);\n defaultDecoder.bytes = varint.encodingLength(length);\n return length;\n};\ndefaultDecoder.bytes = 0;\nexport function decode(source, options) {\n const buffer = new Uint8ArrayList();\n let mode = ReadMode.LENGTH;\n let dataLength = -1;\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;\n function* maybeYield() {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer);\n if (dataLength < 0) {\n throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH');\n }\n if (dataLength > maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG');\n }\n const dataLengthLength = lengthDecoder.bytes;\n buffer.consume(dataLengthLength);\n if (options?.onLength != null) {\n options.onLength(dataLength);\n }\n mode = ReadMode.DATA;\n }\n catch (err) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG');\n }\n break;\n }\n throw err;\n }\n }\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break;\n }\n const data = buffer.sublist(0, dataLength);\n buffer.consume(dataLength);\n if (options?.onData != null) {\n options.onData(data);\n }\n yield data;\n mode = ReadMode.LENGTH;\n }\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');\n }\n })();\n }\n return (function* () {\n for (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');\n }\n })();\n}\ndecode.fromReader = (reader, options) => {\n let byteLength = 1; // Read single byte chunks until the length is known\n const varByteSource = (async function* () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength);\n if (done === true) {\n return;\n }\n if (value != null) {\n yield value;\n }\n }\n catch (err) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null };\n }\n throw err;\n }\n finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1;\n }\n }\n }());\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l) => { byteLength = l; };\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n });\n};\n//# sourceMappingURL=decode.js.map","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","// ported from https://www.npmjs.com/package/fast-fifo\nclass FixedFIFO {\n buffer;\n mask;\n top;\n btm;\n next;\n constructor(hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two');\n }\n this.buffer = new Array(hwm);\n this.mask = hwm - 1;\n this.top = 0;\n this.btm = 0;\n this.next = null;\n }\n push(data) {\n if (this.buffer[this.top] !== undefined) {\n return false;\n }\n this.buffer[this.top] = data;\n this.top = (this.top + 1) & this.mask;\n return true;\n }\n shift() {\n const last = this.buffer[this.btm];\n if (last === undefined) {\n return undefined;\n }\n this.buffer[this.btm] = undefined;\n this.btm = (this.btm + 1) & this.mask;\n return last;\n }\n isEmpty() {\n return this.buffer[this.btm] === undefined;\n }\n}\nexport class FIFO {\n size;\n hwm;\n head;\n tail;\n constructor(options = {}) {\n this.hwm = options.splitLimit ?? 16;\n this.head = new FixedFIFO(this.hwm);\n this.tail = this.head;\n this.size = 0;\n }\n calculateSize(obj) {\n if (obj?.byteLength != null) {\n return obj.byteLength;\n }\n return 1;\n }\n push(val) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value);\n }\n if (!this.head.push(val)) {\n const prev = this.head;\n this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);\n this.head.push(val);\n }\n }\n shift() {\n let val = this.tail.shift();\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next;\n this.tail.next = null;\n this.tail = next;\n val = this.tail.shift();\n }\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value);\n }\n return val;\n }\n isEmpty() {\n return this.head.isEmpty();\n }\n}\n//# sourceMappingURL=fifo.js.map","/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\nimport deferred from 'p-defer';\nimport { FIFO } from './fifo.js';\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.code = code ?? 'ABORT_ERR';\n }\n}\nexport function pushable(options = {}) {\n const getNext = (buffer) => {\n const next = buffer.shift();\n if (next == null) {\n return { done: true };\n }\n if (next.error != null) {\n throw next.error;\n }\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n };\n };\n return _pushable(getNext, options);\n}\nexport function pushableV(options = {}) {\n const getNext = (buffer) => {\n let next;\n const values = [];\n while (!buffer.isEmpty()) {\n next = buffer.shift();\n if (next == null) {\n break;\n }\n if (next.error != null) {\n throw next.error;\n }\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value);\n }\n }\n if (next == null) {\n return { done: true };\n }\n return {\n done: next.done === true,\n value: values\n };\n };\n return _pushable(getNext, options);\n}\nfunction _pushable(getNext, options) {\n options = options ?? {};\n let onEnd = options.onEnd;\n let buffer = new FIFO();\n let pushable;\n let onNext;\n let ended;\n let drain = deferred();\n const waitNext = async () => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer);\n }\n if (ended) {\n return { done: true };\n }\n return await new Promise((resolve, reject) => {\n onNext = (next) => {\n onNext = null;\n buffer.push(next);\n try {\n resolve(getNext(buffer));\n }\n catch (err) {\n reject(err);\n }\n return pushable;\n };\n });\n }\n finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve();\n drain = deferred();\n });\n }\n }\n };\n const bufferNext = (next) => {\n if (onNext != null) {\n return onNext(next);\n }\n buffer.push(next);\n return pushable;\n };\n const bufferError = (err) => {\n buffer = new FIFO();\n if (onNext != null) {\n return onNext({ error: err });\n }\n buffer.push({ error: err });\n return pushable;\n };\n const push = (value) => {\n if (ended) {\n return pushable;\n }\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value');\n }\n return bufferNext({ done: false, value });\n };\n const end = (err) => {\n if (ended)\n return pushable;\n ended = true;\n return (err != null) ? bufferError(err) : bufferNext({ done: true });\n };\n const _return = () => {\n buffer = new FIFO();\n end();\n return { done: true };\n };\n const _throw = (err) => {\n end(err);\n return { done: true };\n };\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength() {\n return buffer.size;\n },\n onEmpty: async (options) => {\n const signal = options?.signal;\n signal?.throwIfAborted();\n if (buffer.isEmpty()) {\n return;\n }\n let cancel;\n let listener;\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError());\n };\n signal.addEventListener('abort', listener);\n });\n }\n try {\n await Promise.race([\n drain.promise,\n cancel\n ]);\n }\n finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener);\n }\n }\n }\n };\n if (onEnd == null) {\n return pushable;\n }\n const _pushable = pushable;\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next() {\n return _pushable.next();\n },\n throw(err) {\n _pushable.throw(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return { done: true };\n },\n return() {\n _pushable.return();\n if (onEnd != null) {\n onEnd();\n onEnd = undefined;\n }\n return { done: true };\n },\n push,\n end(err) {\n _pushable.end(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return pushable;\n },\n get readableLength() {\n return _pushable.readableLength;\n },\n onEmpty: (opts) => {\n return _pushable.onEmpty(opts);\n }\n };\n return pushable;\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\nimport { pushable } from 'it-pushable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction merge(...sources) {\n const syncSources = [];\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source);\n }\n }\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return (function* () {\n for (const source of syncSources) {\n yield* source;\n }\n })();\n }\n return (async function* () {\n const output = pushable({\n objectMode: true\n });\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(sources.map(async (source) => {\n for await (const item of source) {\n output.push(item);\n }\n }));\n output.end();\n }\n catch (err) {\n output.end(err);\n }\n });\n yield* output;\n })();\n}\nexport default merge;\n//# sourceMappingURL=index.js.map","import { pushable } from 'it-pushable';\nimport merge from 'it-merge';\nexport function pipe(first, ...rest) {\n if (first == null) {\n throw new Error('Empty pipeline');\n }\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first;\n first = () => duplex.source;\n // Iterable at start: wrap in function\n }\n else if (isIterable(first) || isAsyncIterable(first)) {\n const source = first;\n first = () => source;\n }\n const fns = [first, ...rest];\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink;\n }\n }\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i]);\n }\n }\n }\n return rawPipe(...fns);\n}\nexport const rawPipe = (...fns) => {\n let res;\n while (fns.length > 0) {\n res = fns.shift()(res);\n }\n return res;\n};\nconst isAsyncIterable = (obj) => {\n return obj?.[Symbol.asyncIterator] != null;\n};\nconst isIterable = (obj) => {\n return obj?.[Symbol.iterator] != null;\n};\nconst isDuplex = (obj) => {\n if (obj == null) {\n return false;\n }\n return obj.sink != null && obj.source != null;\n};\nconst duplexPipelineFn = (duplex) => {\n return (source) => {\n const p = duplex.sink(source);\n if (p?.then != null) {\n const stream = pushable({\n objectMode: true\n });\n p.then(() => {\n stream.end();\n }, (err) => {\n stream.end(err);\n });\n let sourceWrap;\n const source = duplex.source;\n if (isAsyncIterable(source)) {\n sourceWrap = async function* () {\n yield* source;\n stream.end();\n };\n }\n else if (isIterable(source)) {\n sourceWrap = function* () {\n yield* source;\n stream.end();\n };\n }\n else {\n throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable');\n }\n return merge(stream, sourceWrap());\n }\n return duplex.source;\n };\n};\n//# sourceMappingURL=index.js.map","import { Logger } from \"@waku/utils\";\nimport { selectConnection } from \"@waku/utils/libp2p\";\nconst CONNECTION_TIMEOUT = 5_000;\nconst RETRY_BACKOFF_BASE = 1_000;\nconst MAX_RETRIES = 3;\nexport class StreamManager {\n multicodec;\n getConnections;\n addEventListener;\n streamPool;\n log;\n constructor(multicodec, getConnections, addEventListener) {\n this.multicodec = multicodec;\n this.getConnections = getConnections;\n this.addEventListener = addEventListener;\n this.log = new Logger(`stream-manager:${multicodec}`);\n this.streamPool = new Map();\n this.addEventListener(\"peer:update\", this.handlePeerUpdateStreamPool);\n }\n async getStream(peer) {\n const peerIdStr = peer.id.toString();\n const streamPromise = this.streamPool.get(peerIdStr);\n if (!streamPromise) {\n return this.createStream(peer);\n }\n this.streamPool.delete(peerIdStr);\n this.prepareStream(peer);\n try {\n const stream = await streamPromise;\n if (stream && stream.status !== \"closed\") {\n return stream;\n }\n }\n catch (error) {\n this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);\n this.log.warn(\"Attempting to create a new stream for the peer\");\n }\n return this.createStream(peer);\n }\n async createStream(peer, retries = 0) {\n const connections = this.getConnections(peer.id);\n const connection = selectConnection(connections);\n if (!connection) {\n throw new Error(\"Failed to get a connection to the peer\");\n }\n try {\n return await connection.newStream(this.multicodec);\n }\n catch (error) {\n if (retries < MAX_RETRIES) {\n const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);\n await new Promise((resolve) => setTimeout(resolve, backoff));\n return this.createStream(peer, retries + 1);\n }\n throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` + error);\n }\n }\n prepareStream(peer) {\n const timeoutPromise = new Promise((resolve) => setTimeout(resolve, CONNECTION_TIMEOUT));\n const streamPromise = Promise.race([\n this.createStream(peer),\n timeoutPromise.then(() => {\n throw new Error(\"Connection timeout\");\n })\n ]).catch((error) => {\n this.log.error(`Failed to prepare a new stream for ${peer.id.toString()} -- `, error);\n });\n this.streamPool.set(peer.id.toString(), streamPromise);\n }\n handlePeerUpdateStreamPool = (evt) => {\n const { peer } = evt.detail;\n if (peer.protocols.includes(this.multicodec)) {\n const isConnected = this.isConnectedTo(peer.id);\n if (isConnected) {\n this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);\n this.prepareStream(peer);\n }\n else {\n const peerIdStr = peer.id.toString();\n this.streamPool.delete(peerIdStr);\n this.log.info(`Removed pending stream for disconnected peer ${peerIdStr}`);\n }\n }\n };\n isConnectedTo(peerId) {\n const connections = this.getConnections(peerId);\n return connections.some((connection) => connection.status === \"open\");\n }\n}\n//# sourceMappingURL=stream_manager.js.map","import { bytesToUtf8 } from \"../bytes/index.js\";\nimport { decodeRelayShard } from \"../common/relay_shard_codec.js\";\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport function selectRandomPeer(peers) {\n if (peers.length === 0)\n return;\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n/**\n * Function to sort peers by latency from lowest to highest\n * @param peerStore - The Libp2p PeerStore\n * @param peers - The list of peers to choose from\n * @returns Sorted array of peers by latency\n */\nexport async function sortPeersByLatency(peerStore, peers) {\n if (peers.length === 0)\n return [];\n const results = await Promise.all(peers.map(async (peer) => {\n try {\n const pingBytes = (await peerStore.get(peer.id)).metadata.get(\"ping\");\n if (!pingBytes)\n return { peer, ping: Infinity };\n const ping = Number(bytesToUtf8(pingBytes));\n return { peer, ping };\n }\n catch (error) {\n return { peer, ping: Infinity };\n }\n }));\n // filter out null values\n const validResults = results.filter((result) => result !== null);\n return validResults\n .sort((a, b) => a.ping - b.ping)\n .map((result) => result.peer);\n}\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(peerStore, protocols) {\n const peers = [];\n await peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\nexport async function getConnectedPeersForProtocolAndShard(connections, peerStore, protocols, shardInfo) {\n const openConnections = connections.filter((connection) => connection.status === \"open\");\n const peerPromises = openConnections.map(async (connection) => {\n const peer = await peerStore.get(connection.remotePeer);\n const supportsProtocol = protocols.some((protocol) => peer.protocols.includes(protocol));\n if (supportsProtocol) {\n if (shardInfo) {\n const encodedPeerShardInfo = peer.metadata.get(\"shardInfo\");\n const peerShardInfo = encodedPeerShardInfo && decodeRelayShard(encodedPeerShardInfo);\n if (peerShardInfo && shardInfo.clusterId === peerShardInfo.clusterId) {\n return peer;\n }\n }\n else {\n return peer;\n }\n }\n return null;\n });\n const peersWithNulls = await Promise.all(peerPromises);\n return peersWithNulls.filter((peer) => peer !== null);\n}\nexport function selectConnection(connections) {\n if (!connections.length)\n return;\n if (connections.length === 1)\n return connections[0];\n let latestConnection;\n connections.forEach((connection) => {\n if (connection.status === \"open\") {\n if (!latestConnection) {\n latestConnection = connection;\n }\n else if (connection.timeline.open > latestConnection.timeline.open) {\n latestConnection = connection;\n }\n }\n });\n return latestConnection;\n}\n//# sourceMappingURL=index.js.map","import { ensureShardingConfigured } from \"@waku/utils\";\nimport { getConnectedPeersForProtocolAndShard, getPeersForProtocol, sortPeersByLatency } from \"@waku/utils/libp2p\";\nimport { filterPeersByDiscovery } from \"./filterPeers.js\";\nimport { StreamManager } from \"./stream_manager.js\";\n/**\n * A class with predefined helpers, to be used as a base to implement Waku\n * Protocols.\n */\nexport class BaseProtocol {\n multicodec;\n components;\n log;\n pubsubTopics;\n options;\n addLibp2pEventListener;\n removeLibp2pEventListener;\n streamManager;\n constructor(multicodec, components, log, pubsubTopics, options) {\n this.multicodec = multicodec;\n this.components = components;\n this.log = log;\n this.pubsubTopics = pubsubTopics;\n this.options = options;\n this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);\n this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);\n this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);\n }\n async getStream(peer) {\n return this.streamManager.getStream(peer);\n }\n get peerStore() {\n return this.components.peerStore;\n }\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * the class protocol. Waku may or may not be currently connected to these\n * peers.\n */\n async allPeers() {\n return getPeersForProtocol(this.peerStore, [this.multicodec]);\n }\n async connectedPeers() {\n const peers = await this.allPeers();\n return peers.filter((peer) => {\n return (this.components.connectionManager.getConnections(peer.id).length > 0);\n });\n }\n /**\n * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.\n *\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n \n * @returns A list of peers that support the protocol sorted by latency.\n */\n async getPeers({ numPeers, maxBootstrapPeers } = {\n maxBootstrapPeers: 1,\n numPeers: 0\n }) {\n // Retrieve all connected peers that support the protocol & shard (if configured)\n const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], this.options?.shardInfo\n ? ensureShardingConfigured(this.options.shardInfo).shardInfo\n : undefined);\n // Filter the peers based on discovery & number of peers requested\n const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);\n // Sort the peers by latency\n const sortedFilteredPeers = await sortPeersByLatency(this.peerStore, filteredPeers);\n if (sortedFilteredPeers.length === 0) {\n this.log.warn(\"No peers found. Ensure you have a connection to the network.\");\n }\n if (sortedFilteredPeers.length < numPeers) {\n this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);\n }\n return sortedFilteredPeers;\n }\n}\n//# sourceMappingURL=base_protocol.js.map","import { Tags } from \"@waku/interfaces\";\n/**\n * Retrieves a list of peers based on the specified criteria:\n * 1. If numPeers is 0, return all peers\n * 2. Bootstrap peers are prioritized\n * 3. Non-bootstrap peers are randomly selected to fill up to numPeers\n *\n * @param peers - The list of peers to filter from.\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n * @returns An array of peers based on the specified criteria.\n */\nexport function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {\n // Collect the bootstrap peers up to the specified maximum\n let bootstrapPeers = peers\n .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))\n .slice(0, maxBootstrapPeers);\n // If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array\n if (numPeers > 0 && numPeers < bootstrapPeers.length) {\n bootstrapPeers = bootstrapPeers.slice(0, numPeers);\n }\n // Collect non-bootstrap peers\n const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));\n // If numPeers is 0, return all peers\n if (numPeers === 0) {\n return [...bootstrapPeers, ...nonBootstrapPeers];\n }\n // Initialize the list of selected peers with the bootstrap peers\n const selectedPeers = [...bootstrapPeers];\n // Fill up to numPeers with remaining random peers if needed\n while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {\n const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);\n const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];\n selectedPeers.push(randomPeer);\n }\n return selectedPeers;\n}\n//# sourceMappingURL=filterPeers.js.map","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import { proto_filter_v2 as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n/**\n * FilterPushRPC represents a message conforming to the Waku FilterPush protocol.\n * Protocol documentation: https://rfc.vac.dev/spec/12/\n */\nexport class FilterPushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.MessagePush.decode(bytes);\n return new FilterPushRpc(res);\n }\n encode() {\n return proto.MessagePush.encode(this.proto);\n }\n get wakuMessage() {\n return this.proto.wakuMessage;\n }\n /**\n * Get the pubsub topic from the FilterPushRpc object.\n * @returns string\n */\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n}\nexport class FilterSubscribeRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createSubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeAllRequest(pubsubTopic) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE_ALL,\n pubsubTopic,\n contentTopics: []\n });\n }\n static createSubscriberPingRequest() {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBER_PING,\n pubsubTopic: \"\",\n contentTopics: []\n });\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeRequest.decode(bytes);\n return new FilterSubscribeRpc(res);\n }\n encode() {\n return proto.FilterSubscribeRequest.encode(this.proto);\n }\n get filterSubscribeType() {\n return this.proto.filterSubscribeType;\n }\n get requestId() {\n return this.proto.requestId;\n }\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n get contentTopics() {\n return this.proto.contentTopics;\n }\n}\nexport class FilterSubscribeResponse {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeResponse.decode(bytes);\n return new FilterSubscribeResponse(res);\n }\n encode() {\n return proto.FilterSubscribeResponse.encode(this.proto);\n }\n get statusCode() {\n return this.proto.statusCode;\n }\n get statusDesc() {\n return this.proto.statusDesc;\n }\n get requestId() {\n return this.proto.requestId;\n }\n}\n//# sourceMappingURL=filter_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { FilterPushRpc, FilterSubscribeResponse, FilterSubscribeRpc } from \"./filter_rpc.js\";\nconst log = new Logger(\"filter:v2\");\nexport const FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\nexport class FilterCore extends BaseProtocol {\n handleIncomingMessage;\n constructor(handleIncomingMessage, libp2p, options) {\n super(FilterCodecs.SUBSCRIBE, libp2p.components, log, options.pubsubTopics, options);\n this.handleIncomingMessage = handleIncomingMessage;\n libp2p\n .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {\n maxInboundStreams: 100\n })\n .catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n }\n onRequest(streamData) {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n pipe(stream, lp.decode, async (source) => {\n for await (const bytes of source) {\n const response = FilterPushRpc.decode(bytes.slice());\n const { pubsubTopic, wakuMessage } = response;\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n await this.handleIncomingMessage(pubsubTopic, wakuMessage);\n }\n }).then(() => {\n log.info(\"Receiving pipe closed.\");\n }, (e) => {\n log.error(\"Error with receiving pipe\", e);\n });\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n async subscribe(pubsubTopic, peer, contentTopics) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createSubscribeRequest(pubsubTopic, contentTopics);\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send subscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async unsubscribe(pubsubTopic, peer, contentTopics) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n const unsubscribeRequest = FilterSubscribeRpc.createUnsubscribeRequest(pubsubTopic, contentTopics);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);\n }\n catch (error) {\n log.error(\"Failed to send unsubscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n async unsubscribeAll(pubsubTopic, peer) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);\n const res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n if (!res || !res.length) {\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n },\n success: null\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async ping(peer) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n const request = FilterSubscribeRpc.createSubscriberPingRequest();\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send ping request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n if (!res || !res.length) {\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_lightpush as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\nexport class PushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(message, pubsubTopic) {\n return new PushRpc({\n requestId: uuid(),\n request: {\n message: message,\n pubsubTopic: pubsubTopic\n },\n response: undefined\n });\n }\n static decode(bytes) {\n const res = proto.PushRpc.decode(bytes);\n return new PushRpc(res);\n }\n encode() {\n return proto.PushRpc.encode(this.proto);\n }\n get query() {\n return this.proto.request;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=push_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { PushResponse } from \"@waku/proto\";\nimport { isMessageSizeUnderCap } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { PushRpc } from \"./push_rpc.js\";\nconst log = new Logger(\"light-push\");\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class LightPushCore extends BaseProtocol {\n constructor(libp2p, options) {\n super(LightPushCodec, libp2p.components, log, options.pubsubTopics, options);\n }\n async preparePushMessage(encoder, message) {\n try {\n if (!message.payload || message.payload.length === 0) {\n log.error(\"Failed to send waku light push: payload is empty\");\n return { query: null, error: ProtocolError.EMPTY_PAYLOAD };\n }\n if (!(await isMessageSizeUnderCap(encoder, message))) {\n log.error(\"Failed to send waku light push: message is bigger than 1MB\");\n return { query: null, error: ProtocolError.SIZE_TOO_BIG };\n }\n const protoMessage = await encoder.toProtoObj(message);\n if (!protoMessage) {\n log.error(\"Failed to encode to protoMessage, aborting push\");\n return {\n query: null,\n error: ProtocolError.ENCODE_FAILED\n };\n }\n const query = PushRpc.createRequest(protoMessage, encoder.pubsubTopic);\n return { query, error: null };\n }\n catch (error) {\n log.error(\"Failed to prepare push message\", error);\n return {\n query: null,\n error: ProtocolError.GENERIC_FAIL\n };\n }\n }\n async send(encoder, message, peer) {\n const { query, error: preparationError } = await this.preparePushMessage(encoder, message);\n if (preparationError || !query) {\n return {\n success: null,\n failure: {\n error: preparationError,\n peerId: peer.id\n }\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n let res;\n try {\n res = await pipe([query.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (err) {\n log.error(\"Failed to send waku light push request\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n let response;\n try {\n response = PushRpc.decode(bytes).response;\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.DECODE_FAILED,\n peerId: peer.id\n }\n };\n }\n if (!response) {\n log.error(\"Remote peer fault: No response in PushRPC\");\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_FAULT,\n peerId: peer.id\n }\n };\n }\n if (!response.isSuccess) {\n log.error(\"Remote peer rejected the message: \", response.info);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return { success: peer.id, failure: null };\n }\n}\n//# sourceMappingURL=index.js.map","const MB = 1024 ** 2;\nconst SIZE_CAP_IN_MB = 1;\n/**\n * Return whether the size of the message is under the upper limit for the network.\n * This performs a protobuf encoding! If you have access to the fully encoded message,\n * use {@link isSizeUnderCapBuf} instead.\n * @param message\n * @param encoder\n */\nexport async function isMessageSizeUnderCap(encoder, message) {\n const buf = await encoder.toWire(message);\n if (!buf)\n return false;\n return isWireSizeUnderCap(buf);\n}\nexport const isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;\n//# sourceMappingURL=is_size_valid.js.map","const EmptyMessage = {\n payload: new Uint8Array(),\n contentTopic: \"\",\n version: undefined,\n timestamp: undefined,\n meta: undefined,\n rateLimitProof: undefined,\n ephemeral: undefined\n};\nexport function toProtoMessage(wire) {\n return { ...EmptyMessage, ...wire };\n}\n//# sourceMappingURL=to_proto_message.js.map","import { proto_store as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\nconst OneMillion = BigInt(1_000_000);\nexport var PageDirection;\n(function (PageDirection) {\n PageDirection[\"BACKWARD\"] = \"backward\";\n PageDirection[\"FORWARD\"] = \"forward\";\n})(PageDirection || (PageDirection = {}));\nexport class HistoryRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n get query() {\n return this.proto.query;\n }\n get response() {\n return this.proto.response;\n }\n /**\n * Create History Query.\n */\n static createQuery(params) {\n const contentFilters = params.contentTopics.map((contentTopic) => {\n return { contentTopic };\n });\n const direction = directionToProto(params.pageDirection);\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction\n };\n let startTime, endTime;\n if (params.startTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n startTime = BigInt(params.startTime.valueOf()) * OneMillion;\n }\n if (params.endTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n endTime = BigInt(params.endTime.valueOf()) * OneMillion;\n }\n return new HistoryRpc({\n requestId: uuid(),\n query: {\n pubsubTopic: params.pubsubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime\n },\n response: undefined\n });\n }\n decode(bytes) {\n const res = proto.HistoryRpc.decode(bytes);\n return new HistoryRpc(res);\n }\n encode() {\n return proto.HistoryRpc.encode(this.proto);\n }\n}\nfunction directionToProto(pageDirection) {\n switch (pageDirection) {\n case PageDirection.BACKWARD:\n return proto.PagingInfo.Direction.BACKWARD;\n case PageDirection.FORWARD:\n return proto.PagingInfo.Direction.FORWARD;\n default:\n return proto.PagingInfo.Direction.BACKWARD;\n }\n}\n//# sourceMappingURL=history_rpc.js.map","import { proto_store as proto } from \"@waku/proto\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { toProtoMessage } from \"../to_proto_message.js\";\nimport { HistoryRpc, PageDirection } from \"./history_rpc.js\";\nvar HistoryError = proto.HistoryResponse.HistoryError;\nconst log = new Logger(\"store\");\nexport const StoreCodec = \"/vac/waku/store/2.0.0-beta4\";\nexport { PageDirection };\n/**\n * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).\n *\n * The Waku Store protocol can be used to retrieved historical messages.\n */\nexport class StoreCore extends BaseProtocol {\n constructor(libp2p, options) {\n super(StoreCodec, libp2p.components, log, options.pubsubTopics, options);\n }\n async *queryPerPage(queryOpts, decoders, peer) {\n if (queryOpts.contentTopics.toString() !==\n Array.from(decoders.keys()).toString()) {\n throw new Error(\"Internal error, the decoders should match the query's content topics\");\n }\n let currentCursor = queryOpts.cursor;\n while (true) {\n queryOpts.cursor = currentCursor;\n const historyRpcQuery = HistoryRpc.createQuery(queryOpts);\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (e) {\n log.error(\"Failed to get stream\", e);\n break;\n }\n const res = await pipe([historyRpcQuery.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const reply = historyRpcQuery.decode(bytes);\n if (!reply.response) {\n log.warn(\"Stopping pagination due to store `response` field missing\");\n break;\n }\n const response = reply.response;\n if (response.error && response.error !== HistoryError.NONE) {\n throw \"History response contains an Error: \" + response.error;\n }\n if (!response.messages || !response.messages.length) {\n log.warn(\"Stopping pagination due to store `response.messages` field missing or empty\");\n break;\n }\n log.error(`${response.messages.length} messages retrieved from store`);\n yield response.messages.map((protoMsg) => {\n const contentTopic = protoMsg.contentTopic;\n if (typeof contentTopic !== \"undefined\") {\n const decoder = decoders.get(contentTopic);\n if (decoder) {\n return decoder.fromProtoObj(queryOpts.pubsubTopic, toProtoMessage(protoMsg));\n }\n }\n return Promise.resolve(undefined);\n });\n const nextCursor = response.pagingInfo?.cursor;\n if (typeof nextCursor === \"undefined\") {\n // If the server does not return cursor then there is an issue,\n // Need to abort, or we end up in an infinite loop\n log.warn(\"Stopping pagination due to `response.pagingInfo.cursor` missing from store response\");\n break;\n }\n currentCursor = nextCursor;\n const responsePageSize = response.pagingInfo?.pageSize;\n const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;\n if (\n // Response page size smaller than query, meaning this is the last page\n responsePageSize &&\n queryPageSize &&\n responsePageSize < queryPageSize) {\n break;\n }\n }\n }\n}\n//# sourceMappingURL=index.js.map","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\t\tif (options.filter && !options.filter(value)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = error => {\n\t\t\tcancel();\n\t\t\treject(error);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\ttimeout.cancel = cancel;\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]);\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\tif (options.filter && !options.filter(value)) {\n\t\t\tcancel();\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n","import { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { pEvent } from \"p-event\";\nconst log = new Logger(\"wait-for-remote-peer\");\n//TODO: move this function within the Waku class: https://github.com/waku-org/js-waku/issues/1761\n/**\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using\n * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with\n * {@link @waku/sdk!createLightNode}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n * @throws If passing a protocol that is not mounted\n * @default Wait for remote peers with protocols enabled locally and no time out is applied.\n */\nexport async function waitForRemotePeer(waku, protocols, timeoutMs) {\n protocols = protocols ?? getEnabledProtocols(waku);\n if (!waku.isStarted())\n return Promise.reject(\"Waku node is not started\");\n const promises = [];\n if (protocols.includes(Protocols.Relay)) {\n if (!waku.relay)\n throw new Error(\"Cannot wait for Relay peer: protocol not mounted\");\n promises.push(waitForGossipSubPeerInMesh(waku.relay));\n }\n if (protocols.includes(Protocols.Store)) {\n if (!waku.store)\n throw new Error(\"Cannot wait for Store peer: protocol not mounted\");\n promises.push(waitForConnectedPeer(waku.store.protocol, waku.libp2p.services.metadata));\n }\n if (protocols.includes(Protocols.LightPush)) {\n if (!waku.lightPush)\n throw new Error(\"Cannot wait for LightPush peer: protocol not mounted\");\n promises.push(waitForConnectedPeer(waku.lightPush.protocol, waku.libp2p.services.metadata));\n }\n if (protocols.includes(Protocols.Filter)) {\n if (!waku.filter)\n throw new Error(\"Cannot wait for Filter peer: protocol not mounted\");\n promises.push(waitForConnectedPeer(waku.filter.protocol, waku.libp2p.services.metadata));\n }\n if (timeoutMs) {\n await rejectOnTimeout(Promise.all(promises), timeoutMs, \"Timed out waiting for a remote peer.\");\n }\n else {\n await Promise.all(promises);\n }\n}\n//TODO: move this function within protocol SDK class: https://github.com/waku-org/js-waku/issues/1761\n/**\n * Wait for a peer with the given protocol to be connected.\n * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.\n */\nasync function waitForConnectedPeer(protocol, metadataService) {\n const codec = protocol.multicodec;\n const peers = await protocol.connectedPeers();\n if (peers.length) {\n if (!metadataService) {\n log.info(`${codec} peer found: `, peers[0].id.toString());\n return;\n }\n // once a peer is connected, we need to confirm the metadata handshake with at least one of those peers if sharding is enabled\n try {\n await Promise.any(peers.map((peer) => metadataService.confirmOrAttemptHandshake(peer.id)));\n return;\n }\n catch (e) {\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\")\n log.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);\n log.error(`Error waiting for handshake confirmation: ${e}`);\n }\n }\n log.info(`Waiting for ${codec} peer`);\n // else we'll just wait for the next peer to connect\n await new Promise((resolve) => {\n const cb = (evt) => {\n if (evt.detail?.protocols?.includes(codec)) {\n if (metadataService) {\n metadataService\n .confirmOrAttemptHandshake(evt.detail.peerId)\n .then(() => {\n protocol.removeLibp2pEventListener(\"peer:identify\", cb);\n resolve();\n })\n .catch((e) => {\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\")\n log.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);\n log.error(`Error waiting for handshake confirmation: ${e}`);\n });\n }\n else {\n protocol.removeLibp2pEventListener(\"peer:identify\", cb);\n resolve();\n }\n }\n };\n protocol.addLibp2pEventListener(\"peer:identify\", cb);\n });\n}\n/**\n * Wait for at least one peer with the given protocol to be connected and in the gossipsub\n * mesh for all pubsubTopics.\n */\nasync function waitForGossipSubPeerInMesh(waku) {\n let peers = waku.getMeshPeers();\n const pubsubTopics = waku.pubsubTopics;\n for (const topic of pubsubTopics) {\n while (peers.length == 0) {\n await pEvent(waku.gossipSub, \"gossipsub:heartbeat\");\n peers = waku.getMeshPeers(topic);\n }\n }\n}\nconst awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));\nasync function rejectOnTimeout(promise, timeoutMs, rejectReason) {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\nfunction getEnabledProtocols(waku) {\n const protocols = [];\n if (waku.relay) {\n protocols.push(Protocols.Relay);\n }\n if (waku.filter) {\n protocols.push(Protocols.Filter);\n }\n if (waku.store) {\n protocols.push(Protocols.Store);\n }\n if (waku.lightPush) {\n protocols.push(Protocols.LightPush);\n }\n return protocols;\n}\n//# sourceMappingURL=wait_for_remote_peer.js.map","import { setMaxListeners } from './events.js';\n/**\n * An implementation of a typed event target\n * etc\n */\nexport class TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n detail;\n constructor(message, data) {\n super(message, data);\n // @ts-expect-error could be undefined\n this.detail = data?.detail;\n }\n}\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;\n//# sourceMappingURL=event-target.js.map","import { Logger, pubsubTopicToSingleShardInfo } from \"@waku/utils\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport { createEncoder } from \"./message/version_0.js\";\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\nconst log = new Logger(\"keep-alive\");\nexport class KeepAliveManager {\n pingKeepAliveTimers;\n relayKeepAliveTimers;\n options;\n relay;\n constructor(options, relay) {\n this.pingKeepAliveTimers = new Map();\n this.relayKeepAliveTimers = new Map();\n this.options = options;\n this.relay = relay;\n }\n start(peerId, libp2pPing, peerStore) {\n // Just in case a timer already exists for this peer\n this.stop(peerId);\n const { pingKeepAlive: pingPeriodSecs, relayKeepAlive: relayPeriodSecs } = this.options;\n const peerIdStr = peerId.toString();\n // Ping the peer every pingPeriodSecs seconds\n // if pingPeriodSecs is 0, don't ping the peer\n if (pingPeriodSecs !== 0) {\n const interval = setInterval(() => {\n void (async () => {\n let ping;\n try {\n // ping the peer for keep alive\n // also update the peer store with the latency\n try {\n ping = await libp2pPing.ping(peerId);\n log.info(`Ping succeeded (${peerIdStr})`, ping);\n }\n catch (error) {\n log.error(`Ping failed for peer (${peerIdStr}).\n Next ping will be attempted in ${pingPeriodSecs} seconds.\n `);\n return;\n }\n try {\n await peerStore.merge(peerId, {\n metadata: {\n ping: utf8ToBytes(ping.toString())\n }\n });\n }\n catch (e) {\n log.error(\"Failed to update ping\", e);\n }\n }\n catch (e) {\n log.error(`Ping failed (${peerIdStr})`, e);\n }\n })();\n }, pingPeriodSecs * 1000);\n this.pingKeepAliveTimers.set(peerIdStr, interval);\n }\n const relay = this.relay;\n if (relay && relayPeriodSecs !== 0) {\n const intervals = this.scheduleRelayPings(relay, relayPeriodSecs, peerId.toString());\n this.relayKeepAliveTimers.set(peerId, intervals);\n }\n }\n stop(peerId) {\n const peerIdStr = peerId.toString();\n if (this.pingKeepAliveTimers.has(peerIdStr)) {\n clearInterval(this.pingKeepAliveTimers.get(peerIdStr));\n this.pingKeepAliveTimers.delete(peerIdStr);\n }\n if (this.relayKeepAliveTimers.has(peerId)) {\n this.relayKeepAliveTimers.get(peerId)?.map(clearInterval);\n this.relayKeepAliveTimers.delete(peerId);\n }\n }\n stopAll() {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers)\n ]) {\n clearInterval(timer);\n }\n this.pingKeepAliveTimers.clear();\n this.relayKeepAliveTimers.clear();\n }\n connectionsExist() {\n return (this.pingKeepAliveTimers.size > 0 || this.relayKeepAliveTimers.size > 0);\n }\n scheduleRelayPings(relay, relayPeriodSecs, peerIdStr) {\n // send a ping message to each PubsubTopic the peer is part of\n const intervals = [];\n for (const topic of relay.pubsubTopics) {\n const meshPeers = relay.getMeshPeers(topic);\n if (!meshPeers.includes(peerIdStr))\n continue;\n const encoder = createEncoder({\n pubsubTopicShardInfo: pubsubTopicToSingleShardInfo(topic),\n contentTopic: RelayPingContentTopic,\n ephemeral: true\n });\n const interval = setInterval(() => {\n log.info(\"Sending Waku Relay ping message\");\n relay\n .send(encoder, { payload: new Uint8Array([1]) })\n .catch((e) => log.error(\"Failed to send relay ping\", e));\n }, relayPeriodSecs * 1000);\n intervals.push(interval);\n }\n return intervals;\n }\n}\n//# sourceMappingURL=keep_alive_manager.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { EConnectionStateEvents, EPeersByDiscoveryEvents } from \"@waku/interfaces\";\nimport { Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport { KeepAliveManager } from \"./keep_alive_manager.js\";\nconst log = new Logger(\"connection-manager\");\nexport const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;\nexport const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;\nexport const DEFAULT_MAX_PARALLEL_DIALS = 3;\nexport class ConnectionManager extends TypedEventEmitter {\n configuredPubsubTopics;\n static instances = new Map();\n keepAliveManager;\n options;\n libp2p;\n dialAttemptsForPeer = new Map();\n dialErrorsForPeer = new Map();\n currentActiveParallelDialCount = 0;\n pendingPeerDialQueue = [];\n online = false;\n isConnected() {\n return this.online;\n }\n toggleOnline() {\n if (!this.online) {\n this.online = true;\n this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.online\n }));\n }\n }\n toggleOffline() {\n if (this.online && this.libp2p.getConnections().length == 0) {\n this.online = false;\n this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.online\n }));\n }\n }\n static create(peerId, libp2p, keepAliveOptions, pubsubTopics, relay, options) {\n let instance = ConnectionManager.instances.get(peerId);\n if (!instance) {\n instance = new ConnectionManager(libp2p, keepAliveOptions, pubsubTopics, relay, options);\n ConnectionManager.instances.set(peerId, instance);\n }\n return instance;\n }\n async getPeersByDiscovery() {\n const peersDiscovered = await this.libp2p.peerStore.all();\n const peersConnected = this.libp2p\n .getConnections()\n .map((conn) => conn.remotePeer);\n const peersDiscoveredByBootstrap = [];\n const peersDiscoveredByPeerExchange = [];\n const peersDiscoveredByLocal = [];\n const peersConnectedByBootstrap = [];\n const peersConnectedByPeerExchange = [];\n const peersConnectedByLocal = [];\n for (const peer of peersDiscovered) {\n const tags = await this.getTagNamesForPeer(peer.id);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersDiscoveredByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersDiscoveredByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersDiscoveredByLocal.push(peer);\n }\n }\n for (const peerId of peersConnected) {\n const peer = await this.libp2p.peerStore.get(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersConnectedByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersConnectedByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersConnectedByLocal.push(peer);\n }\n }\n return {\n DISCOVERED: {\n [Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,\n [Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,\n [Tags.LOCAL]: peersDiscoveredByLocal\n },\n CONNECTED: {\n [Tags.BOOTSTRAP]: peersConnectedByBootstrap,\n [Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,\n [Tags.LOCAL]: peersConnectedByLocal\n }\n };\n }\n constructor(libp2p, keepAliveOptions, configuredPubsubTopics, relay, options) {\n super();\n this.configuredPubsubTopics = configuredPubsubTopics;\n this.libp2p = libp2p;\n this.configuredPubsubTopics = configuredPubsubTopics;\n this.options = {\n maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,\n maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,\n maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,\n ...options\n };\n this.keepAliveManager = new KeepAliveManager(keepAliveOptions, relay);\n this.run()\n .then(() => log.info(`Connection Manager is now running`))\n .catch((error) => log.error(`Unexpected error while running service`, error));\n // libp2p emits `peer:discovery` events during its initialization\n // which means that before the ConnectionManager is initialized, some peers may have been discovered\n // we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager\n this.dialPeerStorePeers().catch((error) => log.error(`Unexpected error while dialing peer store peers`, error));\n }\n async dialPeerStorePeers() {\n const peerInfos = await this.libp2p.peerStore.all();\n const dialPromises = [];\n for (const peerInfo of peerInfos) {\n if (this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id))\n continue;\n dialPromises.push(this.attemptDial(peerInfo.id));\n }\n try {\n await Promise.all(dialPromises);\n }\n catch (error) {\n log.error(`Unexpected error while dialing peer store peers`, error);\n }\n }\n async run() {\n // start event listeners\n this.startPeerDiscoveryListener();\n this.startPeerConnectionListener();\n this.startPeerDisconnectionListener();\n }\n stop() {\n this.keepAliveManager.stopAll();\n this.libp2p.removeEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n this.libp2p.removeEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n this.libp2p.removeEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n }\n async dialPeer(peerId) {\n this.currentActiveParallelDialCount += 1;\n let dialAttempt = 0;\n while (dialAttempt < this.options.maxDialAttemptsForPeer) {\n try {\n log.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);\n await this.libp2p.dial(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n // add tag to connection describing discovery mechanism\n // don't add duplicate tags\n this.libp2p.getConnections(peerId).forEach((conn) => {\n conn.tags = Array.from(new Set([...conn.tags, ...tags]));\n });\n // instead of deleting the peer from the peer store, we set the dial attempt to -1\n // this helps us keep track of peers that have been dialed before\n this.dialAttemptsForPeer.set(peerId.toString(), -1);\n // Dialing succeeded, break the loop\n break;\n }\n catch (error) {\n if (error instanceof AggregateError) {\n // Handle AggregateError\n log.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);\n }\n else {\n // Handle generic error\n log.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);\n }\n this.dialErrorsForPeer.set(peerId.toString(), error);\n dialAttempt++;\n this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);\n }\n }\n // Always decrease the active dial count and process the dial queue\n this.currentActiveParallelDialCount--;\n this.processDialQueue();\n // If max dial attempts reached and dialing failed, delete the peer\n if (dialAttempt === this.options.maxDialAttemptsForPeer) {\n try {\n const error = this.dialErrorsForPeer.get(peerId.toString());\n if (error) {\n let errorMessage;\n if (error instanceof AggregateError) {\n if (!error.errors) {\n log.warn(`No errors array found for AggregateError`);\n }\n else if (error.errors.length === 0) {\n log.warn(`Errors array is empty for AggregateError`);\n }\n else {\n errorMessage = JSON.stringify(error.errors[0]);\n }\n }\n else {\n errorMessage = error.message;\n }\n log.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);\n }\n this.dialErrorsForPeer.delete(peerId.toString());\n await this.libp2p.peerStore.delete(peerId);\n }\n catch (error) {\n throw new Error(`Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`);\n }\n }\n }\n async dropConnection(peerId) {\n try {\n this.keepAliveManager.stop(peerId);\n await this.libp2p.hangUp(peerId);\n log.info(`Dropped connection with peer ${peerId.toString()}`);\n }\n catch (error) {\n log.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);\n }\n }\n processDialQueue() {\n if (this.pendingPeerDialQueue.length > 0 &&\n this.currentActiveParallelDialCount < this.options.maxParallelDials) {\n const peerId = this.pendingPeerDialQueue.shift();\n if (!peerId)\n return;\n this.attemptDial(peerId).catch((error) => {\n log.error(error);\n });\n }\n }\n startPeerDiscoveryListener() {\n this.libp2p.addEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n }\n startPeerConnectionListener() {\n this.libp2p.addEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n }\n startPeerDisconnectionListener() {\n // TODO: ensure that these following issues are updated and confirmed\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n this.libp2p.addEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n }\n async attemptDial(peerId) {\n if (!(await this.shouldDialPeer(peerId)))\n return;\n if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {\n this.pendingPeerDialQueue.push(peerId);\n return;\n }\n this.dialPeer(peerId).catch((err) => {\n log.error(`Error dialing peer ${peerId.toString()} : ${err}`);\n });\n }\n onEventHandlers = {\n \"peer:discovery\": (evt) => {\n void (async () => {\n const { id: peerId } = evt.detail;\n await this.dispatchDiscoveryEvent(peerId);\n try {\n await this.attemptDial(peerId);\n }\n catch (error) {\n log.error(`Error dialing peer ${peerId.toString()} : ${error}`);\n }\n })();\n },\n \"peer:connect\": (evt) => {\n void (async () => {\n log.info(`Connected to peer ${evt.detail.toString()}`);\n const peerId = evt.detail;\n this.keepAliveManager.start(peerId, this.libp2p.services.ping, this.libp2p.peerStore);\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n if (isBootstrap) {\n const bootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));\n // If we have too many bootstrap connections, drop one\n if (bootstrapConnections.length > this.options.maxBootstrapPeersAllowed) {\n await this.dropConnection(peerId);\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP, {\n detail: peerId\n }));\n }\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n this.toggleOnline();\n })();\n },\n \"peer:disconnect\": (evt) => {\n void (async () => {\n this.keepAliveManager.stop(evt.detail);\n this.toggleOffline();\n })();\n }\n };\n /**\n * Checks if the peer should be dialed based on the following conditions:\n * 1. If the peer is already connected, don't dial\n * 2. If the peer is not part of any of the configured pubsub topics, don't dial\n * 3. If the peer is not dialable based on bootstrap status, don't dial\n * 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it\n * @returns true if the peer should be dialed, false otherwise\n */\n async shouldDialPeer(peerId) {\n // if we're already connected to the peer, don't dial\n const isConnected = this.libp2p.getConnections(peerId).length > 0;\n if (isConnected) {\n log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);\n return false;\n }\n // if the peer is not part of any of the configured pubsub topics, don't dial\n if (!(await this.isPeerTopicConfigured(peerId))) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n log.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`);\n return false;\n }\n // if the peer is not dialable based on bootstrap status, don't dial\n if (!(await this.isPeerDialableBasedOnBootstrapStatus(peerId))) {\n log.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);\n return false;\n }\n // If the peer is already already has an active dial attempt, or has been dialed before, don't dial it\n if (this.dialAttemptsForPeer.has(peerId.toString())) {\n log.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);\n return false;\n }\n return true;\n }\n /**\n * Checks if the peer is dialable based on the following conditions:\n * 1. If the peer is a bootstrap peer, it is only dialable if the number of current bootstrap connections is less than the max allowed.\n * 2. If the peer is not a bootstrap peer\n */\n async isPeerDialableBasedOnBootstrapStatus(peerId) {\n const tagNames = await this.getTagNamesForPeer(peerId);\n const isBootstrap = tagNames.some((tagName) => tagName === Tags.BOOTSTRAP);\n if (isBootstrap) {\n const currentBootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => {\n return conn.tags.find((name) => name === Tags.BOOTSTRAP);\n }).length;\n if (currentBootstrapConnections < this.options.maxBootstrapPeersAllowed)\n return true;\n }\n else {\n return true;\n }\n return false;\n }\n async dispatchDiscoveryEvent(peerId) {\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n this.dispatchEvent(new CustomEvent(isBootstrap\n ? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP\n : EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n /**\n * Fetches the tag names for a given peer\n */\n async getTagNamesForPeer(peerId) {\n try {\n const peer = await this.libp2p.peerStore.get(peerId);\n return Array.from(peer.tags.keys());\n }\n catch (error) {\n log.error(`Failed to get peer ${peerId}, error: ${error}`);\n return [];\n }\n }\n async isPeerTopicConfigured(peerId) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n // If there's no shard information, simply return true\n if (!shardInfo)\n return true;\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n const isTopicConfigured = pubsubTopics.some((topic) => this.configuredPubsubTopics.includes(topic));\n return isTopicConfigured;\n }\n async getPeerShardInfo(peerId, peerStore) {\n const peer = await peerStore.get(peerId);\n const shardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (!shardInfoBytes)\n return undefined;\n return decodeRelayShard(shardInfoBytes);\n }\n}\n//# sourceMappingURL=connection_manager.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { proto_metadata } from \"@waku/proto\";\nimport { encodeRelayShard, Logger, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nconst log = new Logger(\"metadata\");\nexport const MetadataCodec = \"/vac/waku/metadata/1.0.0\";\nclass Metadata extends BaseProtocol {\n shardInfo;\n libp2pComponents;\n handshakesConfirmed = new Map();\n constructor(shardInfo, libp2p) {\n super(MetadataCodec, libp2p.components, log, shardInfoToPubsubTopics(shardInfo));\n this.shardInfo = shardInfo;\n this.libp2pComponents = libp2p;\n void libp2p.registrar.handle(MetadataCodec, (streamData) => {\n void this.onRequest(streamData);\n });\n }\n /**\n * Handle an incoming metadata request\n */\n async onRequest(streamData) {\n try {\n const { stream, connection } = streamData;\n const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode(this.shardInfo);\n const encodedResponse = await pipe([encodedShardInfo], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return;\n }\n await this.savePeerShardInfo(connection.remotePeer, shardInfo);\n }\n catch (error) {\n log.error(\"Error handling metadata request\", error);\n }\n }\n /**\n * Make a metadata query to a peer\n */\n async query(peerId) {\n const request = proto_metadata.WakuMetadataRequest.encode(this.shardInfo);\n const peer = await this.peerStore.get(peerId);\n if (!peer) {\n return {\n shardInfo: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n shardInfo: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const encodedResponse = await pipe([request], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return {\n shardInfo: null,\n error\n };\n }\n await this.savePeerShardInfo(peerId, shardInfo);\n return {\n shardInfo,\n error: null\n };\n }\n async confirmOrAttemptHandshake(peerId) {\n const shardInfo = this.handshakesConfirmed.get(peerId.toString());\n if (shardInfo) {\n return {\n shardInfo,\n error: null\n };\n }\n return await this.query(peerId);\n }\n decodeMetadataResponse(encodedResponse) {\n const bytes = new Uint8ArrayList();\n encodedResponse.forEach((chunk) => {\n bytes.append(chunk);\n });\n const response = proto_metadata.WakuMetadataResponse.decode(bytes);\n if (!response) {\n log.error(\"Error decoding metadata response\");\n return {\n shardInfo: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n return {\n shardInfo: response,\n error: null\n };\n }\n async savePeerShardInfo(peerId, shardInfo) {\n // add or update the shardInfo to peer store\n await this.libp2pComponents.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n this.handshakesConfirmed.set(peerId.toString(), shardInfo);\n }\n}\nexport function wakuMetadata(shardInfo) {\n return (components) => new Metadata(shardInfo, components);\n}\n//# sourceMappingURL=index.js.map","/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal(promise, signal, opts) {\n if (signal == null) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode));\n }\n let listener;\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error);\n };\n signal.addEventListener('abort', listener);\n })\n ]);\n }\n finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\nimport deferred, {} from 'p-defer';\nimport { raceSignal } from 'race-signal';\nclass QueuelessPushable {\n readNext;\n haveNext;\n ended;\n nextResult;\n constructor() {\n this.ended = false;\n this.readNext = deferred();\n this.haveNext = deferred();\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n async next() {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise;\n }\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined');\n }\n const nextResult = this.nextResult;\n this.nextResult = undefined;\n // signal to the supplier that we read the value\n this.readNext.resolve();\n this.readNext = deferred();\n return nextResult;\n }\n async throw(err) {\n this.ended = true;\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => { });\n this.haveNext.reject(err);\n }\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n async return() {\n const result = {\n done: true,\n value: undefined\n };\n await this._push(undefined);\n return result;\n }\n async push(value, options) {\n await this._push(value, options);\n }\n async end(err, options) {\n if (err != null) {\n await this.throw(err);\n }\n else {\n // abortable return\n await this._push(undefined, options);\n }\n }\n async _push(value, options) {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable');\n }\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise;\n }\n if (value != null) {\n this.nextResult = { done: false, value };\n }\n else {\n this.ended = true;\n this.nextResult = { done: true, value: undefined };\n }\n // let the consumer know we have a new value\n this.haveNext.resolve();\n this.haveNext = deferred();\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(this.readNext.promise, options?.signal, options);\n }\n}\nexport function queuelessPushable() {\n return new QueuelessPushable();\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\nimport { queuelessPushable } from 'it-queueless-pushable';\nimport { Uint8ArrayList } from 'uint8arraylist';\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\nexport class AbortError extends CodeError {\n type;\n constructor(message) {\n super(message, 'ABORT_ERR');\n this.type = 'aborted';\n }\n}\nexport function byteStream(duplex, opts) {\n const write = queuelessPushable();\n duplex.sink(write).catch(async (err) => {\n await write.end(err);\n });\n duplex.sink = async (source) => {\n for await (const buf of source) {\n await write.push(buf);\n }\n await write.end();\n };\n let source = duplex.source;\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]();\n }\n else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]();\n }\n const readBuffer = new Uint8ArrayList();\n const W = {\n read: async (bytes, options) => {\n options?.signal?.throwIfAborted();\n let listener;\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'));\n };\n options?.signal?.addEventListener('abort', listener);\n });\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n return new Uint8ArrayList();\n }\n return value;\n }\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n throw new CodeError('unexpected end of input', 'ERR_UNEXPECTED_EOF');\n }\n readBuffer.append(value);\n }\n const buf = readBuffer.sublist(0, bytes);\n readBuffer.consume(bytes);\n return buf;\n }\n finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener);\n }\n }\n },\n write: async (data, options) => {\n options?.signal?.throwIfAborted();\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options);\n }\n else {\n await write.push(data.subarray(), options);\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source;\n duplex.source = (async function* () {\n if (opts?.yieldBytes === false) {\n yield readBuffer;\n }\n else {\n yield* readBuffer;\n }\n yield* originalStream;\n }());\n }\n return duplex;\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\nimport { byteStream } from 'it-byte-stream';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nclass CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\nexport function lpStream(duplex, opts = {}) {\n const bytes = byteStream(duplex, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? varint.decode;\n const encodeLength = opts?.lengthEncoder ?? varint.encode;\n const W = {\n read: async (options) => {\n let dataLength = -1;\n const lengthBuffer = new Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options));\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new CodeError('message length length too long', 'ERR_MSG_LENGTH_TOO_LONG');\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new CodeError('message length too long', 'ERR_MSG_DATA_TOO_LONG');\n }\n return bytes.read(dataLength, options);\n },\n write: async (data, options) => {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n writeV: async (data, options) => {\n const list = new Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap: () => {\n return bytes.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","import defer from 'p-defer';\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair() {\n const deferred = defer();\n let piped = false;\n return {\n sink: async (source) => {\n if (piped) {\n throw new Error('already piped');\n }\n piped = true;\n deferred.resolve(source);\n },\n source: (async function* () {\n const source = await deferred.promise;\n yield* source;\n }())\n };\n}\n//# sourceMappingURL=index.js.map","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535;\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16;\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);\n//# sourceMappingURL=constants.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!isBytes(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = data.slice();\n else\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a))\n throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function ensureBytes(b, len) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (typeof len === 'number')\n if (b.length !== len)\n throw new Error(`Uint8Array length ${len} expected`);\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n//# sourceMappingURL=utils.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// TODO: merge with utils\nfunction isBytes(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint8Array || a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","import { exists as aexists, output as aoutput } from './_assert.js';\nimport { ensureBytes, toBytes } from './utils.js';\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 {\n constructor(key) {\n this.blockLen = 16;\n this.outputLen = 16;\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.pos = 0;\n this.finished = false;\n key = toBytes(key);\n ensureBytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n }\n update(data) {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n this.h.fill(0);\n this.r.fill(0);\n this.buffer.fill(0);\n this.pad.fill(0);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n // buffer.subarray(pos).fill(0);\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n//# sourceMappingURL=_poly1305.js.map","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { checkOpts, u32, utf8ToBytes } from './utils.js';\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\nconst sigma16 = utf8ToBytes('expand 16-byte k');\nconst sigma32 = utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output)\n output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length, k, sigma;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0)\n toClean.pop().fill(0);\n return output;\n };\n}\n//# sourceMappingURL=_arx.js.map","import { wrapCipher, createView, ensureBytes, equalBytes, setBigUint64, } from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(s, k, i, o32) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00;\n o32[oi++] = x01;\n o32[oi++] = x02;\n o32[oi++] = x03;\n o32[oi++] = x12;\n o32[oi++] = x13;\n o32[oi++] = x14;\n o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left)\n h.update(ZEROS16.subarray(left));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, data, AAD) {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n ensureBytes(key, 32);\n ensureBytes(nonce);\n return {\n encrypt: (plaintext, output) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n ensureBytes(output, clength);\n }\n else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext, output) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n ensureBytes(output, plength);\n }\n else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));\n//# sourceMappingURL=chacha.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n, max) {\n // n in [1..max-1]\n if (inRange(n, max))\n return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map();\n function isPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n if (!in0MaskRange(ex))\n throw new Error('x required');\n if (!in0MaskRange(ey))\n throw new Error('y required');\n if (!in0MaskRange(ez))\n throw new Error('z required');\n if (!in0MaskRange(et))\n throw new Error('t required');\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y))\n throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n const { a, d } = CURVE;\n if (this.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n }\n else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215)\n assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else\n assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // Accepts 0 as well\n function assertFieldElement(n) {\n if (typeof n === 'bigint' && _0n <= n && n < P)\n return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU, scalar) {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\nimport { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js';\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\nfunction ed25519_pow_2_252_3(x) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = Field(ED25519_P, undefined, true);\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n};\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\nexport const x25519 = /* @__PURE__ */ (() => montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash, ikm, salt) {\n assertHash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash, prk, info, length = 32) {\n assertHash(hash);\n assertNumber(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","import { pureJsCrypto } from './js.js';\nexport const defaultCrypto = pureJsCrypto;\n//# sourceMappingURL=index.browser.js.map","import { chacha20poly1305 } from '@noble/ciphers/chacha';\nimport { x25519 } from '@noble/curves/ed25519';\nimport { extract, expand } from '@noble/hashes/hkdf';\nimport { sha256 } from '@noble/hashes/sha256';\nexport const pureJsCrypto = {\n hashSHA256(data) {\n return sha256(data.subarray());\n },\n getHKDF(ck, ikm) {\n const prk = extract(sha256, ikm, ck);\n const okmU8Array = expand(sha256, prk, undefined, 96);\n const okm = okmU8Array;\n const k1 = okm.subarray(0, 32);\n const k2 = okm.subarray(32, 64);\n const k3 = okm.subarray(64, 96);\n return [k1, k2, k3];\n },\n generateX25519KeyPair() {\n const secretKey = x25519.utils.randomPrivateKey();\n const publicKey = x25519.getPublicKey(secretKey);\n return {\n publicKey,\n privateKey: secretKey\n };\n },\n generateX25519KeyPairFromSeed(seed) {\n const publicKey = x25519.getPublicKey(seed);\n return {\n publicKey,\n privateKey: seed\n };\n },\n generateX25519SharedKey(privateKey, publicKey) {\n return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray());\n },\n chaCha20Poly1305Encrypt(plaintext, nonce, ad, k) {\n return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray());\n },\n chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst) {\n return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst);\n }\n};\n//# sourceMappingURL=js.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { alloc as uint8ArrayAlloc, allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc';\nexport const uint16BEEncode = (value) => {\n const target = uint8ArrayAllocUnsafe(2);\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false);\n return target;\n};\nuint16BEEncode.bytes = 2;\nexport const uint16BEDecode = (data) => {\n if (data.length < 2)\n throw RangeError('Could not decode int16BE');\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false);\n }\n return data.getUint16(0);\n};\nuint16BEDecode.bytes = 2;\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\nexport function encode0(message) {\n return new Uint8ArrayList(message.ne, message.ciphertext);\n}\nexport function encode1(message) {\n return new Uint8ArrayList(message.ne, message.ns, message.ciphertext);\n}\nexport function encode2(message) {\n return new Uint8ArrayList(message.ns, message.ciphertext);\n}\nexport function decode0(input) {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.');\n }\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: uint8ArrayAlloc(0)\n };\n}\nexport function decode1(input) {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.');\n }\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n };\n}\nexport function decode2(input) {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.');\n }\n return {\n ne: uint8ArrayAlloc(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n };\n}\n//# sourceMappingURL=encoder.js.map","export class UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nexport class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\n//# sourceMappingURL=errors.js.map","/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nexport class CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nexport class AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nexport class UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nexport class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nexport class InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nexport const ERR_TIMEOUT = 'ERR_TIMEOUT';\nexport const ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nexport const ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nexport const ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map","import 'node-forge/lib/util.js';\nimport 'node-forge/lib/jsbn.js';\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nexport function bigIntegerToUintBase64url(num, len) {\n // Call `.abs()` to convert to unsigned\n let buf = Uint8Array.from(num.abs().toByteArray()); // toByteArray converts to big endian\n // toByteArray() gives us back a signed array, which will include a leading 0\n // byte if the most significant bit of the number is 1:\n // https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer\n // Our number will always be positive so we should remove the leading padding.\n buf = buf[0] === 0 ? buf.subarray(1) : buf;\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return uint8ArrayToString(buf, 'base64url');\n}\n// Convert a base64url encoded string to a BigInteger\nexport function base64urlToBigInteger(str) {\n const buf = base64urlToBuffer(str);\n return new forge.jsbn.BigInteger(uint8ArrayToString(buf, 'base16'), 16);\n}\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import 'node-forge/lib/rsa.js';\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js';\nimport { base64urlToBigInteger } from '../util.js';\nfunction convert(key, types) {\n return types.map(t => base64urlToBigInteger(key[t]));\n}\nexport function jwk2priv(key) {\n return forge.pki.setRsaPrivateKey(...convert(key, ['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']));\n}\nexport function jwk2pub(key) {\n return forge.pki.setRsaPublicKey(...convert(key, ['n', 'e']));\n}\n//# sourceMappingURL=jwk2pem.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { jwk2pub, jwk2priv } from './jwk2pem.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\n/*\n\nRSA encryption/decryption for the browser with webcrypto workaround\n\"bloody dark magic. webcrypto's why.\"\n\nExplanation:\n - Convert JWK to nodeForge\n - Convert msg Uint8Array to nodeForge buffer: ByteBuffer is a \"binary-string backed buffer\", so let's make our Uint8Array a binary string\n - Convert resulting nodeForge buffer to Uint8Array: it returns a binary string, turn that into a Uint8Array\n\n*/\nfunction convertKey(key, pub, msg, handle) {\n const fkey = pub ? jwk2pub(key) : jwk2priv(key);\n const fmsg = uint8ArrayToString(msg instanceof Uint8Array ? msg : msg.subarray(), 'ascii');\n const fomsg = handle(fmsg, fkey);\n return uint8ArrayFromString(fomsg, 'ascii');\n}\nexport function encrypt(key, msg) {\n return convertKey(key, true, msg, (msg, key) => key.encrypt(msg));\n}\nexport function decrypt(key, msg) {\n return convertKey(key, false, msg, (msg, key) => key.decrypt(msg));\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { base64urlToBuffer } from '../util.js';\nimport webcrypto from '../webcrypto.js';\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n};\nconst curveTypes = Object.keys(bits);\nconst names = curveTypes.join(' / ');\nexport async function generateEphmeralKeyPair(curve) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'ECDH',\n namedCurve: curve\n }, true, ['deriveBits']);\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub, forcePrivate) => {\n let privateKey;\n if (forcePrivate != null) {\n privateKey = await webcrypto.get().subtle.importKey('jwk', unmarshalPrivateKey(curve, forcePrivate), {\n name: 'ECDH',\n namedCurve: curve\n }, false, ['deriveBits']);\n }\n else {\n privateKey = pair.privateKey;\n }\n const key = await webcrypto.get().subtle.importKey('jwk', unmarshalPublicKey(curve, theirPub), {\n name: 'ECDH',\n namedCurve: curve\n }, false, []);\n const buffer = await webcrypto.get().subtle.deriveBits({\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n }, privateKey, bits[curve]);\n return new Uint8Array(buffer, 0, buffer.byteLength);\n };\n const publicKey = await webcrypto.get().subtle.exportKey('jwk', pair.publicKey);\n const ecdhKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n };\n return ecdhKey;\n}\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n};\n// Marshal converts a jwk encoded ECDH public key into the\n// form specified in section 4.3.6 of ANSI X9.62. (This is the format\n// go-ipfs uses)\nfunction marshalPublicKey(jwk) {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[jwk.crv];\n return uint8ArrayConcat([\n Uint8Array.from([4]), // uncompressed point\n base64urlToBuffer(jwk.x, byteLen),\n base64urlToBuffer(jwk.y, byteLen)\n ], 1 + byteLen * 2);\n}\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey(curve, key) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[curve];\n if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT');\n }\n return {\n kty: 'EC',\n crv: curve,\n x: uint8ArrayToString(key.subarray(1, byteLen + 1), 'base64url'),\n y: uint8ArrayToString(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n };\n}\nconst unmarshalPrivateKey = (curve, key) => ({\n ...unmarshalPublicKey(curve, key.public),\n d: uint8ArrayToString(key.private, 'base64url')\n});\n//# sourceMappingURL=ecdh-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport 'node-forge/lib/sha512.js';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n encrypt(bytes) {\n return crypto.encrypt(this._key, bytes);\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n decrypt(bytes) {\n return crypto.decrypt(this._key, bytes);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected PEM format\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n const buffer = new forge.util.ByteBuffer(this.marshal());\n const asn1 = forge.asn1.fromDer(buffer);\n const privateKey = forge.pki.privateKeyFromAsn1(asn1);\n const options = {\n algorithm: 'aes256',\n count: 10000,\n saltSize: 128 / 8,\n prfAlgorithm: 'sha512'\n };\n return forge.pki.encryptRsaPrivateKey(privateKey, password, options);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import 'node-forge/lib/asn1.js';\nimport 'node-forge/lib/rsa.js';\nimport { CodeError } from '@libp2p/interface';\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js';\n// Convert a PKCS#1 in ASN1 DER format to a JWK key\nexport function pkcs1ToJwk(bytes) {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'));\n const privateKey = forge.pki.privateKeyFromAsn1(asn1);\n // https://tools.ietf.org/html/rfc7518#section-6.3.1\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(privateKey.n),\n e: bigIntegerToUintBase64url(privateKey.e),\n d: bigIntegerToUintBase64url(privateKey.d),\n p: bigIntegerToUintBase64url(privateKey.p),\n q: bigIntegerToUintBase64url(privateKey.q),\n dp: bigIntegerToUintBase64url(privateKey.dP),\n dq: bigIntegerToUintBase64url(privateKey.dQ),\n qi: bigIntegerToUintBase64url(privateKey.qInv),\n alg: 'RS256'\n };\n}\n// Convert a JWK key into PKCS#1 in ASN1 DER format\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const asn1 = forge.pki.privateKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e),\n d: base64urlToBigInteger(jwk.d),\n p: base64urlToBigInteger(jwk.p),\n q: base64urlToBigInteger(jwk.q),\n dP: base64urlToBigInteger(jwk.dp),\n dQ: base64urlToBigInteger(jwk.dq),\n qInv: base64urlToBigInteger(jwk.qi)\n });\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii');\n}\n// Convert a PKCIX in ASN1 DER format to a JWK key\nexport function pkixToJwk(bytes) {\n const asn1 = forge.asn1.fromDer(uint8ArrayToString(bytes, 'ascii'));\n const publicKey = forge.pki.publicKeyFromAsn1(asn1);\n return {\n kty: 'RSA',\n n: bigIntegerToUintBase64url(publicKey.n),\n e: bigIntegerToUintBase64url(publicKey.e)\n };\n}\n// Convert a JWK key to PKCIX in ASN1 DER format\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const asn1 = forge.pki.publicKeyToAsn1({\n n: base64urlToBigInteger(jwk.n),\n e: base64urlToBigInteger(jwk.e)\n });\n return uint8ArrayFromString(forge.asn1.toDer(asn1).getBytes(), 'ascii');\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n if (!fe(x))\n throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r))\n return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport 'node-forge/lib/asn1.js';\nimport 'node-forge/lib/pbe.js';\nimport { CodeError } from '@libp2p/interface';\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n // Only rsa supports pem right now\n const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password);\n if (key === null) {\n throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM');\n }\n let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key));\n der = uint8ArrayFromString(der.getBytes(), 'ascii');\n return supportedKeys.rsa.unmarshalRsaPrivateKey(der);\n}\n//# sourceMappingURL=index.js.map","export const peerIdSymbol = Symbol.for('@libp2p/peer-id');\nexport function isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { CodeError } from '@libp2p/interface';\nimport { peerIdSymbol } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { bases } from 'multiformats/basics';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nexport function createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nexport function peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nexport function peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nexport function peerIdFromBytes(buf) {\n try {\n const multihash = Digest.decode(buf);\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nexport function peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var NoiseExtensions;\n(function (NoiseExtensions) {\n let _codec;\n NoiseExtensions.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n webtransportCerthashes: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.webtransportCerthashes.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseExtensions.encode = (obj) => {\n return encodeMessage(obj, NoiseExtensions.codec());\n };\n NoiseExtensions.decode = (buf) => {\n return decodeMessage(buf, NoiseExtensions.codec());\n };\n})(NoiseExtensions || (NoiseExtensions = {}));\nexport var NoiseHandshakePayload;\n(function (NoiseHandshakePayload) {\n let _codec;\n NoiseHandshakePayload.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.identityKey);\n }\n if ((obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.identitySig);\n }\n if (obj.extensions != null) {\n w.uint32(34);\n NoiseExtensions.codec().encode(obj.extensions, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n identityKey: uint8ArrayAlloc(0),\n identitySig: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.identityKey = reader.bytes();\n break;\n }\n case 2: {\n obj.identitySig = reader.bytes();\n break;\n }\n case 4: {\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseHandshakePayload.encode = (obj) => {\n return encodeMessage(obj, NoiseHandshakePayload.codec());\n };\n NoiseHandshakePayload.decode = (buf) => {\n return decodeMessage(buf, NoiseHandshakePayload.codec());\n };\n})(NoiseHandshakePayload || (NoiseHandshakePayload = {}));\n//# sourceMappingURL=payload.js.map","import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { isUint8ArrayList } from 'uint8arraylist';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { NoiseHandshakePayload } from './proto/payload.js';\nexport async function getPayload(localPeer, staticPublicKey, extensions) {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey));\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId');\n }\n return createHandshakePayload(localPeer.publicKey, signedPayload, extensions);\n}\nexport function createHandshakePayload(libp2pPublicKey, signedPayload, extensions) {\n return NoiseHandshakePayload.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n extensions: extensions ?? { webtransportCerthashes: [] }\n }).subarray();\n}\nexport async function signPayload(peerId, payload) {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId');\n }\n const privateKey = await unmarshalPrivateKey(peerId.privateKey);\n return privateKey.sign(payload);\n}\nexport async function getPeerIdFromPayload(payload) {\n return peerIdFromKeys(payload.identityKey);\n}\nexport function decodePayload(payload) {\n return NoiseHandshakePayload.decode(payload);\n}\nexport function getHandshakePayload(publicKey) {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:');\n if (publicKey instanceof Uint8Array) {\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length);\n }\n publicKey.prepend(prefix);\n return publicKey;\n}\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload(noiseStaticKey, payload, remotePeer) {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey);\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(`Payload identity key ${payloadPeerId.toString()} does not match expected remote peer ${remotePeer.toString()}`);\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey);\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId');\n }\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message');\n }\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey);\n const valid = await publicKey.verify(generatedPayload, payload.identitySig);\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\");\n }\n return payloadPeerId;\n}\nexport function isValidPublicKey(pk) {\n if (!(pk instanceof Uint8Array) && !(isUint8ArrayList(pk))) {\n return false;\n }\n if (pk.byteLength !== 32) {\n return false;\n }\n return true;\n}\n//# sourceMappingURL=utils.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport const MIN_NONCE = 0;\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff;\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed';\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n n;\n bytes;\n view;\n constructor(n = MIN_NONCE) {\n this.n = n;\n this.bytes = uint8ArrayAlloc(12);\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n this.view.setUint32(4, n, true);\n }\n increment() {\n this.n++;\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true);\n }\n getBytes() {\n return this.bytes;\n }\n getUint64() {\n return this.n;\n }\n assertValue() {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE);\n }\n }\n}\n//# sourceMappingURL=nonce.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { Nonce } from '../nonce.js';\nexport class AbstractHandshake {\n crypto;\n log;\n constructor(components, crypto) {\n this.log = components.logger.forComponent('libp2p:noise:abstract-handshake');\n this.crypto = crypto;\n }\n encryptWithAd(cs, ad, plaintext) {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext);\n cs.n.increment();\n return e;\n }\n decryptWithAd(cs, ad, ciphertext, dst) {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext, dst);\n if (valid)\n cs.n.increment();\n return { plaintext, valid };\n }\n // Cipher state related\n hasKey(cs) {\n return !this.isEmptyKey(cs.k);\n }\n createEmptyKey() {\n return uint8ArrayAlloc(32);\n }\n isEmptyKey(k) {\n const emptyKey = this.createEmptyKey();\n return uint8ArrayEquals(emptyKey, k);\n }\n encrypt(k, n, ad, plaintext) {\n n.assertValue();\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k);\n }\n encryptAndHash(ss, plaintext) {\n let ciphertext;\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext);\n }\n else {\n ciphertext = plaintext;\n }\n this.mixHash(ss, ciphertext);\n return ciphertext;\n }\n decrypt(k, n, ad, ciphertext, dst) {\n n.assertValue();\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k, dst);\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n };\n }\n else {\n return {\n plaintext: uint8ArrayAlloc(0),\n valid: false\n };\n }\n }\n decryptAndHash(ss, ciphertext) {\n let plaintext;\n let valid = true;\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext));\n }\n else {\n plaintext = ciphertext;\n }\n this.mixHash(ss, ciphertext);\n return { plaintext, valid };\n }\n dh(privateKey, publicKey) {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey);\n if (derivedU8.length === 32) {\n return derivedU8;\n }\n return derivedU8.subarray(0, 32);\n }\n catch (e) {\n const err = e;\n this.log.error('error deriving shared key', err);\n return uint8ArrayAlloc(32);\n }\n }\n mixHash(ss, data) {\n ss.h = this.getHash(ss.h, data);\n }\n getHash(a, b) {\n const u = this.crypto.hashSHA256(new Uint8ArrayList(a, b));\n return u;\n }\n mixKey(ss, ikm) {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm);\n ss.cs = this.initializeKey(tempK);\n ss.ck = ck;\n }\n initializeKey(k) {\n return { k, n: new Nonce() };\n }\n // Symmetric state related\n initializeSymmetric(protocolName) {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8');\n const h = this.hashProtocolName(protocolNameBytes);\n const ck = h;\n const key = this.createEmptyKey();\n const cs = this.initializeKey(key);\n return { cs, ck, h };\n }\n hashProtocolName(protocolName) {\n if (protocolName.length <= 32) {\n const h = uint8ArrayAlloc(32);\n h.set(protocolName);\n return h;\n }\n else {\n return this.getHash(protocolName, uint8ArrayAlloc(0));\n }\n }\n split(ss) {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, uint8ArrayAlloc(0));\n const cs1 = this.initializeKey(tempk1);\n const cs2 = this.initializeKey(tempk2);\n return { cs1, cs2 };\n }\n writeMessageRegular(cs, payload) {\n const ciphertext = this.encryptWithAd(cs, uint8ArrayAlloc(0), payload);\n const ne = this.createEmptyKey();\n const ns = uint8ArrayAlloc(0);\n return { ne, ns, ciphertext };\n }\n readMessageRegular(cs, message) {\n return this.decryptWithAd(cs, uint8ArrayAlloc(0), message.ciphertext);\n }\n}\n//# sourceMappingURL=abstract-handshake.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { isValidPublicKey } from '../utils.js';\nimport { AbstractHandshake } from './abstract-handshake.js';\nexport class XX extends AbstractHandshake {\n initializeInitiator(prologue, s, rs, psk) {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256';\n const ss = this.initializeSymmetric(name);\n this.mixHash(ss, prologue);\n const re = uint8ArrayAlloc(32);\n return { ss, s, rs, psk, re };\n }\n initializeResponder(prologue, s, rs, psk) {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256';\n const ss = this.initializeSymmetric(name);\n this.mixHash(ss, prologue);\n const re = uint8ArrayAlloc(32);\n return { ss, s, rs, psk, re };\n }\n writeMessageA(hs, payload, e) {\n const ns = uint8ArrayAlloc(0);\n if (e !== undefined) {\n hs.e = e;\n }\n else {\n hs.e = this.crypto.generateX25519KeyPair();\n }\n const ne = hs.e.publicKey;\n this.mixHash(hs.ss, ne);\n const ciphertext = this.encryptAndHash(hs.ss, payload);\n return { ne, ns, ciphertext };\n }\n writeMessageB(hs, payload) {\n hs.e = this.crypto.generateX25519KeyPair();\n const ne = hs.e.publicKey;\n this.mixHash(hs.ss, ne);\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re));\n const spk = hs.s.publicKey;\n const ns = this.encryptAndHash(hs.ss, spk);\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re));\n const ciphertext = this.encryptAndHash(hs.ss, payload);\n return { ne, ns, ciphertext };\n }\n writeMessageC(hs, payload) {\n const spk = hs.s.publicKey;\n const ns = this.encryptAndHash(hs.ss, spk);\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re));\n const ciphertext = this.encryptAndHash(hs.ss, payload);\n const ne = this.createEmptyKey();\n const messageBuffer = { ne, ns, ciphertext };\n const { cs1, cs2 } = this.split(hs.ss);\n return { h: hs.ss.h, messageBuffer, cs1, cs2 };\n }\n readMessageA(hs, message) {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne;\n }\n this.mixHash(hs.ss, hs.re);\n return this.decryptAndHash(hs.ss, message.ciphertext);\n }\n readMessageB(hs, message) {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne;\n }\n this.mixHash(hs.ss, hs.re);\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.');\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re));\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns);\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns;\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs));\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext);\n return { plaintext, valid: (valid1 && valid2) };\n }\n readMessageC(hs, message) {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns);\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns;\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.');\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs));\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext);\n const { cs1, cs2 } = this.split(hs.ss);\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 };\n }\n initSession(initiator, prologue, s) {\n const psk = this.createEmptyKey();\n const rs = uint8ArrayAlloc(32); // no static key yet\n let hs;\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk);\n }\n else {\n hs = this.initializeResponder(prologue, s, rs, psk);\n }\n return {\n hs,\n i: initiator,\n mc: 0\n };\n }\n sendMessage(session, message, ephemeral) {\n let messageBuffer;\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral);\n }\n else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message);\n }\n else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message);\n messageBuffer = resultingBuffer;\n session.h = h;\n session.cs1 = cs1;\n session.cs2 = cs2;\n }\n else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined');\n }\n messageBuffer = this.writeMessageRegular(session.cs1, message);\n }\n else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined');\n }\n messageBuffer = this.writeMessageRegular(session.cs2, message);\n }\n }\n else {\n throw new Error('Session invalid.');\n }\n session.mc++;\n return messageBuffer;\n }\n recvMessage(session, message) {\n let plaintext = uint8ArrayAlloc(0);\n let valid = false;\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message));\n }\n else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message));\n }\n else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message);\n plaintext = resultingPlaintext;\n valid = resultingValid;\n session.h = h;\n session.cs1 = cs1;\n session.cs2 = cs2;\n }\n session.mc++;\n return { plaintext, valid };\n }\n}\n//# sourceMappingURL=xx.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { DUMP_SESSION_KEYS } from './constants.js';\nexport function logLocalStaticKeys(s, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`);\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`);\n}\nexport function logLocalEphemeralKeys(e, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`);\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local ephemeral keys.');\n }\n}\nexport function logRemoteStaticKey(rs, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`);\n}\nexport function logRemoteEphemeralKey(re, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`);\n}\nexport function logCipherState(session, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`);\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`);\n }\n else {\n keyLogger('Missing cipher state.');\n }\n}\n//# sourceMappingURL=logger.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js';\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from './errors.js';\nimport { XX } from './handshakes/xx.js';\nimport { logLocalStaticKeys, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey, logCipherState } from './logger.js';\nimport { decodePayload, getPeerIdFromPayload, verifySignedPayload } from './utils.js';\nexport class XXHandshake {\n isInitiator;\n session;\n remotePeer;\n remoteExtensions = { webtransportCerthashes: [] };\n payload;\n connection;\n xx;\n staticKeypair;\n prologue;\n log;\n constructor(components, isInitiator, payload, prologue, crypto, staticKeypair, connection, remotePeer, handshake) {\n this.log = components.logger.forComponent('libp2p:noise:xxhandshake');\n this.isInitiator = isInitiator;\n this.payload = payload;\n this.prologue = prologue;\n this.staticKeypair = staticKeypair;\n this.connection = connection;\n if (remotePeer) {\n this.remotePeer = remotePeer;\n }\n this.xx = handshake ?? new XX(components, crypto);\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair);\n }\n // stage 0\n async propose() {\n logLocalStaticKeys(this.session.hs.s, this.log);\n if (this.isInitiator) {\n this.log.trace('Stage 0 - Initiator starting to send first message.');\n const messageBuffer = this.xx.sendMessage(this.session, uint8ArrayAlloc(0));\n await this.connection.write(encode0(messageBuffer));\n this.log.trace('Stage 0 - Initiator finished sending first message.');\n logLocalEphemeralKeys(this.session.hs.e, this.log);\n }\n else {\n this.log.trace('Stage 0 - Responder waiting to receive first message...');\n const receivedMessageBuffer = decode0((await this.connection.read()).subarray());\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer);\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail');\n }\n this.log.trace('Stage 0 - Responder received first message.');\n logRemoteEphemeralKey(this.session.hs.re, this.log);\n }\n }\n // stage 1\n async exchange() {\n if (this.isInitiator) {\n this.log.trace('Stage 1 - Initiator waiting to receive first message from responder...');\n const receivedMessageBuffer = decode1((await this.connection.read()).subarray());\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer);\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail');\n }\n this.log.trace('Stage 1 - Initiator received the message.');\n logRemoteEphemeralKey(this.session.hs.re, this.log);\n logRemoteStaticKey(this.session.hs.rs, this.log);\n this.log.trace(\"Initiator going to check remote's signature...\");\n try {\n const decodedPayload = decodePayload(plaintext);\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload);\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer);\n this.setRemoteNoiseExtension(decodedPayload.extensions);\n }\n catch (e) {\n const err = e;\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`);\n }\n this.log.trace('All good with the signature!');\n }\n else {\n this.log.trace('Stage 1 - Responder sending out first message with signed payload and static key.');\n const messageBuffer = this.xx.sendMessage(this.session, this.payload);\n await this.connection.write(encode1(messageBuffer));\n this.log.trace('Stage 1 - Responder sent the second handshake message with signed payload.');\n logLocalEphemeralKeys(this.session.hs.e, this.log);\n }\n }\n // stage 2\n async finish() {\n if (this.isInitiator) {\n this.log.trace('Stage 2 - Initiator sending third handshake message.');\n const messageBuffer = this.xx.sendMessage(this.session, this.payload);\n await this.connection.write(encode2(messageBuffer));\n this.log.trace('Stage 2 - Initiator sent message with signed payload.');\n }\n else {\n this.log.trace('Stage 2 - Responder waiting for third handshake message...');\n const receivedMessageBuffer = decode2((await this.connection.read()).subarray());\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer);\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail');\n }\n this.log.trace('Stage 2 - Responder received the message, finished handshake.');\n try {\n const decodedPayload = decodePayload(plaintext);\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload);\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer);\n this.setRemoteNoiseExtension(decodedPayload.extensions);\n }\n catch (e) {\n const err = e;\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`);\n }\n }\n logCipherState(this.session, this.log);\n }\n encrypt(plaintext, session) {\n const cs = this.getCS(session);\n return this.xx.encryptWithAd(cs, uint8ArrayAlloc(0), plaintext);\n }\n decrypt(ciphertext, session, dst) {\n const cs = this.getCS(session, false);\n return this.xx.decryptWithAd(cs, uint8ArrayAlloc(0), ciphertext, dst);\n }\n getRemoteStaticKey() {\n return this.session.hs.rs;\n }\n getCS(session, encryption = true) {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.');\n }\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2;\n }\n else {\n return encryption ? session.cs2 : session.cs1;\n }\n }\n setRemoteNoiseExtension(e) {\n if (e) {\n this.remoteExtensions = e;\n }\n }\n}\n//# sourceMappingURL=handshake-xx.js.map","import { decode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { duplexPair } from 'it-pair/duplex';\nimport { pipe } from 'it-pipe';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js';\nimport { defaultCrypto } from './crypto/index.js';\nimport { decryptStream, encryptStream } from './crypto/streaming.js';\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js';\nimport { XXHandshake } from './handshake-xx.js';\nimport { registerMetrics } from './metrics.js';\nimport { getPayload } from './utils.js';\nexport class Noise {\n protocol = '/noise';\n crypto;\n prologue;\n staticKeys;\n extensions;\n metrics;\n components;\n constructor(components, init = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes } = init;\n const { metrics } = components;\n this.components = components;\n this.crypto = crypto ?? defaultCrypto;\n this.extensions = extensions;\n this.metrics = metrics ? registerMetrics(metrics) : undefined;\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey);\n }\n else {\n this.staticKeys = this.crypto.generateX25519KeyPair();\n }\n this.prologue = prologueBytes ?? uint8ArrayAlloc(0);\n }\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {Stream} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise>}\n */\n async secureOutbound(localPeer, connection, remotePeer) {\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n });\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n return {\n conn: connection,\n remoteExtensions: handshake.remoteExtensions,\n remotePeer: handshake.remotePeer\n };\n }\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {Stream} connection - streaming iterable duplex that will be encrypted.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise>}\n */\n async secureInbound(localPeer, connection, remotePeer) {\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n });\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n return {\n conn: connection,\n remotePeer: handshake.remotePeer,\n remoteExtensions: handshake.remoteExtensions\n };\n }\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n async performHandshake(params) {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.extensions);\n // run XX handshake\n return this.performXXHandshake(params, payload);\n }\n async performXXHandshake(params, payload) {\n const { isInitiator, remotePeer, connection } = params;\n const handshake = new XXHandshake(this.components, isInitiator, payload, this.prologue, this.crypto, this.staticKeys, connection, remotePeer);\n try {\n await handshake.propose();\n await handshake.exchange();\n await handshake.finish();\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`;\n throw e;\n }\n }\n return handshake;\n }\n async createSecureConnection(connection, handshake) {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair();\n const network = connection.unwrap();\n await pipe(secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n (source) => decode(source, { lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n );\n return user;\n }\n}\n//# sourceMappingURL=noise.js.map","export function registerMetrics(metrics) {\n return {\n xxHandshakeSuccesses: metrics.registerCounter('libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n xxHandshakeErrors: metrics.registerCounter('libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n encryptedPackets: metrics.registerCounter('libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n decryptedPackets: metrics.registerCounter('libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n decryptErrors: metrics.registerCounter('libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n };\n}\n//# sourceMappingURL=metrics.js.map","import { pair } from './index.js';\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair() {\n const a = pair();\n const b = pair();\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ];\n}\n//# sourceMappingURL=duplex.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js';\nimport { uint16BEEncode } from '../encoder.js';\nconst CHACHA_TAG_LENGTH = 16;\n// Returns generator that encrypts payload from the user\nexport function encryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG;\n if (end > chunk.length) {\n end = chunk.length;\n }\n let data;\n if (chunk instanceof Uint8Array) {\n data = handshake.encrypt(chunk.subarray(i, end), handshake.session);\n }\n else {\n data = handshake.encrypt(chunk.sublist(i, end), handshake.session);\n }\n metrics?.encryptedPackets.increment();\n yield new Uint8ArrayList(uint16BEEncode(data.byteLength), data);\n }\n }\n };\n}\n// Decrypt received payload to the user\nexport function decryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES;\n if (end > chunk.length) {\n end = chunk.length;\n }\n if (end - CHACHA_TAG_LENGTH < i) {\n throw new Error('Invalid chunk');\n }\n const encrypted = chunk.sublist(i, end);\n // memory allocation is not cheap so reuse the encrypted Uint8Array\n // see https://github.com/ChainSafe/js-libp2p-noise/pull/242#issue-1422126164\n // this is ok because chacha20 reads bytes one by one and don't reread after that\n // it's also tested in https://github.com/ChainSafe/as-chacha20poly1305/pull/1/files#diff-25252846b58979dcaf4e41d47b3eadd7e4f335e7fb98da6c049b1f9cd011f381R48\n const dst = chunk.subarray(i, end - CHACHA_TAG_LENGTH);\n const { plaintext: decrypted, valid } = handshake.decrypt(encrypted, handshake.session, dst);\n if (!valid) {\n metrics?.decryptErrors.increment();\n throw new Error('Failed to validate decrypted chunk');\n }\n metrics?.decryptedPackets.increment();\n yield decrypted;\n }\n }\n };\n}\n//# sourceMappingURL=streaming.js.map","import { Noise } from './noise.js';\nexport { pureJsCrypto } from './crypto/js.js';\nexport function noise(init = {}) {\n return (components) => new Noise(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');\n//# sourceMappingURL=index.js.map","import { Parser } from \"./parser.js\";\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\nconst parser = new Parser();\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input) {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPAddr());\n}\n//# sourceMappingURL=parse.js.map","/* eslint-disable @typescript-eslint/no-unsafe-return */\nexport class Parser {\n index = 0;\n input = \"\";\n new(input) {\n this.index = 0;\n this.input = input;\n return this;\n }\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically(fn) {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith(fn) {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n /** Peek the next character from the input */\n peekChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n /** Read the next character from the input */\n readChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target) {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator(sep, index, inner) {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n if (digitCount === 0) {\n return undefined;\n }\n else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n }\n else {\n return result;\n }\n });\n }\n /** Read an IPv4 address. */\n readIPv4Addr() {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n return out;\n });\n }\n /** Read an IPv6 Address. */\n readIPv6Addr() {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups) => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n return [ix + 4, true];\n }\n }\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n if (headSize === 16) {\n return head;\n }\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n return head;\n });\n }\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr() {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n//# sourceMappingURL=parser.js.map","import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n/** Check if `input` is IPv4. */\nexport function isIPv4(input) {\n return Boolean(parseIPv4(input));\n}\n/** Check if `input` is IPv6. */\nexport function isIPv6(input) {\n return Boolean(parseIPv6(input));\n}\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input) {\n return Boolean(parseIP(input));\n}\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input) {\n if (isIPv4(input)) {\n return 4;\n }\n else if (isIPv6(input)) {\n return 6;\n }\n else {\n return undefined;\n }\n}\n//# sourceMappingURL=is-ip.js.map","import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\nexport const maxIPv6Octet = parseInt(\"0xFFFF\", 16);\nexport const ipv4Prefix = new Uint8Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255,\n]);\nexport function maskIp(ip, mask) {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)) {\n ip = ip.slice(12);\n }\n const n = ip.length;\n if (n != mask.length) {\n throw new Error(\"Failed to mask ip\");\n }\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n out[i] = ip[i] & mask[i];\n }\n return out;\n}\nexport function containsIp(net, ip) {\n if (typeof ip === \"string\") {\n ip = parseIP(ip);\n }\n if (ip == null)\n throw new Error(\"Invalid ip\");\n if (ip.length !== net.network.length) {\n return false;\n }\n for (let i = 0; i < ip.length; i++) {\n if ((net.network[i] & net.mask[i]) !== (ip[i] & net.mask[i])) {\n return false;\n }\n }\n return true;\n}\nexport function iPv4FromIPv6(ip) {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\nexport function isIPv4mappedIPv6(ip) {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n//# sourceMappingURL=ip.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nexport { isIP } from '@chainsafe/is-ip';\nexport const isV4 = isIPv4;\nexport const isV6 = isIPv6;\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip) {\n let offset = 0;\n ip = ip.toString().trim();\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4);\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff;\n });\n return bytes;\n }\n if (isV6(ip)) {\n const sections = ip.split(':', 8);\n let i;\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i]);\n let v4Buffer;\n if (isv4) {\n v4Buffer = toBytes(sections[i]);\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16');\n }\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'));\n }\n }\n if (sections[0] === '') {\n while (sections.length < 8)\n sections.unshift('0');\n }\n else if (sections[sections.length - 1] === '') {\n while (sections.length < 8)\n sections.push('0');\n }\n else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++)\n ;\n const argv = [i, 1];\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0');\n }\n sections.splice.apply(sections, argv);\n }\n const bytes = new Uint8Array(offset + 16);\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16);\n bytes[offset++] = (word >> 8) & 0xff;\n bytes[offset++] = word & 0xff;\n }\n return bytes;\n }\n throw new Error('invalid ip address');\n};\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf, offset = 0, length) {\n offset = ~~offset;\n length = length ?? (buf.length - offset);\n const view = new DataView(buf.buffer);\n if (length === 4) {\n const result = [];\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i]);\n }\n return result.join('.');\n }\n if (length === 16) {\n const result = [];\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16));\n }\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::');\n }\n return '';\n};\n//# sourceMappingURL=ip.js.map","const V = -1;\nexport const names = {};\nexport const codes = {};\nexport const table = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [481, V, 'http-path'],\n [777, V, 'memory']\n];\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row);\n codes[proto.code] = proto;\n names[proto.name] = proto;\n});\nexport function createProtocol(code, size, name, resolvable, path) {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n };\n}\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol(proto) {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto];\n }\n throw new Error(`no protocol with code: ${proto}`);\n }\n else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto];\n }\n throw new Error(`no protocol with name: ${proto}`);\n }\n throw new Error(`invalid protocol id type: ${typeof proto}`);\n}\n//# sourceMappingURL=protocols-table.js.map","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\nimport { IpNet } from '@chainsafe/netmask';\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { bases } from 'multiformats/basics';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport * as ip from './ip.js';\nimport { getProtocol } from './protocols-table.js';\nconst ip4Protocol = getProtocol('ip4');\nconst ip6Protocol = getProtocol('ip6');\nconst ipcidrProtocol = getProtocol('ipcidr');\nexport function convert(proto, a) {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a);\n }\n else {\n return convertToBytes(proto, a);\n }\n}\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString(proto, buf) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf);\n case 42: // ipv6zone\n return bytes2str(buf);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString();\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf);\n case 421: // ipfs\n return bytes2mh(buf);\n case 444: // onion\n return bytes2onion(buf);\n case 445: // onion3\n return bytes2onion(buf);\n case 466: // certhash\n return bytes2mb(buf);\n case 481: // http-path\n return globalThis.encodeURIComponent(bytes2str(buf));\n default:\n return uint8ArrayToString(buf, 'base16'); // no clue. convert to hex\n }\n}\nexport function convertToBytes(proto, str) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str);\n case 41: // ipv6\n return ip2bytes(str);\n case 42: // ipv6zone\n return str2bytes(str);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10));\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str);\n case 421: // ipfs\n return mh2bytes(str);\n case 444: // onion\n return onion2bytes(str);\n case 445: // onion3\n return onion32bytes(str);\n case 466: // certhash\n return mb2bytes(str);\n case 481: // http-path\n return str2bytes(globalThis.decodeURIComponent(str));\n default:\n return uint8ArrayFromString(str, 'base16'); // no clue. convert from hex\n }\n}\nexport function convertToIpNet(multiaddr) {\n let mask;\n let addr;\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value;\n }\n if (code === ipcidrProtocol.code) {\n mask = value;\n }\n });\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr');\n }\n return new IpNet(addr, mask);\n}\nconst decoders = Object.values(bases).map((c) => c.decoder);\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1]);\n decoders.slice(2).forEach((d) => (acc = acc.or(d)));\n return acc;\n})();\nfunction ip2bytes(ipString) {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ip.toBytes(ipString);\n}\nfunction bytes2ip(ipBuff) {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length);\n if (ipString == null) {\n throw new Error('ipBuff is required');\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ipString;\n}\nfunction port2bytes(port) {\n const buf = new ArrayBuffer(2);\n const view = new DataView(buf);\n view.setUint16(0, port);\n return new Uint8Array(buf);\n}\nfunction bytes2port(buf) {\n const view = new DataView(buf.buffer);\n return view.getUint16(buf.byteOffset);\n}\nfunction str2bytes(str) {\n const buf = uint8ArrayFromString(str);\n const size = Uint8Array.from(varint.encode(buf.length));\n return uint8ArrayConcat([size, buf], size.length + buf.length);\n}\nfunction bytes2str(buf) {\n const size = varint.decode(buf);\n buf = buf.slice(varint.encodingLength(size));\n if (buf.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(buf);\n}\nfunction mh2bytes(hash) {\n let mh;\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes;\n }\n else {\n mh = CID.parse(hash).multihash.bytes;\n }\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length));\n return uint8ArrayConcat([size, mh], size.length + mh.length);\n}\nfunction mb2bytes(mbstr) {\n const mb = anybaseDecoder.decode(mbstr);\n const size = Uint8Array.from(varint.encode(mb.length));\n return uint8ArrayConcat([size, mb], size.length + mb.length);\n}\nfunction bytes2mb(buf) {\n const size = varint.decode(buf);\n const hash = buf.slice(varint.encodingLength(size));\n if (hash.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return 'u' + uint8ArrayToString(hash, 'base64url');\n}\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh(buf) {\n const size = varint.decode(buf);\n const address = buf.slice(varint.encodingLength(size));\n if (address.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(address, 'base58btc');\n}\nfunction onion2bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0]);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction onion32bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction bytes2onion(buf) {\n const addrBytes = buf.slice(0, buf.length - 2);\n const portBytes = buf.slice(buf.length - 2);\n const addr = uint8ArrayToString(addrBytes, 'base32');\n const port = bytes2port(portBytes);\n return `${addr}:${port}`;\n}\n//# sourceMappingURL=convert.js.map","import * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { convertToBytes, convertToString } from './convert.js';\nimport { getProtocol } from './protocols-table.js';\nexport function stringToMultiaddrParts(str) {\n str = cleanPath(str);\n const tuples = [];\n const stringTuples = [];\n let path = null;\n const parts = str.split('/').slice(1);\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n };\n }\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p];\n const proto = getProtocol(part);\n if (proto.size === 0) {\n tuples.push([proto.code]);\n stringTuples.push([proto.code]);\n // eslint-disable-next-line no-continue\n continue;\n }\n p++; // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str);\n }\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'));\n tuples.push([proto.code, convertToBytes(proto.code, path)]);\n stringTuples.push([proto.code, path]);\n break;\n }\n const bytes = convertToBytes(proto.code, parts[p]);\n tuples.push([proto.code, bytes]);\n stringTuples.push([proto.code, convertToString(proto.code, bytes)]);\n }\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n };\n}\nexport function bytesToMultiaddrParts(bytes) {\n const tuples = [];\n const stringTuples = [];\n let path = null;\n let i = 0;\n while (i < bytes.length) {\n const code = varint.decode(bytes, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, bytes.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n stringTuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = bytes.slice(i + n, i + n + size);\n i += (size + n);\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n const stringAddr = convertToString(code, addr);\n stringTuples.push([code, stringAddr]);\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr;\n break;\n }\n }\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n };\n}\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString(tuples) {\n const parts = [];\n tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n parts.push(proto.name);\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1]);\n }\n return null;\n });\n return cleanPath(parts.join('/'));\n}\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes(tuples) {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n let buf = Uint8Array.from(varint.encode(proto.code));\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]); // add address buffer\n }\n return buf;\n }));\n}\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr(p, addr) {\n if (p.size > 0) {\n return p.size / 8;\n }\n else if (p.size === 0) {\n return 0;\n }\n else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));\n return size + varint.encodingLength(size);\n }\n}\nexport function bytesToTuples(buf) {\n const tuples = [];\n let i = 0;\n while (i < buf.length) {\n const code = varint.decode(buf, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, buf.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = buf.slice(i + n, i + n + size);\n i += (size + n);\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n }\n return tuples;\n}\nexport function cleanPath(str) {\n return '/' + str.trim().split('/').filter((a) => a).join('/');\n}\nexport function ParseError(str) {\n return new Error('Error parsing address: ' + str);\n}\n//# sourceMappingURL=codec.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\nimport { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, tuplesToBytes } from './codec.js';\nimport { getProtocol, names } from './protocols-table.js';\nimport { isMultiaddr, multiaddr, resolvers } from './index.js';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n];\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr {\n bytes;\n #string;\n #tuples;\n #stringTuples;\n #path;\n [symbol] = true;\n constructor(addr) {\n // default\n if (addr == null) {\n addr = '';\n }\n let parts;\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr);\n }\n else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`);\n }\n parts = stringToMultiaddrParts(addr);\n }\n else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes);\n }\n else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr');\n }\n this.bytes = parts.bytes;\n this.#string = parts.string;\n this.#tuples = parts.tuples;\n this.#stringTuples = parts.stringTuples;\n this.#path = parts.path;\n }\n toString() {\n return this.#string;\n }\n toJSON() {\n return this.toString();\n }\n toOptions() {\n let family;\n let transport;\n let host;\n let port;\n let zone = '';\n const tcp = getProtocol('tcp');\n const udp = getProtocol('udp');\n const ip4 = getProtocol('ip4');\n const ip6 = getProtocol('ip6');\n const dns6 = getProtocol('dns6');\n const ip6zone = getProtocol('ip6zone');\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`;\n }\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name;\n port = 443;\n host = `${value ?? ''}${zone}`;\n family = code === dns6.code ? 6 : 4;\n }\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name;\n port = parseInt(value ?? '');\n }\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name;\n host = `${value ?? ''}${zone}`;\n family = code === ip6.code ? 6 : 4;\n }\n }\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".');\n }\n const opts = {\n family,\n host,\n transport,\n port\n };\n return opts;\n }\n protos() {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)));\n }\n protoCodes() {\n return this.#tuples.map(([code]) => code);\n }\n protoNames() {\n return this.#tuples.map(([code]) => getProtocol(code).name);\n }\n tuples() {\n return this.#tuples;\n }\n stringTuples() {\n return this.#stringTuples;\n }\n encapsulate(addr) {\n addr = new Multiaddr(addr);\n return new Multiaddr(this.toString() + addr.toString());\n }\n decapsulate(addr) {\n const addrString = addr.toString();\n const s = this.toString();\n const i = s.lastIndexOf(addrString);\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);\n }\n return new Multiaddr(s.slice(0, i));\n }\n decapsulateCode(code) {\n const tuples = this.tuples();\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)));\n }\n }\n return this;\n }\n getPeerId() {\n try {\n let tuples = [];\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name]);\n }\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = [];\n }\n });\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop();\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1];\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc');\n }\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc');\n }\n return null;\n }\n catch (e) {\n return null;\n }\n }\n getPath() {\n return this.#path;\n }\n equals(addr) {\n return uint8ArrayEquals(this.bytes, addr.bytes);\n }\n async resolve(options) {\n const resolvableProto = this.protos().find((p) => p.resolvable);\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this];\n }\n const resolver = resolvers.get(resolvableProto.name);\n if (resolver == null) {\n throw new CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');\n }\n const result = await resolver(this, options);\n return result.map(str => multiaddr(str));\n }\n nodeAddress() {\n const options = this.toOptions();\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`);\n }\n return {\n family: options.family,\n address: options.host,\n port: options.port\n };\n }\n isThinWaistAddress(addr) {\n const protos = (addr ?? this).protos();\n if (protos.length !== 2) {\n return false;\n }\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false;\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false;\n }\n return true;\n }\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect]() {\n return `Multiaddr(${this.#string})`;\n }\n}\n//# sourceMappingURL=multiaddr.js.map","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js';\nimport { getProtocol } from './protocols-table.js';\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map();\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js';\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress(addr, transport) {\n if (addr == null) {\n throw new Error('requires node address object');\n }\n if (transport == null) {\n throw new Error('requires transport protocol');\n }\n let ip;\n let host = addr.address;\n switch (addr.family) {\n case 4:\n ip = 'ip4';\n break;\n case 6:\n ip = 'ip6';\n if (host.includes('%')) {\n const parts = host.split('%');\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr');\n }\n host = parts[0];\n const zone = parts[1];\n ip = `/ip6zone/${zone}/ip6`;\n }\n break;\n default:\n throw Error('Invalid addr family, should be 4 or 6.');\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'));\n}\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName(addr) {\n if (!isMultiaddr(addr)) {\n return false;\n }\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable);\n}\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr(value) {\n return Boolean(value?.[symbol]);\n}\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr(addr) {\n return new MultiaddrClass(addr);\n}\nexport { getProtocol as protocols };\n//# sourceMappingURL=index.js.map","import { multiaddr } from '@multiformats/multiaddr';\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4');\nexport const DNS6 = base('dns6');\nexport const DNSADDR = base('dnsaddr');\nexport const DNS = or(base('dns'), DNSADDR, DNS4, DNS6);\nexport const IP = or(base('ip4'), base('ip6'));\nexport const TCP = or(and(IP, base('tcp')), and(DNS, base('tcp')));\nexport const UDP = and(IP, base('udp'));\nexport const UTP = and(UDP, base('utp'));\nexport const QUIC = and(UDP, base('quic'));\nexport const QUICV1 = and(UDP, base('quic-v1'));\nconst _WebSockets = or(and(TCP, base('ws')), and(DNS, base('ws')));\nexport const WebSockets = or(and(_WebSockets, base('p2p')), _WebSockets);\nconst _WebSocketsSecure = or(and(TCP, base('wss')), and(DNS, base('wss')), and(TCP, base('tls'), base('ws')), and(DNS, base('tls'), base('ws')));\nexport const WebSocketsSecure = or(and(_WebSocketsSecure, base('p2p')), _WebSocketsSecure);\nexport const HTTP = or(and(TCP, base('http')), and(IP, base('http')), and(DNS, base('http')));\nexport const HTTPS = or(and(TCP, base('https')), and(IP, base('https')), and(DNS, base('https')));\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'));\nexport const WebRTCDirect = or(and(_WebRTCDirect, base('p2p')), _WebRTCDirect);\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'));\nexport const WebTransport = or(and(_WebTransport, base('p2p')), _WebTransport);\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(and(WebSockets, base('p2p-webrtc-star'), base('p2p')), and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')), and(WebSockets, base('p2p-webrtc-star')), and(WebSocketsSecure, base('p2p-webrtc-star')));\nexport const WebSocketStar = or(and(WebSockets, base('p2p-websocket-star'), base('p2p')), and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')), and(WebSockets, base('p2p-websocket-star')), and(WebSocketsSecure, base('p2p-websocket-star')));\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(and(HTTP, base('p2p-webrtc-direct'), base('p2p')), and(HTTPS, base('p2p-webrtc-direct'), base('p2p')), and(HTTP, base('p2p-webrtc-direct')), and(HTTPS, base('p2p-webrtc-direct')));\nexport const Reliable = or(_WebSockets, _WebSocketsSecure, HTTP, HTTPS, P2PWebRTCStar, P2PWebRTCDirect, TCP, UTP, QUIC, DNS, WebRTCDirect, WebTransport);\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(and(Reliable, base('p2p-stardust'), base('p2p')), and(Reliable, base('p2p-stardust')));\nconst _P2P = or(and(Reliable, base('p2p')), P2PWebRTCStar, P2PWebRTCDirect, WebRTCDirect, WebTransport, base('p2p'));\nconst _Circuit = or(and(_P2P, base('p2p-circuit'), _P2P), and(_P2P, base('p2p-circuit')), and(base('p2p-circuit'), _P2P), and(Reliable, base('p2p-circuit')), and(base('p2p-circuit'), Reliable), base('p2p-circuit'));\nconst CircuitRecursive = () => or(and(_Circuit, CircuitRecursive), _Circuit);\nexport const Circuit = CircuitRecursive();\nexport const P2P = or(and(Circuit, _P2P, Circuit), and(_P2P, Circuit), and(Circuit, _P2P), Circuit, _P2P);\nexport const IPFS = P2P;\nexport const WebRTC = or(and(Circuit, base('webrtc'), base('p2p')), and(Circuit, base('webrtc')), and(Reliable, base('webrtc'), base('p2p')), and(Reliable, base('webrtc')), base('webrtc'));\n/*\n * Validation funcs\n */\nfunction makeMatchesFunction(partialMatch) {\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const out = partialMatch(ma.protoNames());\n if (out === null) {\n return false;\n }\n if (out === true || out === false) {\n return out;\n }\n return out.length === 0;\n }\n return matches;\n}\nfunction and(...args) {\n function partialMatch(a) {\n if (a.length < args.length) {\n return null;\n }\n let out = a;\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (Array.isArray(out)) {\n a = out;\n }\n if (out === null) {\n return true;\n }\n return false;\n });\n return out;\n }\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n}\nfunction or(...args) {\n function partialMatch(a) {\n let out = null;\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (res != null) {\n out = res;\n return true;\n }\n return false;\n });\n return out;\n }\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n return result;\n}\nfunction base(n) {\n const name = n;\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const pnames = ma.protoNames();\n if (pnames.length === 1 && pnames[0] === name) {\n return true;\n }\n return false;\n }\n function partialMatch(protos) {\n if (protos.length === 0) {\n return null;\n }\n if (protos[0] === name) {\n return protos.slice(1);\n }\n return null;\n }\n return {\n toString: function () { return name; },\n matches,\n partialMatch\n };\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\nimport { TypedEventEmitter, peerDiscoverySymbol } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { P2P } from '@multiformats/mafmt';\nimport { multiaddr } from '@multiformats/multiaddr';\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap';\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nconst DEFAULT_BOOTSTRAP_TAG_TTL = 120000;\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000;\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter {\n static tag = 'bootstrap';\n log;\n timer;\n list;\n timeout;\n components;\n _init;\n constructor(components, options = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses');\n }\n super();\n this.components = components;\n this.log = components.logger.forComponent('libp2p:bootstrap');\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT;\n this.list = [];\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr');\n continue;\n }\n const ma = multiaddr(candidate);\n const peerIdStr = ma.getPeerId();\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id');\n continue;\n }\n const peerData = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma]\n };\n this.list.push(peerData);\n }\n this._init = options;\n }\n [peerDiscoverySymbol] = this;\n [Symbol.toStringTag] = '@libp2p/bootstrap';\n isStarted() {\n return Boolean(this.timer);\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted()) {\n return;\n }\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout);\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err);\n });\n }, this.timeout);\n }\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers() {\n if (this.timer == null) {\n return;\n }\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n }\n });\n // check we are still running\n if (this.timer == null) {\n return;\n }\n this.safeDispatchEvent('peer', { detail: peerData });\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n this.timer = undefined;\n }\n}\nexport function bootstrap(init) {\n return (components) => new Bootstrap(components, init);\n}\n//# sourceMappingURL=index.js.map","// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return encodeMessage(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf) => {\n return decodeMessage(buf, AddressInfo.codec());\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes();\n break;\n case 2:\n obj.seq = reader.uint64();\n break;\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()));\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return encodeMessage(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf) => {\n return decodeMessage(buf, PeerRecord.codec());\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map","import { peerIdFromBytes } from '@libp2p/peer-id';\nimport { arrayEquals } from '@libp2p/utils/array-equals';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { ENVELOPE_DOMAIN_PEER_RECORD, ENVELOPE_PAYLOAD_TYPE_PEER_RECORD } from './consts.js';\nimport { PeerRecord as Protobuf } from './peer-record.js';\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = Protobuf.decode(buf);\n const peerId = peerIdFromBytes(peerRecord.peerId);\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => multiaddr(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map","/*!\n Copyright (c) Peculiar Ventures, LLC\n*/\n\nfunction getUTCDate(date) {\r\n return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));\r\n}\r\nfunction getParametersValue(parameters, name, defaultValue) {\r\n var _a;\r\n if ((parameters instanceof Object) === false) {\r\n return defaultValue;\r\n }\r\n return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;\r\n}\r\nfunction bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {\r\n let result = \"\";\r\n for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {\r\n const str = item.toString(16).toUpperCase();\r\n if (str.length === 1) {\r\n result += \"0\";\r\n }\r\n result += str;\r\n if (insertSpace) {\r\n result += \" \";\r\n }\r\n }\r\n return result.trim();\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof ArrayBuffer)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be \\\"ArrayBuffer\\\"\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction utilFromBase(inputBuffer, inputBase) {\r\n let result = 0;\r\n if (inputBuffer.length === 1) {\r\n return inputBuffer[0];\r\n }\r\n for (let i = (inputBuffer.length - 1); i >= 0; i--) {\r\n result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);\r\n }\r\n return result;\r\n}\r\nfunction utilToBase(value, base, reserved = (-1)) {\r\n const internalReserved = reserved;\r\n let internalValue = value;\r\n let result = 0;\r\n let biggest = Math.pow(2, base);\r\n for (let i = 1; i < 8; i++) {\r\n if (value < biggest) {\r\n let retBuf;\r\n if (internalReserved < 0) {\r\n retBuf = new ArrayBuffer(i);\r\n result = i;\r\n }\r\n else {\r\n if (internalReserved < i) {\r\n return (new ArrayBuffer(0));\r\n }\r\n retBuf = new ArrayBuffer(internalReserved);\r\n result = internalReserved;\r\n }\r\n const retView = new Uint8Array(retBuf);\r\n for (let j = (i - 1); j >= 0; j--) {\r\n const basis = Math.pow(2, j * base);\r\n retView[result - j - 1] = Math.floor(internalValue / basis);\r\n internalValue -= (retView[result - j - 1]) * basis;\r\n }\r\n return retBuf;\r\n }\r\n biggest *= Math.pow(2, base);\r\n }\r\n return new ArrayBuffer(0);\r\n}\r\nfunction utilConcatBuf(...buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const buffer of buffers) {\r\n outputLength += buffer.byteLength;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const buffer of buffers) {\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retBuf;\r\n}\r\nfunction utilConcatView(...views) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const view of views) {\r\n outputLength += view.length;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const view of views) {\r\n retView.set(view, prevLength);\r\n prevLength += view.length;\r\n }\r\n return retView;\r\n}\r\nfunction utilDecodeTC() {\r\n const buf = new Uint8Array(this.valueHex);\r\n if (this.valueHex.byteLength >= 2) {\r\n const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);\r\n const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);\r\n if (condition1 || condition2) {\r\n this.warnings.push(\"Needlessly long format\");\r\n }\r\n }\r\n const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const bigIntView = new Uint8Array(bigIntBuffer);\r\n for (let i = 0; i < this.valueHex.byteLength; i++) {\r\n bigIntView[i] = 0;\r\n }\r\n bigIntView[0] = (buf[0] & 0x80);\r\n const bigInt = utilFromBase(bigIntView, 8);\r\n const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const smallIntView = new Uint8Array(smallIntBuffer);\r\n for (let j = 0; j < this.valueHex.byteLength; j++) {\r\n smallIntView[j] = buf[j];\r\n }\r\n smallIntView[0] &= 0x7F;\r\n const smallInt = utilFromBase(smallIntView, 8);\r\n return (smallInt - bigInt);\r\n}\r\nfunction utilEncodeTC(value) {\r\n const modValue = (value < 0) ? (value * (-1)) : value;\r\n let bigInt = 128;\r\n for (let i = 1; i < 8; i++) {\r\n if (modValue <= bigInt) {\r\n if (value < 0) {\r\n const smallInt = bigInt - modValue;\r\n const retBuf = utilToBase(smallInt, 8, i);\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] |= 0x80;\r\n return retBuf;\r\n }\r\n let retBuf = utilToBase(modValue, 8, i);\r\n let retView = new Uint8Array(retBuf);\r\n if (retView[0] & 0x80) {\r\n const tempBuf = retBuf.slice(0);\r\n const tempView = new Uint8Array(tempBuf);\r\n retBuf = new ArrayBuffer(retBuf.byteLength + 1);\r\n retView = new Uint8Array(retBuf);\r\n for (let k = 0; k < tempBuf.byteLength; k++) {\r\n retView[k + 1] = tempView[k];\r\n }\r\n retView[0] = 0x00;\r\n }\r\n return retBuf;\r\n }\r\n bigInt *= Math.pow(2, 8);\r\n }\r\n return (new ArrayBuffer(0));\r\n}\r\nfunction isEqualBuffer(inputBuffer1, inputBuffer2) {\r\n if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {\r\n return false;\r\n }\r\n const view1 = new Uint8Array(inputBuffer1);\r\n const view2 = new Uint8Array(inputBuffer2);\r\n for (let i = 0; i < view1.length; i++) {\r\n if (view1[i] !== view2[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction padNumber(inputNumber, fullLength) {\r\n const str = inputNumber.toString(10);\r\n if (fullLength < str.length) {\r\n return \"\";\r\n }\r\n const dif = fullLength - str.length;\r\n const padding = new Array(dif);\r\n for (let i = 0; i < dif; i++) {\r\n padding[i] = \"0\";\r\n }\r\n const paddingString = padding.join(\"\");\r\n return paddingString.concat(str);\r\n}\r\nconst base64Template = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\nconst base64UrlTemplate = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\";\r\nfunction toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {\r\n let i = 0;\r\n let flag1 = 0;\r\n let flag2 = 0;\r\n let output = \"\";\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n if (skipLeadingZeros) {\r\n let nonZeroPosition = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n if (input.charCodeAt(i) !== 0) {\r\n nonZeroPosition = i;\r\n break;\r\n }\r\n }\r\n input = input.slice(nonZeroPosition);\r\n }\r\n while (i < input.length) {\r\n const chr1 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag1 = 1;\r\n }\r\n const chr2 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag2 = 1;\r\n }\r\n const chr3 = input.charCodeAt(i++);\r\n const enc1 = chr1 >> 2;\r\n const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);\r\n let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);\r\n let enc4 = chr3 & 0x3F;\r\n if (flag1 === 1) {\r\n enc3 = enc4 = 64;\r\n }\r\n else {\r\n if (flag2 === 1) {\r\n enc4 = 64;\r\n }\r\n }\r\n if (skipPadding) {\r\n if (enc3 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}`;\r\n }\r\n else {\r\n if (enc4 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n return output;\r\n}\r\nfunction fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n function indexOf(toSearch) {\r\n for (let i = 0; i < 64; i++) {\r\n if (template.charAt(i) === toSearch)\r\n return i;\r\n }\r\n return 64;\r\n }\r\n function test(incoming) {\r\n return ((incoming === 64) ? 0x00 : incoming);\r\n }\r\n let i = 0;\r\n let output = \"\";\r\n while (i < input.length) {\r\n const enc1 = indexOf(input.charAt(i++));\r\n const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);\r\n const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);\r\n const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);\r\n output += String.fromCharCode(chr1);\r\n if (enc3 !== 64) {\r\n output += String.fromCharCode(chr2);\r\n }\r\n if (enc4 !== 64) {\r\n output += String.fromCharCode(chr3);\r\n }\r\n }\r\n if (cutTailZeros) {\r\n const outputLength = output.length;\r\n let nonZeroStart = (-1);\r\n for (let i = (outputLength - 1); i >= 0; i--) {\r\n if (output.charCodeAt(i) !== 0) {\r\n nonZeroStart = i;\r\n break;\r\n }\r\n }\r\n if (nonZeroStart !== (-1)) {\r\n output = output.slice(0, nonZeroStart + 1);\r\n }\r\n else {\r\n output = \"\";\r\n }\r\n }\r\n return output;\r\n}\r\nfunction arrayBufferToString(buffer) {\r\n let resultString = \"\";\r\n const view = new Uint8Array(buffer);\r\n for (const element of view) {\r\n resultString += String.fromCharCode(element);\r\n }\r\n return resultString;\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n const stringLength = str.length;\r\n const resultBuffer = new ArrayBuffer(stringLength);\r\n const resultView = new Uint8Array(resultBuffer);\r\n for (let i = 0; i < stringLength; i++) {\r\n resultView[i] = str.charCodeAt(i);\r\n }\r\n return resultBuffer;\r\n}\r\nconst log2 = Math.log(2);\r\nfunction nearestPowerOf2(length) {\r\n const base = (Math.log(length) / log2);\r\n const floor = Math.floor(base);\r\n const round = Math.round(base);\r\n return ((floor === round) ? floor : round);\r\n}\r\nfunction clearProps(object, propsArray) {\r\n for (const prop of propsArray) {\r\n delete object[prop];\r\n }\r\n}\n\nexport { arrayBufferToString, bufferToHexCodes, checkBufferParams, clearProps, fromBase64, getParametersValue, getUTCDate, isEqualBuffer, nearestPowerOf2, padNumber, stringToArrayBuffer, toBase64, utilConcatBuf, utilConcatView, utilDecodeTC, utilEncodeTC, utilFromBase, utilToBase };\n","/*!\n * Copyright (c) 2014, GMO GlobalSign\n * Copyright (c) 2015-2022, Peculiar Ventures\n * All rights reserved.\n * \n * Author 2014-2019, Yury Strozhevsky\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * \n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\nimport * as pvtsutils from 'pvtsutils';\nimport * as pvutils from 'pvutils';\n\nfunction assertBigInt() {\r\n if (typeof BigInt === \"undefined\") {\r\n throw new Error(\"BigInt is not defined. Your environment doesn't implement BigInt.\");\r\n }\r\n}\r\nfunction concat(buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n outputLength += buffer.byteLength;\r\n }\r\n const retView = new Uint8Array(outputLength);\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retView.buffer;\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof Uint8Array)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be 'Uint8Array'\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\n\nclass ViewWriter {\r\n constructor() {\r\n this.items = [];\r\n }\r\n write(buf) {\r\n this.items.push(buf);\r\n }\r\n final() {\r\n return concat(this.items);\r\n }\r\n}\n\nconst powers2 = [new Uint8Array([1])];\r\nconst digitsString = \"0123456789\";\r\nconst NAME = \"name\";\r\nconst VALUE_HEX_VIEW = \"valueHexView\";\r\nconst IS_HEX_ONLY = \"isHexOnly\";\r\nconst ID_BLOCK = \"idBlock\";\r\nconst TAG_CLASS = \"tagClass\";\r\nconst TAG_NUMBER = \"tagNumber\";\r\nconst IS_CONSTRUCTED = \"isConstructed\";\r\nconst FROM_BER = \"fromBER\";\r\nconst TO_BER = \"toBER\";\r\nconst LOCAL = \"local\";\r\nconst EMPTY_STRING = \"\";\r\nconst EMPTY_BUFFER = new ArrayBuffer(0);\r\nconst EMPTY_VIEW = new Uint8Array(0);\r\nconst END_OF_CONTENT_NAME = \"EndOfContent\";\r\nconst OCTET_STRING_NAME = \"OCTET STRING\";\r\nconst BIT_STRING_NAME = \"BIT STRING\";\n\nfunction HexBlock(BaseClass) {\r\n var _a;\r\n return _a = class Some extends BaseClass {\r\n constructor(...args) {\r\n var _a;\r\n super(...args);\r\n const params = args[0] || {};\r\n this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;\r\n }\r\n get valueHex() {\r\n return this.valueHexView.slice().buffer;\r\n }\r\n set valueHex(value) {\r\n this.valueHexView = new Uint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const endLength = inputOffset + inputLength;\r\n this.valueHexView = view.subarray(inputOffset, endLength);\r\n if (!this.valueHexView.length) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n this.blockLength = inputLength;\r\n return endLength;\r\n }\r\n toBER(sizeOnly = false) {\r\n if (!this.isHexOnly) {\r\n this.error = \"Flag 'isHexOnly' is not set, abort\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength);\r\n }\r\n return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)\r\n ? this.valueHexView.buffer\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isHexOnly: this.isHexOnly,\r\n valueHex: pvtsutils.Convert.ToHex(this.valueHexView),\r\n };\r\n }\r\n },\r\n _a.NAME = \"hexBlock\",\r\n _a;\r\n}\n\nclass LocalBaseBlock {\r\n constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {\r\n this.blockLength = blockLength;\r\n this.error = error;\r\n this.warnings = warnings;\r\n this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode);\r\n }\r\n static blockName() {\r\n return this.NAME;\r\n }\r\n get valueBeforeDecode() {\r\n return this.valueBeforeDecodeView.slice().buffer;\r\n }\r\n set valueBeforeDecode(value) {\r\n this.valueBeforeDecodeView = new Uint8Array(value);\r\n }\r\n toJSON() {\r\n return {\r\n blockName: this.constructor.NAME,\r\n blockLength: this.blockLength,\r\n error: this.error,\r\n warnings: this.warnings,\r\n valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView),\r\n };\r\n }\r\n}\r\nLocalBaseBlock.NAME = \"baseBlock\";\n\nclass ValueBlock extends LocalBaseBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n toBER(sizeOnly, writer) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n}\r\nValueBlock.NAME = \"valueBlock\";\n\nclass LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ idBlock = {}, } = {}) {\r\n var _a, _b, _c, _d;\r\n super();\r\n if (idBlock) {\r\n this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;\r\n this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;\r\n this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;\r\n this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;\r\n }\r\n else {\r\n this.tagClass = -1;\r\n this.tagNumber = -1;\r\n this.isConstructed = false;\r\n }\r\n }\r\n toBER(sizeOnly = false) {\r\n let firstOctet = 0;\r\n switch (this.tagClass) {\r\n case 1:\r\n firstOctet |= 0x00;\r\n break;\r\n case 2:\r\n firstOctet |= 0x40;\r\n break;\r\n case 3:\r\n firstOctet |= 0x80;\r\n break;\r\n case 4:\r\n firstOctet |= 0xC0;\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (this.isConstructed)\r\n firstOctet |= 0x20;\r\n if (this.tagNumber < 31 && !this.isHexOnly) {\r\n const retView = new Uint8Array(1);\r\n if (!sizeOnly) {\r\n let number = this.tagNumber;\r\n number &= 0x1F;\r\n firstOctet |= number;\r\n retView[0] = firstOctet;\r\n }\r\n return retView.buffer;\r\n }\r\n if (!this.isHexOnly) {\r\n const encodedBuf = pvutils.utilToBase(this.tagNumber, 7);\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const size = encodedBuf.byteLength;\r\n const retView = new Uint8Array(size + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n for (let i = 0; i < (size - 1); i++)\r\n retView[i + 1] = encodedView[i] | 0x80;\r\n retView[size] = encodedView[size - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.byteLength + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n const curView = this.valueHexView;\r\n for (let i = 0; i < (curView.length - 1); i++)\r\n retView[i + 1] = curView[i] | 0x80;\r\n retView[this.valueHexView.byteLength] = curView[curView.length - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n const tagClassMask = intBuffer[0] & 0xC0;\r\n switch (tagClassMask) {\r\n case 0x00:\r\n this.tagClass = (1);\r\n break;\r\n case 0x40:\r\n this.tagClass = (2);\r\n break;\r\n case 0x80:\r\n this.tagClass = (3);\r\n break;\r\n case 0xC0:\r\n this.tagClass = (4);\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return -1;\r\n }\r\n this.isConstructed = (intBuffer[0] & 0x20) === 0x20;\r\n this.isHexOnly = false;\r\n const tagNumberMask = intBuffer[0] & 0x1F;\r\n if (tagNumberMask !== 0x1F) {\r\n this.tagNumber = (tagNumberMask);\r\n this.blockLength = 1;\r\n }\r\n else {\r\n let count = 1;\r\n let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);\r\n let tagNumberBufferMaxLength = 255;\r\n while (intBuffer[count] & 0x80) {\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n count++;\r\n if (count >= intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (count === tagNumberBufferMaxLength) {\r\n tagNumberBufferMaxLength += 255;\r\n const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);\r\n for (let i = 0; i < intTagNumberBuffer.length; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);\r\n }\r\n }\r\n this.blockLength = (count + 1);\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n const tempBufferView = new Uint8Array(count);\r\n for (let i = 0; i < count; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(count);\r\n intTagNumberBuffer.set(tempBufferView);\r\n if (this.blockLength <= 9)\r\n this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Tag too long, represented as hex-coded\");\r\n }\r\n }\r\n if (((this.tagClass === 1)) &&\r\n (this.isConstructed)) {\r\n switch (this.tagNumber) {\r\n case 1:\r\n case 2:\r\n case 5:\r\n case 6:\r\n case 9:\r\n case 13:\r\n case 14:\r\n case 23:\r\n case 24:\r\n case 31:\r\n case 32:\r\n case 33:\r\n case 34:\r\n this.error = \"Constructed encoding used for primitive type\";\r\n return -1;\r\n }\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n tagClass: this.tagClass,\r\n tagNumber: this.tagNumber,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalIdentificationBlock.NAME = \"identificationBlock\";\n\nclass LocalLengthBlock extends LocalBaseBlock {\r\n constructor({ lenBlock = {}, } = {}) {\r\n var _a, _b, _c;\r\n super();\r\n this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;\r\n this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;\r\n this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n if (intBuffer[0] === 0xFF) {\r\n this.error = \"Length block 0xFF is reserved by standard\";\r\n return -1;\r\n }\r\n this.isIndefiniteForm = intBuffer[0] === 0x80;\r\n if (this.isIndefiniteForm) {\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n this.longFormUsed = !!(intBuffer[0] & 0x80);\r\n if (this.longFormUsed === false) {\r\n this.length = (intBuffer[0]);\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n const count = intBuffer[0] & 0x7F;\r\n if (count > 8) {\r\n this.error = \"Too big integer\";\r\n return -1;\r\n }\r\n if ((count + 1) > intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n const lenOffset = inputOffset + 1;\r\n const lengthBufferView = view.subarray(lenOffset, lenOffset + count);\r\n if (lengthBufferView[count - 1] === 0x00)\r\n this.warnings.push(\"Needlessly long encoded length\");\r\n this.length = pvutils.utilFromBase(lengthBufferView, 8);\r\n if (this.longFormUsed && (this.length <= 127))\r\n this.warnings.push(\"Unnecessary usage of long length form\");\r\n this.blockLength = count + 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly = false) {\r\n let retBuf;\r\n let retView;\r\n if (this.length > 127)\r\n this.longFormUsed = true;\r\n if (this.isIndefiniteForm) {\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = 0x80;\r\n }\r\n return retBuf;\r\n }\r\n if (this.longFormUsed) {\r\n const encodedBuf = pvutils.utilToBase(this.length, 8);\r\n if (encodedBuf.byteLength > 127) {\r\n this.error = \"Too big length\";\r\n return (EMPTY_BUFFER);\r\n }\r\n retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);\r\n if (sizeOnly)\r\n return retBuf;\r\n const encodedView = new Uint8Array(encodedBuf);\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = encodedBuf.byteLength | 0x80;\r\n for (let i = 0; i < encodedBuf.byteLength; i++)\r\n retView[i + 1] = encodedView[i];\r\n return retBuf;\r\n }\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = this.length;\r\n }\r\n return retBuf;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n longFormUsed: this.longFormUsed,\r\n length: this.length,\r\n };\r\n }\r\n}\r\nLocalLengthBlock.NAME = \"lengthBlock\";\n\nconst typeStore = {};\n\nclass BaseBlock extends LocalBaseBlock {\r\n constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {\r\n super(parameters);\r\n this.name = name;\r\n this.optional = optional;\r\n if (primitiveSchema) {\r\n this.primitiveSchema = primitiveSchema;\r\n }\r\n this.idBlock = new LocalIdentificationBlock(parameters);\r\n this.lenBlock = new LocalLengthBlock(parameters);\r\n this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n if (!writer) {\r\n prepareIndefiniteForm(this);\r\n }\r\n const idBlockBuf = this.idBlock.toBER(sizeOnly);\r\n _writer.write(idBlockBuf);\r\n if (this.lenBlock.isIndefiniteForm) {\r\n _writer.write(new Uint8Array([0x80]).buffer);\r\n this.valueBlock.toBER(sizeOnly, _writer);\r\n _writer.write(new ArrayBuffer(2));\r\n }\r\n else {\r\n const valueBlockBuf = this.valueBlock.toBER(sizeOnly);\r\n this.lenBlock.length = valueBlockBuf.byteLength;\r\n const lenBlockBuf = this.lenBlock.toBER(sizeOnly);\r\n _writer.write(lenBlockBuf);\r\n _writer.write(valueBlockBuf);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n idBlock: this.idBlock.toJSON(),\r\n lenBlock: this.lenBlock.toJSON(),\r\n valueBlock: this.valueBlock.toJSON(),\r\n name: this.name,\r\n optional: this.optional,\r\n };\r\n if (this.primitiveSchema)\r\n object.primitiveSchema = this.primitiveSchema.toJSON();\r\n return object;\r\n }\r\n toString(encoding = \"ascii\") {\r\n if (encoding === \"ascii\") {\r\n return this.onAsciiEncoding();\r\n }\r\n return pvtsutils.Convert.ToHex(this.toBER());\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;\r\n }\r\n isEqual(other) {\r\n if (this === other) {\r\n return true;\r\n }\r\n if (!(other instanceof this.constructor)) {\r\n return false;\r\n }\r\n const thisRaw = this.toBER();\r\n const otherRaw = other.toBER();\r\n return pvutils.isEqualBuffer(thisRaw, otherRaw);\r\n }\r\n}\r\nBaseBlock.NAME = \"BaseBlock\";\r\nfunction prepareIndefiniteForm(baseBlock) {\r\n if (baseBlock instanceof typeStore.Constructed) {\r\n for (const value of baseBlock.valueBlock.value) {\r\n if (prepareIndefiniteForm(value)) {\r\n baseBlock.lenBlock.isIndefiniteForm = true;\r\n }\r\n }\r\n }\r\n return !!baseBlock.lenBlock.isIndefiniteForm;\r\n}\n\nclass BaseStringBlock extends BaseBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {\r\n super(parameters, stringValueBlockType);\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n this.fromBuffer(this.valueBlock.valueHexView);\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : '${this.valueBlock.value}'`;\r\n }\r\n}\r\nBaseStringBlock.NAME = \"BaseStringBlock\";\n\nclass LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ isHexOnly = true, ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = isHexOnly;\r\n }\r\n}\r\nLocalPrimitiveValueBlock.NAME = \"PrimitiveValueBlock\";\n\nvar _a$w;\r\nclass Primitive extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalPrimitiveValueBlock);\r\n this.idBlock.isConstructed = false;\r\n }\r\n}\r\n_a$w = Primitive;\r\n(() => {\r\n typeStore.Primitive = _a$w;\r\n})();\r\nPrimitive.NAME = \"PRIMITIVE\";\n\nfunction localChangeType(inputObject, newType) {\r\n if (inputObject instanceof newType) {\r\n return inputObject;\r\n }\r\n const newObject = new newType();\r\n newObject.idBlock = inputObject.idBlock;\r\n newObject.lenBlock = inputObject.lenBlock;\r\n newObject.warnings = inputObject.warnings;\r\n newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;\r\n return newObject;\r\n}\r\nfunction localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {\r\n const incomingOffset = inputOffset;\r\n let returnObject = new BaseBlock({}, ValueBlock);\r\n const baseBlock = new LocalBaseBlock();\r\n if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {\r\n returnObject.error = baseBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);\r\n if (!intBuffer.length) {\r\n returnObject.error = \"Zero buffer length\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.idBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.idBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.idBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.idBlock.blockLength;\r\n resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.lenBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.lenBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.lenBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.lenBlock.blockLength;\r\n if (!returnObject.idBlock.isConstructed &&\r\n returnObject.lenBlock.isIndefiniteForm) {\r\n returnObject.error = \"Indefinite length form used for primitive encoding form\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let newASN1Type = BaseBlock;\r\n switch (returnObject.idBlock.tagClass) {\r\n case 1:\r\n if ((returnObject.idBlock.tagNumber >= 37) &&\r\n (returnObject.idBlock.isHexOnly === false)) {\r\n returnObject.error = \"UNIVERSAL 37 and upper tags are reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n switch (returnObject.idBlock.tagNumber) {\r\n case 0:\r\n if ((returnObject.idBlock.isConstructed) &&\r\n (returnObject.lenBlock.length > 0)) {\r\n returnObject.error = \"Type [UNIVERSAL 0] is reserved\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n newASN1Type = typeStore.EndOfContent;\r\n break;\r\n case 1:\r\n newASN1Type = typeStore.Boolean;\r\n break;\r\n case 2:\r\n newASN1Type = typeStore.Integer;\r\n break;\r\n case 3:\r\n newASN1Type = typeStore.BitString;\r\n break;\r\n case 4:\r\n newASN1Type = typeStore.OctetString;\r\n break;\r\n case 5:\r\n newASN1Type = typeStore.Null;\r\n break;\r\n case 6:\r\n newASN1Type = typeStore.ObjectIdentifier;\r\n break;\r\n case 10:\r\n newASN1Type = typeStore.Enumerated;\r\n break;\r\n case 12:\r\n newASN1Type = typeStore.Utf8String;\r\n break;\r\n case 13:\r\n newASN1Type = typeStore.RelativeObjectIdentifier;\r\n break;\r\n case 14:\r\n newASN1Type = typeStore.TIME;\r\n break;\r\n case 15:\r\n returnObject.error = \"[UNIVERSAL 15] is reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n case 16:\r\n newASN1Type = typeStore.Sequence;\r\n break;\r\n case 17:\r\n newASN1Type = typeStore.Set;\r\n break;\r\n case 18:\r\n newASN1Type = typeStore.NumericString;\r\n break;\r\n case 19:\r\n newASN1Type = typeStore.PrintableString;\r\n break;\r\n case 20:\r\n newASN1Type = typeStore.TeletexString;\r\n break;\r\n case 21:\r\n newASN1Type = typeStore.VideotexString;\r\n break;\r\n case 22:\r\n newASN1Type = typeStore.IA5String;\r\n break;\r\n case 23:\r\n newASN1Type = typeStore.UTCTime;\r\n break;\r\n case 24:\r\n newASN1Type = typeStore.GeneralizedTime;\r\n break;\r\n case 25:\r\n newASN1Type = typeStore.GraphicString;\r\n break;\r\n case 26:\r\n newASN1Type = typeStore.VisibleString;\r\n break;\r\n case 27:\r\n newASN1Type = typeStore.GeneralString;\r\n break;\r\n case 28:\r\n newASN1Type = typeStore.UniversalString;\r\n break;\r\n case 29:\r\n newASN1Type = typeStore.CharacterString;\r\n break;\r\n case 30:\r\n newASN1Type = typeStore.BmpString;\r\n break;\r\n case 31:\r\n newASN1Type = typeStore.DATE;\r\n break;\r\n case 32:\r\n newASN1Type = typeStore.TimeOfDay;\r\n break;\r\n case 33:\r\n newASN1Type = typeStore.DateTime;\r\n break;\r\n case 34:\r\n newASN1Type = typeStore.Duration;\r\n break;\r\n default: {\r\n const newObject = returnObject.idBlock.isConstructed\r\n ? new typeStore.Constructed()\r\n : new typeStore.Primitive();\r\n newObject.idBlock = returnObject.idBlock;\r\n newObject.lenBlock = returnObject.lenBlock;\r\n newObject.warnings = returnObject.warnings;\r\n returnObject = newObject;\r\n }\r\n }\r\n break;\r\n case 2:\r\n case 3:\r\n case 4:\r\n default: {\r\n newASN1Type = returnObject.idBlock.isConstructed\r\n ? typeStore.Constructed\r\n : typeStore.Primitive;\r\n }\r\n }\r\n returnObject = localChangeType(returnObject, newASN1Type);\r\n resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);\r\n returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);\r\n return {\r\n offset: resultOffset,\r\n result: returnObject\r\n };\r\n}\r\nfunction fromBER(inputBuffer) {\r\n if (!inputBuffer.byteLength) {\r\n const result = new BaseBlock({}, ValueBlock);\r\n result.error = \"Input buffer has zero length\";\r\n return {\r\n offset: -1,\r\n result\r\n };\r\n }\r\n return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);\r\n}\n\nfunction checkLen(indefiniteLength, length) {\r\n if (indefiniteLength) {\r\n return 1;\r\n }\r\n return length;\r\n}\r\nclass LocalConstructedValueBlock extends ValueBlock {\r\n constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.isIndefiniteForm = isIndefiniteForm;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (this.valueBeforeDecodeView.length === 0) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n let currentOffset = inputOffset;\r\n while (checkLen(this.isIndefiniteForm, inputLength) > 0) {\r\n const returnObject = localFromBER(view, currentOffset, inputLength);\r\n if (returnObject.offset === -1) {\r\n this.error = returnObject.result.error;\r\n this.warnings.concat(returnObject.result.warnings);\r\n return -1;\r\n }\r\n currentOffset = returnObject.offset;\r\n this.blockLength += returnObject.result.blockLength;\r\n inputLength -= returnObject.result.blockLength;\r\n this.value.push(returnObject.result);\r\n if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {\r\n break;\r\n }\r\n }\r\n if (this.isIndefiniteForm) {\r\n if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {\r\n this.value.pop();\r\n }\r\n else {\r\n this.warnings.push(\"No EndOfContent block encoded\");\r\n }\r\n }\r\n return currentOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n for (let i = 0; i < this.value.length; i++) {\r\n this.value[i].toBER(sizeOnly, _writer);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n value: [],\r\n };\r\n for (const value of this.value) {\r\n object.value.push(value.toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalConstructedValueBlock.NAME = \"ConstructedValueBlock\";\n\nvar _a$v;\r\nclass Constructed extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalConstructedValueBlock);\r\n this.idBlock.isConstructed = true;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n const values = [];\r\n for (const value of this.valueBlock.value) {\r\n values.push(value.toString(\"ascii\").split(\"\\n\").map(o => ` ${o}`).join(\"\\n\"));\r\n }\r\n const blockName = this.idBlock.tagClass === 3\r\n ? `[${this.idBlock.tagNumber}]`\r\n : this.constructor.NAME;\r\n return values.length\r\n ? `${blockName} :\\n${values.join(\"\\n\")}`\r\n : `${blockName} :`;\r\n }\r\n}\r\n_a$v = Constructed;\r\n(() => {\r\n typeStore.Constructed = _a$v;\r\n})();\r\nConstructed.NAME = \"CONSTRUCTED\";\n\nclass LocalEndOfContentValueBlock extends ValueBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n return inputOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return EMPTY_BUFFER;\r\n }\r\n}\r\nLocalEndOfContentValueBlock.override = \"EndOfContentValueBlock\";\n\nvar _a$u;\r\nclass EndOfContent extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalEndOfContentValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 0;\r\n }\r\n}\r\n_a$u = EndOfContent;\r\n(() => {\r\n typeStore.EndOfContent = _a$u;\r\n})();\r\nEndOfContent.NAME = END_OF_CONTENT_NAME;\n\nvar _a$t;\r\nclass Null extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, ValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 5;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (this.lenBlock.length > 0)\r\n this.warnings.push(\"Non-zero length of value block for Null type\");\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n this.blockLength += inputLength;\r\n if ((inputOffset + inputLength) > inputBuffer.byteLength) {\r\n this.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return -1;\r\n }\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuf = new ArrayBuffer(2);\r\n if (!sizeOnly) {\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] = 0x05;\r\n retView[1] = 0x00;\r\n }\r\n if (writer) {\r\n writer.write(retBuf);\r\n }\r\n return retBuf;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME}`;\r\n }\r\n}\r\n_a$t = Null;\r\n(() => {\r\n typeStore.Null = _a$t;\r\n})();\r\nNull.NAME = \"NULL\";\n\nclass LocalBooleanValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n if (parameters.valueHex) {\r\n this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex);\r\n }\r\n else {\r\n this.valueHexView = new Uint8Array(1);\r\n }\r\n if (value) {\r\n this.value = value;\r\n }\r\n }\r\n get value() {\r\n for (const octet of this.valueHexView) {\r\n if (octet > 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n set value(value) {\r\n this.valueHexView[0] = value ? 0xFF : 0x00;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (inputLength > 1)\r\n this.warnings.push(\"Boolean value encoded in more then 1 octet\");\r\n this.isHexOnly = true;\r\n pvutils.utilDecodeTC.call(this);\r\n this.blockLength = inputLength;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER() {\r\n return this.valueHexView.slice();\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalBooleanValueBlock.NAME = \"BooleanValueBlock\";\n\nvar _a$s;\r\nclass Boolean extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalBooleanValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 1;\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.getValue}`;\r\n }\r\n}\r\n_a$s = Boolean;\r\n(() => {\r\n typeStore.Boolean = _a$s;\r\n})();\r\nBoolean.NAME = \"BOOLEAN\";\n\nclass LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.isConstructed = isConstructed;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = 0;\r\n if (this.isConstructed) {\r\n this.isHexOnly = false;\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (let i = 0; i < this.value.length; i++) {\r\n const currentBlockName = this.value[i].constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== OCTET_STRING_NAME) {\r\n this.error = \"OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n }\r\n else {\r\n this.isHexOnly = true;\r\n resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n this.blockLength = inputLength;\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed)\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.byteLength)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalOctetStringValueBlock.NAME = \"OctetStringValueBlock\";\n\nvar _a$r;\r\nclass OctetString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalOctetStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 4;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n if (inputLength === 0) {\r\n if (this.idBlock.error.length === 0)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (this.lenBlock.error.length === 0)\r\n this.blockLength += this.lenBlock.blockLength;\r\n return inputOffset;\r\n }\r\n if (!this.valueBlock.isConstructed) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n const buf = view.subarray(inputOffset, inputOffset + inputLength);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === inputLength) {\r\n this.valueBlock.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`;\r\n }\r\n getValue() {\r\n if (!this.idBlock.isConstructed) {\r\n return this.valueBlock.valueHexView.slice().buffer;\r\n }\r\n const array = [];\r\n for (const content of this.valueBlock.value) {\r\n if (content instanceof OctetString) {\r\n array.push(content.valueBlock.valueHexView);\r\n }\r\n }\r\n return pvtsutils.BufferSourceConverter.concat(array);\r\n }\r\n}\r\n_a$r = OctetString;\r\n(() => {\r\n typeStore.OctetString = _a$r;\r\n})();\r\nOctetString.NAME = OCTET_STRING_NAME;\n\nclass LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.unusedBits = unusedBits;\r\n this.isConstructed = isConstructed;\r\n this.blockLength = this.valueHexView.byteLength;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n let resultOffset = -1;\r\n if (this.isConstructed) {\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (const value of this.value) {\r\n const currentBlockName = value.constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== BIT_STRING_NAME) {\r\n this.error = \"BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n const valueBlock = value.valueBlock;\r\n if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {\r\n this.error = \"Using of \\\"unused bits\\\" inside constructive BIT STRING allowed for least one only\";\r\n return -1;\r\n }\r\n this.unusedBits = valueBlock.unusedBits;\r\n }\r\n return resultOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.unusedBits = intBuffer[0];\r\n if (this.unusedBits > 7) {\r\n this.error = \"Unused bits for BitString must be in range 0-7\";\r\n return -1;\r\n }\r\n if (!this.unusedBits) {\r\n const buf = intBuffer.subarray(1);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {\r\n this.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n this.valueHexView = intBuffer.subarray(1);\r\n this.blockLength = intBuffer.length;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed) {\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength + 1);\r\n }\r\n if (!this.valueHexView.byteLength) {\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.length + 1);\r\n retView[0] = this.unusedBits;\r\n retView.set(this.valueHexView, 1);\r\n return retView.buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n unusedBits: this.unusedBits,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalBitStringValueBlock.NAME = \"BitStringValueBlock\";\n\nvar _a$q;\r\nclass BitString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalBitStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 3;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n else {\r\n const bits = [];\r\n const valueHex = this.valueBlock.valueHexView;\r\n for (const byte of valueHex) {\r\n bits.push(byte.toString(2).padStart(8, \"0\"));\r\n }\r\n const bitsStr = bits.join(\"\");\r\n return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;\r\n }\r\n }\r\n}\r\n_a$q = BitString;\r\n(() => {\r\n typeStore.BitString = _a$q;\r\n})();\r\nBitString.NAME = BIT_STRING_NAME;\n\nvar _a$p;\r\nfunction viewAdd(first, second) {\r\n const c = new Uint8Array([0]);\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n let firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value = 0;\r\n const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;\r\n let counter = 0;\r\n for (let i = max; i >= 0; i--, counter++) {\r\n switch (true) {\r\n case (counter < secondViewCopy.length):\r\n value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];\r\n break;\r\n default:\r\n value = firstViewCopy[firstViewCopyLength - counter] + c[0];\r\n }\r\n c[0] = value / 10;\r\n switch (true) {\r\n case (counter >= firstViewCopy.length):\r\n firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);\r\n break;\r\n default:\r\n firstViewCopy[firstViewCopyLength - counter] = value % 10;\r\n }\r\n }\r\n if (c[0] > 0)\r\n firstViewCopy = pvutils.utilConcatView(c, firstViewCopy);\r\n return firstViewCopy;\r\n}\r\nfunction power2(n) {\r\n if (n >= powers2.length) {\r\n for (let p = powers2.length; p <= n; p++) {\r\n const c = new Uint8Array([0]);\r\n let digits = (powers2[p - 1]).slice(0);\r\n for (let i = (digits.length - 1); i >= 0; i--) {\r\n const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);\r\n c[0] = newValue[0] / 10;\r\n digits[i] = newValue[0] % 10;\r\n }\r\n if (c[0] > 0)\r\n digits = pvutils.utilConcatView(c, digits);\r\n powers2.push(digits);\r\n }\r\n }\r\n return powers2[n];\r\n}\r\nfunction viewSub(first, second) {\r\n let b = 0;\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n const firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value;\r\n let counter = 0;\r\n for (let i = secondViewCopyLength; i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;\r\n switch (true) {\r\n case (value < 0):\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n break;\r\n default:\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n }\r\n }\r\n if (b > 0) {\r\n for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - b;\r\n if (value < 0) {\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n }\r\n else {\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n break;\r\n }\r\n }\r\n }\r\n return firstViewCopy.slice();\r\n}\r\nclass LocalIntegerValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n this._valueDec = 0;\r\n if (parameters.valueHex) {\r\n this.setValueHex();\r\n }\r\n if (value !== undefined) {\r\n this.valueDec = value;\r\n }\r\n }\r\n setValueHex() {\r\n if (this.valueHexView.length >= 4) {\r\n this.warnings.push(\"Too big Integer for decoding, hex only\");\r\n this.isHexOnly = true;\r\n this._valueDec = 0;\r\n }\r\n else {\r\n this.isHexOnly = false;\r\n if (this.valueHexView.length > 0) {\r\n this._valueDec = pvutils.utilDecodeTC.call(this);\r\n }\r\n }\r\n }\r\n set valueDec(v) {\r\n this._valueDec = v;\r\n this.isHexOnly = false;\r\n this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v));\r\n }\r\n get valueDec() {\r\n return this._valueDec;\r\n }\r\n fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {\r\n const offset = this.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (offset === -1)\r\n return offset;\r\n const view = this.valueHexView;\r\n if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {\r\n this.valueHexView = view.subarray(1);\r\n }\r\n else {\r\n if (expectedLength !== 0) {\r\n if (view.length < expectedLength) {\r\n if ((expectedLength - view.length) > 1)\r\n expectedLength = view.length + 1;\r\n this.valueHexView = view.subarray(expectedLength - view.length);\r\n }\r\n }\r\n }\r\n return offset;\r\n }\r\n toDER(sizeOnly = false) {\r\n const view = this.valueHexView;\r\n switch (true) {\r\n case ((view[0] & 0x80) !== 0):\r\n {\r\n const updatedView = new Uint8Array(this.valueHexView.length + 1);\r\n updatedView[0] = 0x00;\r\n updatedView.set(view, 1);\r\n this.valueHexView = updatedView;\r\n }\r\n break;\r\n case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):\r\n {\r\n this.valueHexView = this.valueHexView.subarray(1);\r\n }\r\n break;\r\n }\r\n return this.toBER(sizeOnly);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1) {\r\n return resultOffset;\r\n }\r\n this.setValueHex();\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.length)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n toString() {\r\n const firstBit = (this.valueHexView.length * 8) - 1;\r\n let digits = new Uint8Array((this.valueHexView.length * 8) / 3);\r\n let bitNumber = 0;\r\n let currentByte;\r\n const asn1View = this.valueHexView;\r\n let result = \"\";\r\n let flag = false;\r\n for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {\r\n currentByte = asn1View[byteNumber];\r\n for (let i = 0; i < 8; i++) {\r\n if ((currentByte & 1) === 1) {\r\n switch (bitNumber) {\r\n case firstBit:\r\n digits = viewSub(power2(bitNumber), digits);\r\n result = \"-\";\r\n break;\r\n default:\r\n digits = viewAdd(digits, power2(bitNumber));\r\n }\r\n }\r\n bitNumber++;\r\n currentByte >>= 1;\r\n }\r\n }\r\n for (let i = 0; i < digits.length; i++) {\r\n if (digits[i])\r\n flag = true;\r\n if (flag)\r\n result += digitsString.charAt(digits[i]);\r\n }\r\n if (flag === false)\r\n result += digitsString.charAt(0);\r\n return result;\r\n }\r\n}\r\n_a$p = LocalIntegerValueBlock;\r\nLocalIntegerValueBlock.NAME = \"IntegerValueBlock\";\r\n(() => {\r\n Object.defineProperty(_a$p.prototype, \"valueHex\", {\r\n set: function (v) {\r\n this.valueHexView = new Uint8Array(v);\r\n this.setValueHex();\r\n },\r\n get: function () {\r\n return this.valueHexView.slice().buffer;\r\n },\r\n });\r\n})();\n\nvar _a$o;\r\nclass Integer extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalIntegerValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 2;\r\n }\r\n toBigInt() {\r\n assertBigInt();\r\n return BigInt(this.valueBlock.toString());\r\n }\r\n static fromBigInt(value) {\r\n assertBigInt();\r\n const bigIntValue = BigInt(value);\r\n const writer = new ViewWriter();\r\n const hex = bigIntValue.toString(16).replace(/^-/, \"\");\r\n const view = new Uint8Array(pvtsutils.Convert.FromHex(hex));\r\n if (bigIntValue < 0) {\r\n const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));\r\n first[0] |= 0x80;\r\n const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`);\r\n const secondInt = firstInt + bigIntValue;\r\n const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16)));\r\n second[0] |= 0x80;\r\n writer.write(second);\r\n }\r\n else {\r\n if (view[0] & 0x80) {\r\n writer.write(new Uint8Array([0]));\r\n }\r\n writer.write(view);\r\n }\r\n const res = new Integer({\r\n valueHex: writer.final(),\r\n });\r\n return res;\r\n }\r\n convertToDER() {\r\n const integer = new Integer({ valueHex: this.valueBlock.valueHexView });\r\n integer.valueBlock.toDER();\r\n return integer;\r\n }\r\n convertFromDER() {\r\n return new Integer({\r\n valueHex: this.valueBlock.valueHexView[0] === 0\r\n ? this.valueBlock.valueHexView.subarray(1)\r\n : this.valueBlock.valueHexView,\r\n });\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;\r\n }\r\n}\r\n_a$o = Integer;\r\n(() => {\r\n typeStore.Integer = _a$o;\r\n})();\r\nInteger.NAME = \"INTEGER\";\n\nvar _a$n;\r\nclass Enumerated extends Integer {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 10;\r\n }\r\n}\r\n_a$n = Enumerated;\r\n(() => {\r\n typeStore.Enumerated = _a$n;\r\n})();\r\nEnumerated.NAME = \"ENUMERATED\";\n\nclass LocalSidValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n this.isFirstSid = isFirstSid;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++) {\r\n tempView[i] = this.valueHexView[i];\r\n }\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n set valueBigInt(value) {\r\n assertBigInt();\r\n let bits = BigInt(value).toString(2);\r\n while (bits.length % 7) {\r\n bits = \"0\" + bits;\r\n }\r\n const bytes = new Uint8Array(bits.length / 7);\r\n for (let i = 0; i < bytes.length; i++) {\r\n bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);\r\n }\r\n this.fromBER(bytes.buffer, 0, bytes.length);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n if (this.isFirstSid) {\r\n let sidValue = this.valueDec;\r\n if (this.valueDec <= 39)\r\n result = \"0.\";\r\n else {\r\n if (this.valueDec <= 79) {\r\n result = \"1.\";\r\n sidValue -= 40;\r\n }\r\n else {\r\n result = \"2.\";\r\n sidValue -= 80;\r\n }\r\n }\r\n result += sidValue.toString();\r\n }\r\n else\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n isFirstSid: this.isFirstSid,\r\n };\r\n }\r\n}\r\nLocalSidValueBlock.NAME = \"sidBlock\";\n\nclass LocalObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n if (this.value.length === 0)\r\n sidBlock.isFirstSid = true;\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n let flag = false;\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n if (flag) {\r\n const sidBlock = this.value[0];\r\n let plus = 0;\r\n switch (sidBlock.valueDec) {\r\n case 0:\r\n break;\r\n case 1:\r\n plus = 40;\r\n break;\r\n case 2:\r\n plus = 80;\r\n break;\r\n default:\r\n this.value = [];\r\n return;\r\n }\r\n const parsedSID = parseInt(sid, 10);\r\n if (isNaN(parsedSID))\r\n return;\r\n sidBlock.valueDec = parsedSID + plus;\r\n flag = false;\r\n }\r\n else {\r\n const sidBlock = new LocalSidValueBlock();\r\n if (sid > Number.MAX_SAFE_INTEGER) {\r\n assertBigInt();\r\n const sidValue = BigInt(sid);\r\n sidBlock.valueBigInt = sidValue;\r\n }\r\n else {\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return;\r\n }\r\n if (!this.value.length) {\r\n sidBlock.isFirstSid = true;\r\n flag = true;\r\n }\r\n this.value.push(sidBlock);\r\n }\r\n } while (pos2 !== -1);\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n if (this.value[i].isFirstSid)\r\n result = `2.{${sidStr} - 80}`;\r\n else\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++) {\r\n object.sidArray.push(this.value[i].toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalObjectIdentifierValueBlock.NAME = \"ObjectIdentifierValueBlock\";\n\nvar _a$m;\r\nclass ObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 6;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$m = ObjectIdentifier;\r\n(() => {\r\n typeStore.ObjectIdentifier = _a$m;\r\n})();\r\nObjectIdentifier.NAME = \"OBJECT IDENTIFIER\";\n\nclass LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ valueDec = 0, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (inputLength === 0)\r\n return inputOffset;\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength))\r\n return -1;\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++)\r\n tempView[i] = this.valueHexView[i];\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView.buffer;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n}\r\nLocalRelativeSidValueBlock.NAME = \"relativeSidBlock\";\n\nclass LocalRelativeObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return true;\r\n this.value.push(sidBlock);\r\n } while (pos2 !== -1);\r\n return true;\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++)\r\n object.sidArray.push(this.value[i].toJSON());\r\n return object;\r\n }\r\n}\r\nLocalRelativeObjectIdentifierValueBlock.NAME = \"RelativeObjectIdentifierValueBlock\";\n\nvar _a$l;\r\nclass RelativeObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalRelativeObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 13;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$l = RelativeObjectIdentifier;\r\n(() => {\r\n typeStore.RelativeObjectIdentifier = _a$l;\r\n})();\r\nRelativeObjectIdentifier.NAME = \"RelativeObjectIdentifier\";\n\nvar _a$k;\r\nclass Sequence extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 16;\r\n }\r\n}\r\n_a$k = Sequence;\r\n(() => {\r\n typeStore.Sequence = _a$k;\r\n})();\r\nSequence.NAME = \"SEQUENCE\";\n\nvar _a$j;\r\nclass Set extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 17;\r\n }\r\n}\r\n_a$j = Set;\r\n(() => {\r\n typeStore.Set = _a$j;\r\n})();\r\nSet.NAME = \"SET\";\n\nclass LocalStringValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = true;\r\n this.value = EMPTY_STRING;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalStringValueBlock.NAME = \"StringValueBlock\";\n\nclass LocalSimpleStringValueBlock extends LocalStringValueBlock {\r\n}\r\nLocalSimpleStringValueBlock.NAME = \"SimpleStringValueBlock\";\n\nclass LocalSimpleStringBlock extends BaseStringBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters, LocalSimpleStringValueBlock);\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLen = inputString.length;\r\n const view = this.valueBlock.valueHexView = new Uint8Array(strLen);\r\n for (let i = 0; i < strLen; i++)\r\n view[i] = inputString.charCodeAt(i);\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalSimpleStringBlock.NAME = \"SIMPLE STRING\";\n\nclass LocalUtf8StringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n try {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer);\r\n }\r\n catch (ex) {\r\n this.warnings.push(`Error during \"decodeURIComponent\": ${ex}, using raw string`);\r\n this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer);\r\n }\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString));\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUtf8StringValueBlock.NAME = \"Utf8StringValueBlock\";\n\nvar _a$i;\r\nclass Utf8String extends LocalUtf8StringValueBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 12;\r\n }\r\n}\r\n_a$i = Utf8String;\r\n(() => {\r\n typeStore.Utf8String = _a$i;\r\n})();\r\nUtf8String.NAME = \"UTF8String\";\n\nclass LocalBmpStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer);\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.value = inputString;\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString));\r\n }\r\n}\r\nLocalBmpStringValueBlock.NAME = \"BmpStringValueBlock\";\n\nvar _a$h;\r\nclass BmpString extends LocalBmpStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 30;\r\n }\r\n}\r\n_a$h = BmpString;\r\n(() => {\r\n typeStore.BmpString = _a$h;\r\n})();\r\nBmpString.NAME = \"BMPString\";\n\nclass LocalUniversalStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);\r\n const valueView = new Uint8Array(copyBuffer);\r\n for (let i = 0; i < valueView.length; i += 4) {\r\n valueView[i] = valueView[i + 3];\r\n valueView[i + 1] = valueView[i + 2];\r\n valueView[i + 2] = 0x00;\r\n valueView[i + 3] = 0x00;\r\n }\r\n this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLength = inputString.length;\r\n const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);\r\n for (let i = 0; i < strLength; i++) {\r\n const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8);\r\n const codeView = new Uint8Array(codeBuf);\r\n if (codeView.length > 4)\r\n continue;\r\n const dif = 4 - codeView.length;\r\n for (let j = (codeView.length - 1); j >= 0; j--)\r\n valueHexView[i * 4 + j + dif] = codeView[j];\r\n }\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUniversalStringValueBlock.NAME = \"UniversalStringValueBlock\";\n\nvar _a$g;\r\nclass UniversalString extends LocalUniversalStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 28;\r\n }\r\n}\r\n_a$g = UniversalString;\r\n(() => {\r\n typeStore.UniversalString = _a$g;\r\n})();\r\nUniversalString.NAME = \"UniversalString\";\n\nvar _a$f;\r\nclass NumericString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 18;\r\n }\r\n}\r\n_a$f = NumericString;\r\n(() => {\r\n typeStore.NumericString = _a$f;\r\n})();\r\nNumericString.NAME = \"NumericString\";\n\nvar _a$e;\r\nclass PrintableString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 19;\r\n }\r\n}\r\n_a$e = PrintableString;\r\n(() => {\r\n typeStore.PrintableString = _a$e;\r\n})();\r\nPrintableString.NAME = \"PrintableString\";\n\nvar _a$d;\r\nclass TeletexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 20;\r\n }\r\n}\r\n_a$d = TeletexString;\r\n(() => {\r\n typeStore.TeletexString = _a$d;\r\n})();\r\nTeletexString.NAME = \"TeletexString\";\n\nvar _a$c;\r\nclass VideotexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 21;\r\n }\r\n}\r\n_a$c = VideotexString;\r\n(() => {\r\n typeStore.VideotexString = _a$c;\r\n})();\r\nVideotexString.NAME = \"VideotexString\";\n\nvar _a$b;\r\nclass IA5String extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 22;\r\n }\r\n}\r\n_a$b = IA5String;\r\n(() => {\r\n typeStore.IA5String = _a$b;\r\n})();\r\nIA5String.NAME = \"IA5String\";\n\nvar _a$a;\r\nclass GraphicString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 25;\r\n }\r\n}\r\n_a$a = GraphicString;\r\n(() => {\r\n typeStore.GraphicString = _a$a;\r\n})();\r\nGraphicString.NAME = \"GraphicString\";\n\nvar _a$9;\r\nclass VisibleString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 26;\r\n }\r\n}\r\n_a$9 = VisibleString;\r\n(() => {\r\n typeStore.VisibleString = _a$9;\r\n})();\r\nVisibleString.NAME = \"VisibleString\";\n\nvar _a$8;\r\nclass GeneralString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 27;\r\n }\r\n}\r\n_a$8 = GeneralString;\r\n(() => {\r\n typeStore.GeneralString = _a$8;\r\n})();\r\nGeneralString.NAME = \"GeneralString\";\n\nvar _a$7;\r\nclass CharacterString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 29;\r\n }\r\n}\r\n_a$7 = CharacterString;\r\n(() => {\r\n typeStore.CharacterString = _a$7;\r\n})();\r\nCharacterString.NAME = \"CharacterString\";\n\nvar _a$6;\r\nclass UTCTime extends VisibleString {\r\n constructor({ value, valueDate, ...parameters } = {}) {\r\n super(parameters);\r\n this.year = 0;\r\n this.month = 0;\r\n this.day = 0;\r\n this.hour = 0;\r\n this.minute = 0;\r\n this.second = 0;\r\n if (value) {\r\n this.fromString(value);\r\n this.valueBlock.valueHexView = new Uint8Array(value.length);\r\n for (let i = 0; i < value.length; i++)\r\n this.valueBlock.valueHexView[i] = value.charCodeAt(i);\r\n }\r\n if (valueDate) {\r\n this.fromDate(valueDate);\r\n this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());\r\n }\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 23;\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)));\r\n }\r\n toBuffer() {\r\n const str = this.toString();\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buffer);\r\n for (let i = 0; i < str.length; i++)\r\n view[i] = str.charCodeAt(i);\r\n return buffer;\r\n }\r\n fromDate(inputDate) {\r\n this.year = inputDate.getUTCFullYear();\r\n this.month = inputDate.getUTCMonth() + 1;\r\n this.day = inputDate.getUTCDate();\r\n this.hour = inputDate.getUTCHours();\r\n this.minute = inputDate.getUTCMinutes();\r\n this.second = inputDate.getUTCSeconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));\r\n }\r\n fromString(inputString) {\r\n const parser = /(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/ig;\r\n const parserArray = parser.exec(inputString);\r\n if (parserArray === null) {\r\n this.error = \"Wrong input string for conversion\";\r\n return;\r\n }\r\n const year = parseInt(parserArray[1], 10);\r\n if (year >= 50)\r\n this.year = 1900 + year;\r\n else\r\n this.year = 2000 + year;\r\n this.month = parseInt(parserArray[2], 10);\r\n this.day = parseInt(parserArray[3], 10);\r\n this.hour = parseInt(parserArray[4], 10);\r\n this.minute = parseInt(parserArray[5], 10);\r\n this.second = parseInt(parserArray[6], 10);\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = new Array(7);\r\n outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);\r\n outputArray[1] = pvutils.padNumber(this.month, 2);\r\n outputArray[2] = pvutils.padNumber(this.day, 2);\r\n outputArray[3] = pvutils.padNumber(this.hour, 2);\r\n outputArray[4] = pvutils.padNumber(this.minute, 2);\r\n outputArray[5] = pvutils.padNumber(this.second, 2);\r\n outputArray[6] = \"Z\";\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n year: this.year,\r\n month: this.month,\r\n day: this.day,\r\n hour: this.hour,\r\n minute: this.minute,\r\n second: this.second,\r\n };\r\n }\r\n}\r\n_a$6 = UTCTime;\r\n(() => {\r\n typeStore.UTCTime = _a$6;\r\n})();\r\nUTCTime.NAME = \"UTCTime\";\n\nvar _a$5;\r\nclass GeneralizedTime extends UTCTime {\r\n constructor(parameters = {}) {\r\n var _b;\r\n super(parameters);\r\n (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 24;\r\n }\r\n fromDate(inputDate) {\r\n super.fromDate(inputDate);\r\n this.millisecond = inputDate.getUTCMilliseconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));\r\n }\r\n fromString(inputString) {\r\n let isUTC = false;\r\n let timeString = \"\";\r\n let dateTimeString = \"\";\r\n let fractionPart = 0;\r\n let parser;\r\n let hourDifference = 0;\r\n let minuteDifference = 0;\r\n if (inputString[inputString.length - 1] === \"Z\") {\r\n timeString = inputString.substring(0, inputString.length - 1);\r\n isUTC = true;\r\n }\r\n else {\r\n const number = new Number(inputString[inputString.length - 1]);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n timeString = inputString;\r\n }\r\n if (isUTC) {\r\n if (timeString.indexOf(\"+\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n if (timeString.indexOf(\"-\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n else {\r\n let multiplier = 1;\r\n let differencePosition = timeString.indexOf(\"+\");\r\n let differenceString = \"\";\r\n if (differencePosition === -1) {\r\n differencePosition = timeString.indexOf(\"-\");\r\n multiplier = -1;\r\n }\r\n if (differencePosition !== -1) {\r\n differenceString = timeString.substring(differencePosition + 1);\r\n timeString = timeString.substring(0, differencePosition);\r\n if ((differenceString.length !== 2) && (differenceString.length !== 4))\r\n throw new Error(\"Wrong input string for conversion\");\r\n let number = parseInt(differenceString.substring(0, 2), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n hourDifference = multiplier * number;\r\n if (differenceString.length === 4) {\r\n number = parseInt(differenceString.substring(2, 4), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n minuteDifference = multiplier * number;\r\n }\r\n }\r\n }\r\n let fractionPointPosition = timeString.indexOf(\".\");\r\n if (fractionPointPosition === -1)\r\n fractionPointPosition = timeString.indexOf(\",\");\r\n if (fractionPointPosition !== -1) {\r\n const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);\r\n if (isNaN(fractionPartCheck.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n fractionPart = fractionPartCheck.valueOf();\r\n dateTimeString = timeString.substring(0, fractionPointPosition);\r\n }\r\n else\r\n dateTimeString = timeString;\r\n switch (true) {\r\n case (dateTimeString.length === 8):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n break;\r\n case (dateTimeString.length === 10):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.minute = Math.floor(fractionResult);\r\n fractionResult = 60 * (fractionResult - this.minute);\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 12):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 14):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n const fractionResult = 1000 * fractionPart;\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n const parserArray = parser.exec(dateTimeString);\r\n if (parserArray === null)\r\n throw new Error(\"Wrong input string for conversion\");\r\n for (let j = 1; j < parserArray.length; j++) {\r\n switch (j) {\r\n case 1:\r\n this.year = parseInt(parserArray[j], 10);\r\n break;\r\n case 2:\r\n this.month = parseInt(parserArray[j], 10);\r\n break;\r\n case 3:\r\n this.day = parseInt(parserArray[j], 10);\r\n break;\r\n case 4:\r\n this.hour = parseInt(parserArray[j], 10) + hourDifference;\r\n break;\r\n case 5:\r\n this.minute = parseInt(parserArray[j], 10) + minuteDifference;\r\n break;\r\n case 6:\r\n this.second = parseInt(parserArray[j], 10);\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n }\r\n if (isUTC === false) {\r\n const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\r\n this.year = tempDate.getUTCFullYear();\r\n this.month = tempDate.getUTCMonth();\r\n this.day = tempDate.getUTCDay();\r\n this.hour = tempDate.getUTCHours();\r\n this.minute = tempDate.getUTCMinutes();\r\n this.second = tempDate.getUTCSeconds();\r\n this.millisecond = tempDate.getUTCMilliseconds();\r\n }\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = [];\r\n outputArray.push(pvutils.padNumber(this.year, 4));\r\n outputArray.push(pvutils.padNumber(this.month, 2));\r\n outputArray.push(pvutils.padNumber(this.day, 2));\r\n outputArray.push(pvutils.padNumber(this.hour, 2));\r\n outputArray.push(pvutils.padNumber(this.minute, 2));\r\n outputArray.push(pvutils.padNumber(this.second, 2));\r\n if (this.millisecond !== 0) {\r\n outputArray.push(\".\");\r\n outputArray.push(pvutils.padNumber(this.millisecond, 3));\r\n }\r\n outputArray.push(\"Z\");\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n millisecond: this.millisecond,\r\n };\r\n }\r\n}\r\n_a$5 = GeneralizedTime;\r\n(() => {\r\n typeStore.GeneralizedTime = _a$5;\r\n})();\r\nGeneralizedTime.NAME = \"GeneralizedTime\";\n\nvar _a$4;\r\nclass DATE extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 31;\r\n }\r\n}\r\n_a$4 = DATE;\r\n(() => {\r\n typeStore.DATE = _a$4;\r\n})();\r\nDATE.NAME = \"DATE\";\n\nvar _a$3;\r\nclass TimeOfDay extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 32;\r\n }\r\n}\r\n_a$3 = TimeOfDay;\r\n(() => {\r\n typeStore.TimeOfDay = _a$3;\r\n})();\r\nTimeOfDay.NAME = \"TimeOfDay\";\n\nvar _a$2;\r\nclass DateTime extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 33;\r\n }\r\n}\r\n_a$2 = DateTime;\r\n(() => {\r\n typeStore.DateTime = _a$2;\r\n})();\r\nDateTime.NAME = \"DateTime\";\n\nvar _a$1;\r\nclass Duration extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 34;\r\n }\r\n}\r\n_a$1 = Duration;\r\n(() => {\r\n typeStore.Duration = _a$1;\r\n})();\r\nDuration.NAME = \"Duration\";\n\nvar _a;\r\nclass TIME extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 14;\r\n }\r\n}\r\n_a = TIME;\r\n(() => {\r\n typeStore.TIME = _a;\r\n})();\r\nTIME.NAME = \"TIME\";\n\nclass Any {\r\n constructor({ name = EMPTY_STRING, optional = false, } = {}) {\r\n this.name = name;\r\n this.optional = optional;\r\n }\r\n}\n\nclass Choice extends Any {\r\n constructor({ value = [], ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n }\r\n}\n\nclass Repeated extends Any {\r\n constructor({ value = new Any(), local = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.local = local;\r\n }\r\n}\n\nclass RawData {\r\n constructor({ data = EMPTY_VIEW } = {}) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data);\r\n }\r\n get data() {\r\n return this.dataView.slice().buffer;\r\n }\r\n set data(value) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const endLength = inputOffset + inputLength;\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);\r\n return endLength;\r\n }\r\n toBER(sizeOnly) {\r\n return this.dataView.slice().buffer;\r\n }\r\n}\n\nfunction compareSchema(root, inputData, inputSchema) {\r\n if (inputSchema instanceof Choice) {\r\n for (let j = 0; j < inputSchema.value.length; j++) {\r\n const result = compareSchema(root, inputData, inputSchema.value[j]);\r\n if (result.verified) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n }\r\n {\r\n const _result = {\r\n verified: false,\r\n result: {\r\n error: \"Wrong values for Choice type\"\r\n },\r\n };\r\n if (inputSchema.hasOwnProperty(NAME))\r\n _result.name = inputSchema.name;\r\n return _result;\r\n }\r\n }\r\n if (inputSchema instanceof Any) {\r\n if (inputSchema.hasOwnProperty(NAME))\r\n root[inputSchema.name] = inputData;\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((root instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong root object\" }\r\n };\r\n }\r\n if ((inputData instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 data\" }\r\n };\r\n }\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((ID_BLOCK in inputSchema) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((FROM_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((TO_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const encodedId = inputSchema.idBlock.toBER(false);\r\n if (encodedId.byteLength === 0) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error encoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);\r\n if (decodedOffset === -1) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error decoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (!(IS_HEX_ONLY in inputSchema.idBlock)) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly) {\r\n if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const schemaView = inputSchema.idBlock.valueHexView;\r\n const asn1View = inputData.idBlock.valueHexView;\r\n if (schemaView.length !== asn1View.length) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < schemaView.length; i++) {\r\n if (schemaView[i] !== asn1View[1]) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n }\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n root[inputSchema.name] = inputData;\r\n }\r\n if (inputSchema instanceof typeStore.Constructed) {\r\n let admission = 0;\r\n let result = {\r\n verified: false,\r\n result: {\r\n error: \"Unknown error\",\r\n }\r\n };\r\n let maxLength = inputSchema.valueBlock.value.length;\r\n if (maxLength > 0) {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n maxLength = inputData.valueBlock.value.length;\r\n }\r\n }\r\n if (maxLength === 0) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((inputData.valueBlock.value.length === 0) &&\r\n (inputSchema.valueBlock.value.length !== 0)) {\r\n let _optional = true;\r\n for (let i = 0; i < inputSchema.valueBlock.value.length; i++)\r\n _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);\r\n if (_optional) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n root.error = \"Inconsistent object length\";\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < maxLength; i++) {\r\n if ((i - admission) >= inputData.valueBlock.value.length) {\r\n if (inputSchema.valueBlock.value[i].optional === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n root.error = \"Inconsistent length between ASN.1 data and schema\";\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n }\r\n else {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[0].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {\r\n let arrayRoot = {};\r\n if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))\r\n arrayRoot = inputData;\r\n else\r\n arrayRoot = root;\r\n if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === \"undefined\")\r\n arrayRoot[inputSchema.valueBlock.value[0].name] = [];\r\n arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);\r\n }\r\n }\r\n else {\r\n result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[i].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (result.verified === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.primitiveSchema &&\r\n (VALUE_HEX_VIEW in inputData.valueBlock)) {\r\n const asn1 = localFromBER(inputData.valueBlock.valueHexView);\r\n if (asn1.offset === -1) {\r\n const _result = {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return compareSchema(root, asn1.result, inputSchema.primitiveSchema);\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n}\r\nfunction verifySchema(inputBuffer, inputSchema) {\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema type\" }\r\n };\r\n }\r\n const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n if (asn1.offset === -1) {\r\n return {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n }\r\n return compareSchema(asn1.result, asn1.result, inputSchema);\r\n}\n\nexport { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema };\n","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.payloadType = reader.bytes();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n case 5:\n obj.signature = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return encodeMessage(obj, Envelope.codec());\n };\n Envelope.decode = (buf) => {\n return decodeMessage(buf, Envelope.codec());\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { CodeError } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string';\nimport { codes } from '../errors.js';\nimport { Envelope as Protobuf } from './envelope.js';\nexport class RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = Protobuf.decode(data);\n const peerId = await peerIdFromKeys(envelopeData.publicKey);\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, peerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const key = await unmarshalPrivateKey(peerId.privateKey);\n const signature = await key.sign(signData.subarray());\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new CodeError('envelope signature is not valid for the given domain', codes.ERR_SIGNATURE_NOT_VALID);\n }\n return envelope;\n };\n peerId;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { peerId, payloadType, payload, signature } = init;\n this.peerId = peerId;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return uint8ArrayEquals(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n const key = unmarshalPublicKey(this.peerId.publicKey);\n return key.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = uint8arraysFromString(domain);\n const domainLength = varint.encode(domainUint8Array.byteLength);\n const payloadTypeLength = varint.encode(payloadType.length);\n const payloadLength = varint.encode(payload.length);\n return new Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map","export const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n};\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\nimport { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport {} from '@multiformats/multiaddr';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma) => {\n return ma.toString().split('/').slice(1);\n};\nconst func = (fn) => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false;\n }\n if (fn(vals[0])) {\n return vals.slice(1);\n }\n return false;\n },\n pattern: 'fn'\n };\n};\nconst literal = (str) => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n };\n};\nconst string = () => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n };\n};\nconst number = () => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n };\n};\nconst peerId = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false;\n }\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n base58btc.decode(`z${vals[1]}`);\n }\n catch (err) {\n return false;\n }\n }\n else {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/p2p/{peerid}'\n };\n};\nconst certhash = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'certhash') {\n return false;\n }\n try {\n base64url.decode(vals[1]);\n }\n catch {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/certhash/{certhash}'\n };\n};\nconst optional = (matcher) => {\n return {\n match: (vals) => {\n const result = matcher.match(vals);\n if (result === false) {\n return vals;\n }\n return result;\n },\n pattern: `optional(${matcher.pattern})`\n };\n};\nconst or = (...matchers) => {\n return {\n match: (vals) => {\n let matches;\n for (const matcher of matchers) {\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n continue;\n }\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result;\n }\n }\n if (matches == null) {\n return false;\n }\n return matches;\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nconst and = (...matchers) => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n return false;\n }\n vals = result;\n }\n return vals;\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nfunction fmt(...matchers) {\n function match(ma) {\n let parts = toParts(ma);\n for (const matcher of matchers) {\n const result = matcher.match(parts);\n if (result === false) {\n return false;\n }\n parts = result;\n }\n return parts;\n }\n function matches(ma) {\n const result = match(ma);\n return result !== false;\n }\n function exactMatch(ma) {\n const result = match(ma);\n if (result === false) {\n return false;\n }\n return result.length === 0;\n }\n return {\n matches,\n exactMatch\n };\n}\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string());\nconst _DNS6 = and(literal('dns6'), string());\nconst _DNSADDR = and(literal('dnsaddr'), string());\nconst _DNS = and(literal('dns'), string());\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4);\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6);\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR);\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6));\nconst _IP4 = and(literal('ip4'), func(isIPv4));\nconst _IP6 = and(literal('ip6'), func(isIPv6));\nconst _IP = or(_IP4, _IP6);\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(_IP_OR_DOMAIN);\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4);\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6);\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP);\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number());\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number());\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(_TCP);\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP);\nconst _QUIC = and(_UDP, literal('quic'));\nconst _QUICV1 = and(_UDP, literal('quic-v1'));\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1);\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC);\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUICV1 = fmt(_QUICV1);\nconst _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUICV1);\nconst _WebSockets = or(and(_WEB, literal('ws'), optional(peerId())));\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets);\nconst _WebSocketsSecure = or(and(_WEB, literal('wss'), optional(peerId())), and(_WEB, literal('tls'), literal('ws'), optional(peerId())));\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure);\nconst _WebRTCDirect = and(_UDP, literal('webrtc-direct'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect);\nconst _WebTransport = and(_QUICV1, literal('webtransport'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport);\nconst _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(peerId())), and(QUIC_V0_OR_V1, optional(peerId())), and(_IP_OR_DOMAIN, optional(peerId())), _WebRTCDirect, _WebTransport, peerId());\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P);\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId());\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit);\nconst _WebRTC = or(and(_P2P, literal('p2p-circuit'), literal('webrtc'), optional(peerId())), and(_P2P, literal('webrtc'), optional(peerId())), literal('webrtc'));\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC);\nconst _HTTP = or(and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('http'), optional(peerId())));\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP);\nconst _HTTPS = or(and(_IP_OR_DOMAIN, literal('tcp'), or(and(literal('443'), literal('http')), and(number(), literal('https'))), optional(peerId())), and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('https'), optional(peerId())));\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS);\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed Protobuf encoded\n * messages over streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-protobuf-stream'\n * import { MessageType } from './src/my-message-type.js'\n *\n * // RequestType and ResponseType have been generate from `.proto` files and have\n * // `.encode` and `.decode` methods for serialization/deserialization\n *\n * const stream = pbStream(duplex)\n *\n * // write a message to the stream\n * stream.write({\n * foo: 'bar'\n * }, MessageType)\n *\n * // read a message from the stream\n * const res = await stream.read(MessageType)\n * ```\n */\nimport { lpStream } from 'it-length-prefixed-stream';\nexport function pbStream(duplex, opts) {\n const lp = lpStream(duplex, opts);\n const W = {\n read: async (proto, options) => {\n // readLP, decode\n const value = await lp.read(options);\n return proto.decode(value);\n },\n write: async (message, proto, options) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options);\n },\n writeV: async (messages, proto, options) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options);\n },\n pb: (proto) => {\n return {\n read: async (options) => W.read(proto, options),\n write: async (d, options) => W.write(d, proto, options),\n writeV: async (d, options) => W.writeV(d, proto, options),\n unwrap: () => W\n };\n },\n unwrap: () => {\n return lp.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Identify;\n(function (Identify) {\n let _codec;\n Identify.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.protocolVersion != null) {\n w.uint32(42);\n w.string(obj.protocolVersion);\n }\n if (obj.agentVersion != null) {\n w.uint32(50);\n w.string(obj.agentVersion);\n }\n if (obj.publicKey != null) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (obj.observedAddr != null) {\n w.uint32(34);\n w.bytes(obj.observedAddr);\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26);\n w.string(value);\n }\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(66);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n listenAddrs: [],\n protocols: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string();\n break;\n case 6:\n obj.agentVersion = reader.string();\n break;\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.listenAddrs.push(reader.bytes());\n break;\n case 4:\n obj.observedAddr = reader.bytes();\n break;\n case 3:\n obj.protocols.push(reader.string());\n break;\n case 8:\n obj.signedPeerRecord = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Identify.encode = (obj) => {\n return encodeMessage(obj, Identify.codec());\n };\n Identify.decode = (buf) => {\n return decodeMessage(buf, Identify.codec());\n };\n})(Identify || (Identify = {}));\n//# sourceMappingURL=message.js.map","/* eslint-disable complexity */\nimport { CodeError, ERR_NOT_FOUND, setMaxListeners } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport { multiaddr, protocols } from '@multiformats/multiaddr';\nimport { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher';\nimport { pbStream } from 'it-protobuf-stream';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe';\nimport { IDENTIFY_PROTOCOL_VERSION, MULTICODEC_IDENTIFY_PROTOCOL_NAME, MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME, MULTICODEC_IDENTIFY_PROTOCOL_VERSION, MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION } from './consts.js';\nimport { Identify as IdentifyMessage } from './pb/message.js';\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8;\nconst defaultValues = {\n protocolPrefix: 'ipfs',\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1,\n maxObservedAddresses: 10,\n maxIdentifyMessageSize: 8192,\n runOnConnectionOpen: true,\n runOnTransientConnection: true\n};\nexport class Identify {\n identifyProtocolStr;\n identifyPushProtocolStr;\n host;\n started;\n timeout;\n peerId;\n peerStore;\n registrar;\n connectionManager;\n addressManager;\n maxInboundStreams;\n maxOutboundStreams;\n maxPushIncomingStreams;\n maxPushOutgoingStreams;\n maxIdentifyMessageSize;\n maxObservedAddresses;\n events;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.started = false;\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.registrar = components.registrar;\n this.addressManager = components.addressManager;\n this.connectionManager = components.connectionManager;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:identify');\n this.identifyProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`;\n this.identifyPushProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? defaultValues.timeout;\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams;\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams;\n this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? defaultValues.maxPushIncomingStreams;\n this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? defaultValues.maxPushOutgoingStreams;\n this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? defaultValues.maxIdentifyMessageSize;\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses;\n this.runOnTransientConnection = init.runOnTransientConnection ?? defaultValues.runOnTransientConnection;\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: init.agentVersion ?? `${components.nodeInfo.name}/${components.nodeInfo.version}`\n };\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail;\n this.identify(connection).catch(err => { this.log.error('error during identify trigged by connection:open', err); });\n });\n }\n // When self peer record changes, trigger identify-push\n components.events.addEventListener('self:peer:update', (evt) => {\n void this.push().catch(err => { this.log.error(err); });\n });\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (this.host.agentVersion === `${components.nodeInfo.name}/${components.nodeInfo.version}`) {\n if (isNode || isElectronMain) {\n this.host.agentVersion += ` UserAgent=${globalThis.process.version}`;\n }\n else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n this.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`;\n }\n }\n }\n isStarted() {\n return this.started;\n }\n async start() {\n if (this.started) {\n return;\n }\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: uint8ArrayFromString(this.host.agentVersion),\n ProtocolVersion: uint8ArrayFromString(this.host.protocolVersion)\n }\n });\n await this.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n await this.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxPushIncomingStreams,\n maxOutboundStreams: this.maxPushOutgoingStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.registrar.unhandle(this.identifyProtocolStr);\n await this.registrar.unhandle(this.identifyPushProtocolStr);\n this.started = false;\n }\n /**\n * Send an Identify Push update to the list of connections\n */\n async pushToConnections(connections) {\n const listenAddresses = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code));\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs: listenAddresses\n });\n const signedPeerRecord = await RecordEnvelope.seal(peerRecord, this.peerId);\n const supportedProtocols = this.registrar.getProtocols();\n const peer = await this.peerStore.get(this.peerId);\n const agentVersion = uint8ArrayToString(peer.metadata.get('AgentVersion') ?? uint8ArrayFromString(this.host.agentVersion));\n const protocolVersion = uint8ArrayToString(peer.metadata.get('ProtocolVersion') ?? uint8ArrayFromString(this.host.protocolVersion));\n const pushes = connections.map(async (connection) => {\n let stream;\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n try {\n stream = await connection.newStream(this.identifyPushProtocolStr, {\n signal,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage);\n await pb.write({\n listenAddrs: listenAddresses.map(ma => ma.bytes),\n signedPeerRecord: signedPeerRecord.marshal(),\n protocols: supportedProtocols,\n agentVersion,\n protocolVersion\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n // Just log errors\n this.log.error('could not push identify update to peer', err);\n stream?.abort(err);\n }\n });\n await Promise.all(pushes);\n }\n /**\n * Calls `push` on all peer connections\n */\n async push() {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return;\n }\n const connections = [];\n await Promise.all(this.connectionManager.getConnections().map(async (conn) => {\n try {\n const peer = await this.peerStore.get(conn.remotePeer);\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n return;\n }\n connections.push(conn);\n }\n catch (err) {\n if (err.code !== ERR_NOT_FOUND) {\n throw err;\n }\n }\n }));\n await this.pushToConnections(connections);\n }\n async _identify(connection, options = {}) {\n let stream;\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.identifyProtocolStr, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage);\n const message = await pb.read(options);\n await stream.close(options);\n return message;\n }\n catch (err) {\n this.log.error('error while reading identify message', err);\n stream?.abort(err);\n throw err;\n }\n }\n async identify(connection, options = {}) {\n const message = await this._identify(connection, options);\n const { publicKey, protocols, observedAddr } = message;\n if (publicKey == null) {\n throw new CodeError('public key was missing from identify message', 'ERR_MISSING_PUBLIC_KEY');\n }\n const id = await peerIdFromKeys(publicKey);\n if (!connection.remotePeer.equals(id)) {\n throw new CodeError('identified peer does not match the expected peer', 'ERR_INVALID_PEER');\n }\n if (this.peerId.equals(id)) {\n throw new CodeError('identified peer is our own peer id?', 'ERR_INVALID_PEER');\n }\n // Get the observedAddr if there is one\n const cleanObservedAddr = getCleanMultiaddr(observedAddr);\n this.log('identify completed for peer %p and protocols %o', id, protocols);\n this.log('our observed address is %a', cleanObservedAddr);\n if (cleanObservedAddr != null &&\n this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {\n this.log('storing our observed address %a', cleanObservedAddr);\n this.addressManager.addObservedAddr(cleanObservedAddr);\n }\n return this.#consumeIdentifyMessage(connection, message);\n }\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify(data) {\n const { connection, stream } = data;\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n try {\n const publicKey = this.peerId.publicKey ?? new Uint8Array(0);\n const peerData = await this.peerStore.get(this.peerId);\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code));\n let signedPeerRecord = peerData.peerRecordEnvelope;\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs\n });\n const envelope = await RecordEnvelope.seal(peerRecord, this.peerId);\n signedPeerRecord = envelope.marshal().subarray();\n }\n let observedAddr = connection.remoteAddr.bytes;\n if (!IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined;\n }\n const pb = pbStream(stream).pb(IdentifyMessage);\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n this.log.error('could not respond to identify request', err);\n stream.abort(err);\n }\n }\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush(data) {\n const { connection, stream } = data;\n try {\n if (this.peerId.equals(connection.remotePeer)) {\n throw new Error('received push from ourselves?');\n }\n const options = {\n signal: AbortSignal.timeout(this.timeout)\n };\n const pb = pbStream(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(IdentifyMessage);\n const message = await pb.read(options);\n await stream.close(options);\n await this.#consumeIdentifyMessage(connection, message);\n }\n catch (err) {\n this.log.error('received invalid message', err);\n stream.abort(err);\n return;\n }\n this.log('handled push from %p', connection.remotePeer);\n }\n async #consumeIdentifyMessage(connection, message) {\n this.log('received identify from %p', connection.remotePeer);\n if (message == null) {\n throw new CodeError('message was null or undefined', 'ERR_INVALID_MESSAGE');\n }\n const peer = {};\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: multiaddr(buf)\n }));\n }\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols;\n }\n if (message.publicKey != null) {\n peer.publicKey = message.publicKey;\n const peerId = await peerIdFromKeys(message.publicKey);\n if (!peerId.equals(connection.remotePeer)) {\n throw new CodeError('public key did not match remote PeerId', 'ERR_INVALID_PUBLIC_KEY');\n }\n }\n let output;\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n this.log('received signedPeerRecord from %p', connection.remotePeer);\n let peerRecordEnvelope = message.signedPeerRecord;\n const envelope = await RecordEnvelope.openAndCertify(peerRecordEnvelope, PeerRecord.DOMAIN);\n let peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n // Verify peerId\n if (!peerRecord.peerId.equals(envelope.peerId)) {\n throw new CodeError('signing key does not match PeerId in the PeerRecord', 'ERR_INVALID_SIGNING_KEY');\n }\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new CodeError('signing key does not match remote PeerId', 'ERR_INVALID_PEER_RECORD_KEY');\n }\n let existingPeer;\n try {\n existingPeer = await this.peerStore.get(peerRecord.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata;\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n peerRecord = storedRecord;\n peerRecordEnvelope = existingPeer.peerRecordEnvelope;\n }\n }\n }\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope;\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }));\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n };\n }\n else {\n this.log('%p did not send a signed peer record', connection.remotePeer);\n }\n this.log('patching %p with', connection.remotePeer, peer);\n await this.peerStore.patch(connection.remotePeer, peer);\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata = {};\n if (message.agentVersion != null) {\n metadata.AgentVersion = uint8ArrayFromString(message.agentVersion);\n }\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = uint8ArrayFromString(message.protocolVersion);\n }\n this.log('merging %p metadata', connection.remotePeer, metadata);\n await this.peerStore.merge(connection.remotePeer, {\n metadata\n });\n }\n const result = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => multiaddr(buf)),\n observedAddr: message.observedAddr == null ? undefined : multiaddr(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n };\n this.events.safeDispatchEvent('peer:identify', { detail: result });\n return result;\n }\n}\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nfunction getCleanMultiaddr(addr) {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr);\n }\n catch {\n }\n }\n}\n//# sourceMappingURL=identify.js.map","/**\n * @packageDocumentation\n *\n * Use the `identify` function to add support for the [Identify protocol](https://github.com/libp2p/specs/blob/master/identify/README.md) to libp2p.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identify: identify()\n * }\n * })\n * ```\n */\nimport { MULTICODEC_IDENTIFY, MULTICODEC_IDENTIFY_PUSH } from './consts.js';\nimport { Identify as IdentifyClass } from './identify.js';\n/**\n * The protocols the Identify service supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n};\nexport function identify(init = {}) {\n return (components) => new IdentifyClass(components, init);\n}\n//# sourceMappingURL=index.js.map","import { getIterator } from 'get-iterator';\nimport { isPromise } from './is-promise.js';\nexport function closeSource(source, log) {\n const res = getIterator(source).return?.();\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err);\n });\n }\n}\n//# sourceMappingURL=close-source.js.map","export function getIterator(obj) {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]();\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]();\n }\n if (typeof obj.next === 'function') {\n return obj; // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable');\n}\n//# sourceMappingURL=index.js.map","export function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=is-promise.js.map","// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15\nconst randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);\n\nconst createAbortError = () => {\n\tconst error = new Error('Delay aborted');\n\terror.name = 'AbortError';\n\treturn error;\n};\n\nconst clearMethods = new WeakMap();\n\nexport function createDelay({clearTimeout: defaultClear, setTimeout: defaultSet} = {}) {\n\t// We cannot use `async` here as we need the promise identity.\n\treturn (milliseconds, {value, signal} = {}) => {\n\t\t// TODO: Use `signal?.throwIfAborted()` when targeting Node.js 18.\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(createAbortError());\n\t\t}\n\n\t\tlet timeoutId;\n\t\tlet settle;\n\t\tlet rejectFunction;\n\t\tconst clear = defaultClear ?? clearTimeout;\n\n\t\tconst signalListener = () => {\n\t\t\tclear(timeoutId);\n\t\t\trejectFunction(createAbortError());\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t\t}\n\t\t};\n\n\t\tconst delayPromise = new Promise((resolve, reject) => {\n\t\t\tsettle = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t};\n\n\t\t\trejectFunction = reject;\n\t\t\ttimeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);\n\t\t});\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t\t}\n\n\t\tclearMethods.set(delayPromise, () => {\n\t\t\tclear(timeoutId);\n\t\t\ttimeoutId = null;\n\t\t\tsettle();\n\t\t});\n\n\t\treturn delayPromise;\n\t};\n}\n\nconst delay = createDelay();\n\nexport default delay;\n\nexport async function rangeDelay(minimum, maximum, options = {}) {\n\treturn delay(randomInteger(minimum, maximum), options);\n}\n\nexport function clearDelay(promise) {\n\tclearMethods.get(promise)?.();\n}\n","import { CodeError } from '@libp2p/interface';\nimport delay from 'delay';\nexport class RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await delay(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nclass MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map","export var MessageTypes;\n(function (MessageTypes) {\n MessageTypes[MessageTypes[\"NEW_STREAM\"] = 0] = \"NEW_STREAM\";\n MessageTypes[MessageTypes[\"MESSAGE_RECEIVER\"] = 1] = \"MESSAGE_RECEIVER\";\n MessageTypes[MessageTypes[\"MESSAGE_INITIATOR\"] = 2] = \"MESSAGE_INITIATOR\";\n MessageTypes[MessageTypes[\"CLOSE_RECEIVER\"] = 3] = \"CLOSE_RECEIVER\";\n MessageTypes[MessageTypes[\"CLOSE_INITIATOR\"] = 4] = \"CLOSE_INITIATOR\";\n MessageTypes[MessageTypes[\"RESET_RECEIVER\"] = 5] = \"RESET_RECEIVER\";\n MessageTypes[MessageTypes[\"RESET_INITIATOR\"] = 6] = \"RESET_INITIATOR\";\n})(MessageTypes || (MessageTypes = {}));\nexport const MessageTypeNames = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n});\nexport const InitiatorMessageTypes = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n});\nexport const ReceiverMessageTypes = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n});\n//# sourceMappingURL=message-types.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { MessageTypeNames, MessageTypes } from './message-types.js';\nexport const MAX_MSG_SIZE = 1 << 20; // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20; // 4MB\nexport class Decoder {\n _buffer;\n _headerInfo;\n _maxMessageSize;\n _maxUnprocessedMessageQueueSize;\n constructor(maxMessageSize = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList();\n this._headerInfo = null;\n this._maxMessageSize = maxMessageSize;\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize;\n }\n write(chunk) {\n if (chunk == null || chunk.length === 0) {\n return [];\n }\n this._buffer.append(chunk);\n if (this._buffer.byteLength > this._maxUnprocessedMessageQueueSize) {\n throw Object.assign(new Error('unprocessed message queue size too large!'), { code: 'ERR_MSG_QUEUE_TOO_BIG' });\n }\n const msgs = [];\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer);\n }\n catch (err) {\n if (err.code === 'ERR_MSG_TOO_BIG') {\n throw err;\n }\n break; // We haven't received enough data yet\n }\n }\n const { id, type, length, offset } = this._headerInfo;\n const bufferedDataLength = this._buffer.length - offset;\n if (bufferedDataLength < length) {\n break; // not enough data yet\n }\n const msg = {\n id,\n type\n };\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.sublist(offset, offset + length);\n }\n msgs.push(msg);\n this._buffer.consume(offset + length);\n this._headerInfo = null;\n }\n return msgs;\n }\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader(data) {\n const { value: h, offset } = readVarInt(data);\n const { value: length, offset: end } = readVarInt(data, offset);\n const type = h & 7;\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`);\n }\n // test message type varint + data length\n if (length > this._maxMessageSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' });\n }\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length };\n }\n}\nconst MSB = 0x80;\nconst REST = 0x7F;\nfunction readVarInt(buf, offset = 0) {\n let res = 0;\n let shift = 0;\n let counter = offset;\n let b;\n const l = buf.length;\n do {\n if (counter >= l || shift > 49) {\n offset = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf.get(counter++);\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB);\n offset = counter - offset;\n return {\n value: res,\n offset\n };\n}\n//# sourceMappingURL=decode.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { MessageTypes } from './message-types.js';\nconst POOL_SIZE = 10 * 1024;\nclass Encoder {\n _pool;\n _poolOffset;\n constructor() {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n /**\n * Encodes the given message and adds it to the passed list\n */\n write(msg, list) {\n const pool = this._pool;\n let offset = this._poolOffset;\n varint.encode(msg.id << 3 | msg.type, pool, offset);\n offset += varint.encodingLength(msg.id << 3 | msg.type);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset);\n offset += varint.encodingLength(msg.data.length);\n }\n else {\n varint.encode(0, pool, offset);\n offset += varint.encodingLength(0);\n }\n const header = pool.subarray(this._poolOffset, offset);\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n else {\n this._poolOffset = offset;\n }\n list.append(header);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n list.append(msg.data);\n }\n }\n}\nconst encoder = new Encoder();\n/**\n * Encode and yield one or more messages\n */\nexport async function* encode(source) {\n for await (const message of source) {\n const list = new Uint8ArrayList();\n encoder.write(message, list);\n yield list;\n }\n}\n//# sourceMappingURL=encode.js.map","import { CodeError } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport defer, {} from 'p-defer';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { closeSource } from './close-source.js';\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET';\nconst ERR_SINK_INVALID_STATE = 'ERR_SINK_INVALID_STATE';\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000;\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\nexport class AbstractStream {\n id;\n direction;\n timeline;\n protocol;\n metadata;\n source;\n status;\n readStatus;\n writeStatus;\n log;\n sinkController;\n sinkEnd;\n closed;\n endErr;\n streamSource;\n onEnd;\n onCloseRead;\n onCloseWrite;\n onReset;\n onAbort;\n sendCloseWriteTimeout;\n sendingData;\n constructor(init) {\n this.sinkController = new AbortController();\n this.sinkEnd = defer();\n this.closed = defer();\n this.log = init.log;\n // stream status\n this.status = 'open';\n this.readStatus = 'ready';\n this.writeStatus = 'ready';\n this.id = init.id;\n this.metadata = init.metadata ?? {};\n this.direction = init.direction;\n this.timeline = {\n open: Date.now()\n };\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT;\n this.onEnd = init.onEnd;\n this.onCloseRead = init?.onCloseRead;\n this.onCloseWrite = init?.onCloseWrite;\n this.onReset = init?.onReset;\n this.onAbort = init?.onAbort;\n this.source = this.streamSource = pushable({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err);\n }\n else {\n this.log.trace('source ended');\n }\n this.onSourceEnd(err);\n }\n });\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this);\n }\n async sink(source) {\n if (this.writeStatus !== 'ready') {\n throw new CodeError(`writable end state is \"${this.writeStatus}\" not \"ready\"`, ERR_SINK_INVALID_STATE);\n }\n try {\n this.writeStatus = 'writing';\n const options = {\n signal: this.sinkController.signal\n };\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options);\n if (isPromise(res)) {\n await res;\n }\n }\n const abortListener = () => {\n closeSource(source, this.log);\n };\n try {\n this.sinkController.signal.addEventListener('abort', abortListener);\n this.log.trace('sink reading from source');\n for await (let data of source) {\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data;\n const res = this.sendData(data, options);\n if (isPromise(res)) {\n this.sendingData = pDefer();\n await res;\n this.sendingData.resolve();\n this.sendingData = undefined;\n }\n }\n }\n finally {\n this.sinkController.signal.removeEventListener('abort', abortListener);\n }\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus);\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing';\n this.log.trace('send close write to remote');\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n });\n this.writeStatus = 'closed';\n }\n this.onSinkEnd();\n }\n catch (err) {\n this.log.trace('sink ended with error, calling abort with error', err);\n this.abort(err);\n throw err;\n }\n finally {\n this.log.trace('resolve sink end');\n this.sinkEnd.resolve();\n }\n }\n onSourceEnd(err) {\n if (this.timeline.closeRead != null) {\n return;\n }\n this.timeline.closeRead = Date.now();\n this.readStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseRead?.();\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('source ended, waiting for sink to end');\n }\n }\n onSinkEnd(err) {\n if (this.timeline.closeWrite != null) {\n return;\n }\n this.timeline.closeWrite = Date.now();\n this.writeStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseWrite?.();\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('sink ended, waiting for source to end');\n }\n }\n // Close for both Reading and Writing\n async close(options) {\n this.log.trace('closing gracefully');\n this.status = 'closing';\n // wait for read and write ends to close\n await raceSignal(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal);\n this.status = 'closed';\n this.log.trace('closed gracefully');\n }\n async closeRead(options = {}) {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return;\n }\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus);\n const readStatus = this.readStatus;\n this.readStatus = 'closing';\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote');\n await this.sendCloseRead(options);\n }\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength);\n this.streamSource.end();\n }\n this.log.trace('closed readable end of stream');\n }\n async closeWrite(options = {}) {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return;\n }\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus);\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array');\n await raceSignal(this.sink([]), options.signal);\n }\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await raceSignal(this.sendingData.promise, options.signal);\n }\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink');\n this.sinkController.abort();\n await raceSignal(this.sinkEnd.promise, options.signal);\n }\n this.writeStatus = 'closed';\n this.log.trace('closed writable end of stream');\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n this.log('abort with error', err);\n // try to send a reset message\n this.log('try to send reset to remote');\n const res = this.sendReset();\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err);\n });\n }\n this.status = 'aborted';\n this.timeline.abort = Date.now();\n this._closeSinkAndSource(err);\n this.onAbort?.(err);\n }\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n const err = new CodeError('stream reset', ERR_STREAM_RESET);\n this.status = 'reset';\n this.timeline.reset = Date.now();\n this._closeSinkAndSource(err);\n this.onReset?.();\n }\n _closeSinkAndSource(err) {\n this._closeSink(err);\n this._closeSource(err);\n }\n _closeSink(err) {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source');\n this.sinkController.abort();\n }\n this.onSinkEnd(err);\n }\n _closeSource(err) {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength);\n this.readStatus = 'closing';\n this.streamSource.end(err);\n }\n }\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite() {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed');\n return;\n }\n this.log.trace('remote close write');\n this._closeSource();\n }\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead() {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed');\n return;\n }\n this.log.trace('remote close read');\n this._closeSink();\n }\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed');\n return;\n }\n this.log.trace('stream destroyed');\n this._closeSinkAndSource();\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush(data) {\n this.streamSource.push(data);\n }\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength() {\n return this.streamSource.readableLength;\n }\n}\n//# sourceMappingURL=abstract-stream.js.map","import { AbstractStream } from '@libp2p/utils/abstract-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_MSG_SIZE } from './decode.js';\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js';\nexport class MplexStream extends AbstractStream {\n name;\n streamId;\n send;\n types;\n maxDataSize;\n constructor(init) {\n super(init);\n this.types = init.direction === 'outbound' ? InitiatorMessageTypes : ReceiverMessageTypes;\n this.send = init.send;\n this.name = init.name;\n this.streamId = init.streamId;\n this.maxDataSize = init.maxDataSize;\n }\n async sendNewStream() {\n await this.send({ id: this.streamId, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(this.name)) });\n }\n async sendData(data) {\n data = data.sublist();\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize);\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n });\n data.consume(toSend);\n }\n }\n async sendReset() {\n await this.send({ id: this.streamId, type: this.types.RESET });\n }\n async sendCloseWrite() {\n await this.send({ id: this.streamId, type: this.types.CLOSE });\n }\n async sendCloseRead() {\n // mplex does not support close read, only close write\n }\n}\nexport function createStream(options) {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options;\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name == null ? id : name}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n });\n}\n//# sourceMappingURL=stream.js.map","import { CodeError } from '@libp2p/interface';\nimport { closeSource } from '@libp2p/utils/close-source';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { pipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nimport { toString as uint8ArrayToString } from 'uint8arrays';\nimport { Decoder } from './decode.js';\nimport { encode } from './encode.js';\nimport { MessageTypes, MessageTypeNames } from './message-types.js';\nimport { createStream } from './stream.js';\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB\nconst DISCONNECT_THRESHOLD = 5;\nconst CLOSE_TIMEOUT = 500;\nfunction printMessage(msg) {\n const output = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n };\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray());\n }\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16');\n }\n return output;\n}\nexport class MplexStreamMuxer {\n protocol = '/mplex/6.7.0';\n sink;\n source;\n log;\n _streamId;\n _streams;\n _init;\n _source;\n closeController;\n rateLimiter;\n closeTimeout;\n logger;\n constructor(components, init) {\n init = init ?? {};\n this.log = components.logger.forComponent('libp2p:mplex');\n this.logger = components.logger;\n this._streamId = 0;\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n };\n this._init = init;\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT;\n /**\n * An iterable sink\n */\n this.sink = this._createSink();\n /**\n * An iterable source\n */\n this._source = pushable({\n objectMode: true,\n onEnd: () => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy();\n }\n for (const stream of this._streams.receivers.values()) {\n stream.destroy();\n }\n }\n });\n this.source = pipe(this._source, source => encode(source));\n /**\n * Close controller\n */\n this.closeController = new AbortController();\n this.rateLimiter = new RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n });\n }\n /**\n * Returns a Map of streams and their ids\n */\n get streams() {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams = [];\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream);\n }\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream);\n }\n return streams;\n }\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream(name) {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed');\n }\n const id = this._streamId++;\n name = name == null ? id.toString() : name.toString();\n const registry = this._streams.initiators;\n return this._newStream({ id, name, type: 'initiator', registry });\n }\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close(options) {\n if (this.closeController.signal.aborted) {\n return;\n }\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout);\n try {\n // try to gracefully close all streams\n await Promise.all(this.streams.map(async (s) => s.close({\n signal\n })));\n this._source.end();\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n });\n this.closeController.abort();\n }\n catch (err) {\n this.abort(err);\n }\n }\n abort(err) {\n if (this.closeController.signal.aborted) {\n return;\n }\n this.streams.forEach(s => { s.abort(err); });\n this.closeController.abort(err);\n }\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream(options) {\n const { id, name } = options;\n const registry = this._streams.receivers;\n return this._newStream({ id, name, type: 'receiver', registry });\n }\n _newStream(options) {\n const { id, name, type, registry } = options;\n this.log('new %s stream %s', type, id);\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS');\n }\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`);\n }\n const send = async (msg) => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg));\n }\n this._source.push(msg);\n };\n const onEnd = () => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);\n registry.delete(id);\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream);\n }\n };\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });\n registry.set(id, stream);\n return stream;\n }\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink() {\n const sink = async (source) => {\n const abortListener = () => {\n closeSource(source, this.log);\n };\n this.closeController.signal.addEventListener('abort', abortListener);\n try {\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg);\n }\n }\n this._source.end();\n }\n catch (err) {\n this.log('error in sink', err);\n this._source.end(err); // End the source with an error\n }\n finally {\n this.closeController.signal.removeEventListener('abort', abortListener);\n }\n };\n return sink;\n }\n async _handleIncoming(message) {\n const { id, type } = message;\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message));\n }\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open');\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n });\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1);\n }\n catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'));\n return;\n }\n return;\n }\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) });\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream);\n }\n return;\n }\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;\n const stream = list.get(id);\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, MessageTypeNames[type]);\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1);\n }\n catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'));\n return;\n }\n return;\n }\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE;\n try {\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n });\n // Inform the stream consumer they are not fast enough\n throw new CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL');\n }\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data);\n break;\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite();\n break;\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset();\n break;\n default:\n this.log('unknown message type %s', type);\n }\n }\n catch (err) {\n this.log.error('error while processing message', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=mplex.js.map","/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\nimport { MplexStreamMuxer } from './mplex.js';\nclass Mplex {\n protocol = '/mplex/6.7.0';\n _init;\n components;\n constructor(components, init = {}) {\n this.components = components;\n this._init = init;\n }\n createStreamMuxer(init = {}) {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n });\n }\n}\nexport function mplex(init = {}) {\n return (components) => new Mplex(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Return the first value in an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import first from 'it-first'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const res = first(values)\n *\n * console.info(res) // 0\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import first from 'it-first'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const res = await first(values())\n *\n * console.info(res) // 0\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction first(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n })();\n }\n for (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n}\nexport default first;\n//# sourceMappingURL=index.js.map","export const PING_PROTOCOL = '/ipfs/ping/1.0.0';\nexport const PING_LENGTH = 32;\nexport const PROTOCOL_VERSION = '1.0.0';\nexport const PROTOCOL_NAME = 'ping';\nexport const PROTOCOL_PREFIX = 'ipfs';\nexport const TIMEOUT = 10000;\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2;\nexport const MAX_OUTBOUND_STREAMS = 1;\nexport const ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK';\n//# sourceMappingURL=constants.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { CodeError, ERR_TIMEOUT } from '@libp2p/interface';\nimport first from 'it-first';\nimport { pipe } from 'it-pipe';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS, ERR_WRONG_PING_ACK } from './constants.js';\nexport class PingService {\n protocol;\n components;\n started;\n timeout;\n maxInboundStreams;\n maxOutboundStreams;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.components = components;\n this.log = components.logger.forComponent('libp2p:ping');\n this.started = false;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? TIMEOUT;\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS;\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS;\n this.runOnTransientConnection = init.runOnTransientConnection ?? true;\n this.handleMessage = this.handleMessage.bind(this);\n }\n async start() {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.components.registrar.unhandle(this.protocol);\n this.started = false;\n }\n isStarted() {\n return this.started;\n }\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage(data) {\n this.log('incoming ping from %p', data.connection.remotePeer);\n const { stream } = data;\n const start = Date.now();\n void pipe(stream, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);\n })\n .finally(() => {\n const ms = Date.now() - start;\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms);\n });\n }\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping(peer, options = {}) {\n this.log('pinging %p', peer);\n const start = Date.now();\n const data = randomBytes(PING_LENGTH);\n const connection = await this.components.connectionManager.openConnection(peer, options);\n let stream;\n let onAbort = () => { };\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n onAbort = () => {\n stream?.abort(new CodeError('ping timeout', ERR_TIMEOUT));\n };\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true });\n const result = await pipe([data], stream, async (source) => first(source));\n const ms = Date.now() - start;\n if (result == null) {\n throw new CodeError(`Did not receive a ping ack after ${ms}ms`, ERR_WRONG_PING_ACK);\n }\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new CodeError(`Received wrong ping ack after ${ms}ms`, ERR_WRONG_PING_ACK);\n }\n this.log('ping %p complete in %dms', connection.remotePeer, ms);\n return ms;\n }\n catch (err) {\n this.log.error('error while pinging %p', connection.remotePeer, err);\n stream?.abort(err);\n throw err;\n }\n finally {\n options.signal?.removeEventListener('abort', onAbort);\n if (stream != null) {\n await stream.close();\n }\n }\n }\n}\n//# sourceMappingURL=ping.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\nimport { PingService as PingServiceClass } from './ping.js';\nexport function ping(init = {}) {\n return (components) => new PingServiceClass(components, init);\n}\nexport { PING_PROTOCOL } from './constants.js';\n//# sourceMappingURL=index.js.map","export const transportSymbol = Symbol.for('@libp2p/transport');\nexport function isTransport(other) {\n return other != null && Boolean(other[transportSymbol]);\n}\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport var FaultTolerance;\n(function (FaultTolerance) {\n /**\n * should be used for failing in any listen circumstance\n */\n FaultTolerance[FaultTolerance[\"FATAL_ALL\"] = 0] = \"FATAL_ALL\";\n /**\n * should be used for not failing when not listening\n */\n FaultTolerance[FaultTolerance[\"NO_FATAL\"] = 1] = \"NO_FATAL\";\n})(FaultTolerance || (FaultTolerance = {}));\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\nimport { multiaddr, protocols } from '@multiformats/multiaddr';\nconst ASSUME_HTTP_CODES = [\n protocols('tcp').code,\n protocols('dns').code,\n protocols('dnsaddr').code,\n protocols('dns4').code,\n protocols('dns6').code\n];\nfunction extractSNI(ma) {\n let sniProtoCode;\n try {\n sniProtoCode = protocols('sni').code;\n }\n catch (e) {\n // No SNI protocol in multiaddr\n return null;\n }\n for (const [proto, value] of ma) {\n if (proto === sniProtoCode && value !== undefined) {\n return value;\n }\n }\n return null;\n}\nfunction hasTLS(ma) {\n return ma.some(([proto, _]) => proto === protocols('tls').code);\n}\nfunction interpretNext(headProtoCode, headProtoVal, restMa) {\n const interpreter = interpreters[protocols(headProtoCode).name];\n if (interpreter === undefined) {\n throw new Error(`Can't interpret protocol ${protocols(headProtoCode).name}`);\n }\n const restVal = interpreter(headProtoVal, restMa);\n if (headProtoCode === protocols('ip6').code) {\n return `[${restVal}]`;\n }\n return restVal;\n}\nconst interpreters = {\n ip4: (value, restMa) => value,\n ip6: (value, restMa) => {\n if (restMa.length === 0) {\n return value;\n }\n return `[${value}]`;\n },\n tcp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n udp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n dnsaddr: (value, restMa) => value,\n dns4: (value, restMa) => value,\n dns6: (value, restMa) => value,\n dns: (value, restMa) => value,\n ipfs: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/ipfs/${value}`;\n },\n p2p: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p/${value}`;\n },\n http: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `https://${sni}`;\n }\n const protocol = maHasTLS ? 'https://' : 'http://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n 'http-path': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n const baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n const decodedValue = decodeURIComponent(value);\n return `${baseVal}/${decodedValue}`;\n },\n tls: (value, restMa) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n sni: (value, restMa) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n https: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `https://${baseVal}`;\n },\n ws: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `wss://${sni}`;\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n wss: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `wss://${baseVal}`;\n },\n 'p2p-websocket-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-websocket-star`;\n },\n 'p2p-webrtc-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-star`;\n },\n 'p2p-webrtc-direct': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-direct`;\n }\n};\nexport function multiaddrToUri(input, opts) {\n const ma = multiaddr(input);\n const parts = ma.stringTuples();\n const head = parts.pop();\n if (head === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n const protocol = protocols(head[0]);\n const interpreter = interpreters[protocol.name];\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`);\n }\n let uri = interpreter(head[1] ?? '', parts);\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '');\n if (head[1] === '443') {\n uri = `https://${uri}`;\n }\n else {\n uri = `http://${uri}`;\n }\n }\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString();\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1);\n }\n }\n return uri;\n}\n//# sourceMappingURL=index.js.map","export default async (socket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed');\n }\n // if open, return\n if (socket.readyState === 1) {\n return;\n }\n await new Promise((resolve, reject) => {\n function cleanup() {\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('error', handleErr);\n }\n function handleOpen() {\n cleanup();\n resolve();\n }\n function handleErr(event) {\n cleanup();\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`));\n }\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('error', handleErr);\n });\n};\n//# sourceMappingURL=ready.js.map","import ready from './ready.js';\nexport default (socket, options) => {\n options = options ?? {};\n options.closeOnEnd = options.closeOnEnd !== false;\n const sink = async (source) => {\n for await (const data of source) {\n try {\n await ready(socket);\n }\n catch (err) {\n if (err.message === 'socket closed')\n break;\n throw err;\n }\n // the ready promise resolved without error but the socket was closing so\n // exit the loop and don't send data\n if (socket.readyState === socket.CLOSING || socket.readyState === socket.CLOSED) {\n break;\n }\n socket.send(data);\n }\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve();\n }\n else {\n const err = Object.assign(new Error('ws error'), { event });\n reject(err);\n }\n });\n setTimeout(() => { socket.close(); });\n });\n }\n };\n return sink;\n};\n//# sourceMappingURL=sink.js.map","import { EventIterator } from 'event-iterator';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer(obj) {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number');\n}\nexport default (socket) => {\n socket.binaryType = 'arraybuffer';\n const connected = async () => {\n await new Promise((resolve, reject) => {\n if (isConnected) {\n resolve();\n return;\n }\n if (connError != null) {\n reject(connError);\n return;\n }\n const cleanUp = (cont) => {\n socket.removeEventListener('open', onOpen);\n socket.removeEventListener('error', onError);\n cont();\n };\n const onOpen = () => { cleanUp(resolve); };\n const onError = (event) => {\n cleanUp(() => { reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)); });\n };\n socket.addEventListener('open', onOpen);\n socket.addEventListener('error', onError);\n });\n };\n const source = (async function* () {\n const messages = new EventIterator(({ push, stop, fail }) => {\n const onMessage = (event) => {\n let data = null;\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data);\n }\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data);\n }\n if (event.data instanceof Uint8Array) {\n data = event.data;\n }\n if (data == null) {\n return;\n }\n push(data);\n };\n const onError = (event) => { fail(event.error ?? new Error('Socket error')); };\n socket.addEventListener('message', onMessage);\n socket.addEventListener('error', onError);\n socket.addEventListener('close', stop);\n return () => {\n socket.removeEventListener('message', onMessage);\n socket.removeEventListener('error', onError);\n socket.removeEventListener('close', stop);\n };\n }, { highWaterMark: Infinity });\n await connected();\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk;\n }\n }());\n let isConnected = socket.readyState === 1;\n let connError;\n socket.addEventListener('open', () => {\n isConnected = true;\n connError = null;\n });\n socket.addEventListener('close', () => {\n isConnected = false;\n connError = null;\n });\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`);\n }\n });\n return Object.assign(source, {\n connected\n });\n};\n//# sourceMappingURL=source.js.map","/* eslint-env browser */\nexport default WebSocket;\n//# sourceMappingURL=web-socket.browser.js.map","const map = { 'http:': 'ws:', 'https:': 'wss:' };\nconst defaultProtocol = 'ws:';\nexport default (url, location) => {\n if (url.startsWith('//')) {\n url = `${location?.protocol ?? defaultProtocol}${url}`;\n }\n if (url.startsWith('/') && location != null) {\n const proto = location.protocol ?? defaultProtocol;\n const host = location.host;\n const port = location.port != null && host?.endsWith(`:${location.port}`) !== true ? `:${location.port}` : '';\n url = `${proto}//${host}${port}${url}`;\n }\n const wsUrl = new URL(url);\n for (const [httpProto, wsProto] of Object.entries(map)) {\n if (wsUrl.protocol === httpProto) {\n wsUrl.protocol = wsProto;\n }\n }\n return wsUrl;\n};\n//# sourceMappingURL=ws-url.js.map","// load websocket library if we are not in the browser\nimport duplex from './duplex.js';\nimport WebSocket from './web-socket.js';\nimport wsurl from './ws-url.js';\nexport function connect(addr, opts) {\n const location = typeof window === 'undefined' ? undefined : window.location;\n opts = opts ?? {};\n const url = wsurl(addr, location);\n // it's necessary to stringify the URL object otherwise react-native crashes\n const socket = new WebSocket(url.toString(), opts.websocket);\n return duplex(socket, opts);\n}\n//# sourceMappingURL=client.js.map","import sink from './sink.js';\nimport source from './source.js';\nexport default (socket, options) => {\n options = options ?? {};\n const connectedSource = source(socket);\n let remoteAddress = options.remoteAddress;\n let remotePort = options.remotePort;\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url);\n remoteAddress = url.hostname;\n remotePort = parseInt(url.port, 10);\n }\n catch { }\n }\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port');\n }\n const duplex = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => { await connectedSource.connected(); },\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve();\n });\n socket.close();\n });\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate();\n }\n else {\n socket.close();\n }\n },\n remoteAddress,\n remotePort,\n socket\n };\n return duplex;\n};\n//# sourceMappingURL=duplex.js.map","// p2p multi-address code\nexport const CODE_P2P = 421;\nexport const CODE_CIRCUIT = 290;\nexport const CODE_TCP = 6;\nexport const CODE_WS = 477;\nexport const CODE_WSS = 478;\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 500;\n//# sourceMappingURL=constants.js.map","import * as mafmt from '@multiformats/mafmt';\nimport { CODE_CIRCUIT, CODE_P2P, CODE_TCP, CODE_WS, CODE_WSS } from './constants.js';\nexport function all(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa);\n });\n}\nexport function wss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSocketsSecure.matches(testMa);\n });\n}\nexport function dnsWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS));\n });\n}\nexport function dnsWsOrWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS));\n }\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS));\n });\n}\n//# sourceMappingURL=filters.js.map","/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/9090/ws')\n * await node.dial(ma)\n * ```\n *\n * ## Filters\n *\n * When run in a browser by default this module will only connect to secure web socket addresses.\n *\n * To change this you should pass a filter to the factory function.\n *\n * You can create your own address filters for this transports, or rely in the filters [provided](./src/filters.js).\n *\n * The available filters are:\n *\n * - `filters.all`\n * - Returns all TCP and DNS based addresses, both with `ws` or `wss`.\n * - `filters.dnsWss`\n * - Returns all DNS based addresses with `wss`.\n * - `filters.dnsWsOrWss`\n * - Returns all DNS based addresses, both with `ws` or `wss`.\n *\n * @example Allow dialing insecure WebSockets\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import * as filters from '@libp2p/websockets/filters'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets({\n * // connect to all sockets, even insecure ones\n * filter: filters.all\n * })\n * ]\n * })\n * ```\n */\nimport { AbortError, CodeError } from '@libp2p/interface';\nimport { transportSymbol } from '@libp2p/interface';\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri';\nimport { connect } from 'it-ws/client';\nimport pDefer from 'p-defer';\nimport { isBrowser, isWebWorker } from 'wherearewe';\nimport * as filters from './filters.js';\nimport { createListener } from './listener.js';\nimport { socketToMaConn } from './socket-to-conn.js';\nclass WebSockets {\n log;\n init;\n logger;\n constructor(components, init) {\n this.log = components.logger.forComponent('libp2p:websockets');\n this.logger = components.logger;\n this.init = init;\n }\n [Symbol.toStringTag] = '@libp2p/websockets';\n [transportSymbol] = true;\n async dial(ma, options) {\n this.log('dialing %s', ma);\n options = options ?? {};\n const socket = await this._connect(ma, options);\n const maConn = socketToMaConn(socket, ma, {\n logger: this.logger\n });\n this.log('new outbound connection %s', maConn.remoteAddr);\n const conn = await options.upgrader.upgradeOutbound(maConn);\n this.log('outbound connection %s upgraded', maConn.remoteAddr);\n return conn;\n }\n async _connect(ma, options) {\n if (options?.signal?.aborted === true) {\n throw new AbortError();\n }\n const cOpts = ma.toOptions();\n this.log('dialing %s:%s', cOpts.host, cOpts.port);\n const errorPromise = pDefer();\n const rawSocket = connect(toUri(ma), this.init);\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new CodeError(`Could not connect to ${ma.toString()}`, 'ERR_CONNECTION_FAILED');\n this.log.error('connection error:', err);\n errorPromise.reject(err);\n });\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise]);\n this.log('connected %s', ma);\n return rawSocket;\n }\n // Allow abort via signal during connect\n let onAbort;\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError());\n rawSocket.close().catch(err => {\n this.log.error('error closing raw socket', err);\n });\n };\n // Already aborted?\n if (options?.signal?.aborted === true) {\n onAbort();\n return;\n }\n options?.signal?.addEventListener('abort', onAbort);\n });\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()]);\n }\n finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort);\n }\n }\n this.log('connected %s', ma);\n return rawSocket;\n }\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener(options) {\n return createListener({\n logger: this.logger\n }, {\n ...this.init,\n ...options\n });\n }\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n listenFilter(multiaddrs) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs];\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs);\n }\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.wss(multiaddrs);\n }\n return filters.all(multiaddrs);\n }\n /**\n * Filter check for all Multiaddrs that this transport can dial\n */\n dialFilter(multiaddrs) {\n return this.listenFilter(multiaddrs);\n }\n}\nexport function webSockets(init = {}) {\n return (components) => {\n return new WebSockets(components, init);\n };\n}\n//# sourceMappingURL=index.js.map","import { CodeError } from '@libp2p/interface';\nimport { CLOSE_TIMEOUT } from './constants.js';\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn(stream, remoteAddr, options) {\n const log = options.logger.forComponent('libp2p:websockets:maconn');\n const maConn = {\n log,\n async sink(source) {\n try {\n await stream.sink((async function* () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf;\n }\n else {\n yield buf.subarray();\n }\n }\n })());\n }\n catch (err) {\n if (err.type !== 'aborted') {\n log.error(err);\n }\n }\n },\n source: stream.source,\n remoteAddr,\n timeline: { open: Date.now() },\n async close(options = {}) {\n const start = Date.now();\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n options = {\n ...options,\n signal\n };\n }\n const listener = () => {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s after %dms, destroying it manually', host, port, Date.now() - start);\n this.abort(new CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'));\n };\n options.signal?.addEventListener('abort', listener);\n try {\n await stream.close();\n }\n catch (err) {\n log.error('error closing WebSocket gracefully', err);\n this.abort(err);\n }\n finally {\n options.signal?.removeEventListener('abort', listener);\n maConn.timeline.close = Date.now();\n }\n },\n abort(err) {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s due to error', host, port, err);\n stream.destroy();\n maConn.timeline.close = Date.now();\n }\n };\n stream.socket.addEventListener('close', () => {\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now();\n }\n }, { once: true });\n return maConn;\n}\n//# sourceMappingURL=socket-to-conn.js.map","export function createListener() {\n throw new Error('WebSocket Servers can not be created in the browser!');\n}\n//# sourceMappingURL=listener.browser.js.map","/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign';\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign';\nexport var TopicValidatorResult;\n(function (TopicValidatorResult) {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n TopicValidatorResult[\"Accept\"] = \"accept\";\n /**\n * The message is neither delivered nor forwarded to the network\n */\n TopicValidatorResult[\"Ignore\"] = \"ignore\";\n /**\n * The message is considered invalid, and it should be rejected\n */\n TopicValidatorResult[\"Reject\"] = \"reject\";\n})(TopicValidatorResult || (TopicValidatorResult = {}));\n//# sourceMappingURL=index.js.map","export const second = 1000;\nexport const minute = 60 * second;\n// Protocol identifiers\nexport const FloodsubID = '/floodsub/1.0.0';\n/**\n * The protocol ID for version 1.0.0 of the Gossipsub protocol\n * It is advertised along with GossipsubIDv11 for backwards compatability\n */\nexport const GossipsubIDv10 = '/meshsub/1.0.0';\n/**\n * The protocol ID for version 1.1.0 of the Gossipsub protocol\n * See the spec for details about how v1.1.0 compares to v1.0.0:\n * https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md\n */\nexport const GossipsubIDv11 = '/meshsub/1.1.0';\n// Overlay parameters\n/**\n * GossipsubD sets the optimal degree for a Gossipsub topic mesh. For example, if GossipsubD == 6,\n * each peer will want to have about six peers in their mesh for each topic they're subscribed to.\n * GossipsubD should be set somewhere between GossipsubDlo and GossipsubDhi.\n */\nexport const GossipsubD = 6;\n/**\n * GossipsubDlo sets the lower bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have fewer than GossipsubDlo peers, we will attempt to graft some more into the mesh at\n * the next heartbeat.\n */\nexport const GossipsubDlo = 4;\n/**\n * GossipsubDhi sets the upper bound on the number of peers we keep in a Gossipsub topic mesh.\n * If we have more than GossipsubDhi peers, we will select some to prune from the mesh at the next heartbeat.\n */\nexport const GossipsubDhi = 12;\n/**\n * GossipsubDscore affects how peers are selected when pruning a mesh due to over subscription.\n * At least GossipsubDscore of the retained peers will be high-scoring, while the remainder are\n * chosen randomly.\n */\nexport const GossipsubDscore = 4;\n/**\n * GossipsubDout sets the quota for the number of outbound connections to maintain in a topic mesh.\n * When the mesh is pruned due to over subscription, we make sure that we have outbound connections\n * to at least GossipsubDout of the survivor peers. This prevents sybil attackers from overwhelming\n * our mesh with incoming connections.\n *\n * GossipsubDout must be set below GossipsubDlo, and must not exceed GossipsubD / 2.\n */\nexport const GossipsubDout = 2;\n// Gossip parameters\n/**\n * GossipsubHistoryLength controls the size of the message cache used for gossip.\n * The message cache will remember messages for GossipsubHistoryLength heartbeats.\n */\nexport const GossipsubHistoryLength = 5;\n/**\n * GossipsubHistoryGossip controls how many cached message ids we will advertise in\n * IHAVE gossip messages. When asked for our seen message IDs, we will return\n * only those from the most recent GossipsubHistoryGossip heartbeats. The slack between\n * GossipsubHistoryGossip and GossipsubHistoryLength allows us to avoid advertising messages\n * that will be expired by the time they're requested.\n *\n * GossipsubHistoryGossip must be less than or equal to GossipsubHistoryLength to\n * avoid a runtime panic.\n */\nexport const GossipsubHistoryGossip = 3;\n/**\n * GossipsubDlazy affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to at least GossipsubDlazy peers outside our mesh. The actual\n * number may be more, depending on GossipsubGossipFactor and how many peers we're\n * connected to.\n */\nexport const GossipsubDlazy = 6;\n/**\n * GossipsubGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to GossipsubGossipFactor * (total number of non-mesh peers), or\n * GossipsubDlazy, whichever is greater.\n */\nexport const GossipsubGossipFactor = 0.25;\n/**\n * GossipsubGossipRetransmission controls how many times we will allow a peer to request\n * the same message id through IWANT gossip before we start ignoring them. This is designed\n * to prevent peers from spamming us with requests and wasting our resources.\n */\nexport const GossipsubGossipRetransmission = 3;\n// Heartbeat interval\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const GossipsubHeartbeatInitialDelay = 100;\n/**\n * GossipsubHeartbeatInterval controls the time between heartbeats.\n */\nexport const GossipsubHeartbeatInterval = second;\n/**\n * GossipsubFanoutTTL controls how long we keep track of the fanout state. If it's been\n * GossipsubFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const GossipsubFanoutTTL = minute;\n/**\n * GossipsubPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to GossipsubPrunePeers other peers that we\n * know of.\n */\nexport const GossipsubPrunePeers = 16;\n/**\n * GossipsubPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of GossipsubPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least GossipsubPruneBackoff\n * before attempting to re-graft.\n */\nexport const GossipsubPruneBackoff = minute;\n/**\n * Backoff to use when unsuscribing from a topic. Should not resubscribe to this topic before it expired.\n */\nexport const GossipsubUnsubscribeBackoff = 10 * second;\n/**\n * GossipsubPruneBackoffTicks is the number of heartbeat ticks for attempting to prune expired\n * backoff timers.\n */\nexport const GossipsubPruneBackoffTicks = 15;\n/**\n * GossipsubConnectors controls the number of active connection attempts for peers obtained through PX.\n */\nexport const GossipsubConnectors = 8;\n/**\n * GossipsubMaxPendingConnections sets the maximum number of pending connections for peers attempted through px.\n */\nexport const GossipsubMaxPendingConnections = 128;\n/**\n * GossipsubConnectionTimeout controls the timeout for connection attempts.\n */\nexport const GossipsubConnectionTimeout = 30 * second;\n/**\n * GossipsubDirectConnectTicks is the number of heartbeat ticks for attempting to reconnect direct peers\n * that are not currently connected.\n */\nexport const GossipsubDirectConnectTicks = 300;\n/**\n * GossipsubDirectConnectInitialDelay is the initial delay before opening connections to direct peers\n */\nexport const GossipsubDirectConnectInitialDelay = second;\n/**\n * GossipsubOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every GossipsubOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const GossipsubOpportunisticGraftTicks = 60;\n/**\n * GossipsubOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const GossipsubOpportunisticGraftPeers = 2;\n/**\n * If a GRAFT comes before GossipsubGraftFloodThreshold has elapsed since the last PRUNE,\n * then there is an extra score penalty applied to the peer through P7.\n */\nexport const GossipsubGraftFloodThreshold = 10 * second;\n/**\n * GossipsubMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const GossipsubMaxIHaveLength = 5000;\n/**\n * GossipsubMaxIHaveMessages is the maximum number of IHAVE messages to accept from a peer within a heartbeat.\n */\nexport const GossipsubMaxIHaveMessages = 10;\n/**\n * Time to wait for a message requested through IWANT following an IHAVE advertisement.\n * If the message is not received within this window, a broken promise is declared and\n * the router may apply bahavioural penalties.\n */\nexport const GossipsubIWantFollowupTime = 3 * second;\n/**\n * Time in milliseconds to keep message ids in the seen cache\n */\nexport const GossipsubSeenTTL = 2 * minute;\nexport const TimeCacheDuration = 120 * 1000;\nexport const ERR_TOPIC_VALIDATOR_REJECT = 'ERR_TOPIC_VALIDATOR_REJECT';\nexport const ERR_TOPIC_VALIDATOR_IGNORE = 'ERR_TOPIC_VALIDATOR_IGNORE';\n/**\n * If peer score is better than this, we accept messages from this peer\n * within ACCEPT_FROM_WHITELIST_DURATION_MS from the last time computing score.\n **/\nexport const ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE = 0;\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept up to this\n * number of messages from that peer.\n */\nexport const ACCEPT_FROM_WHITELIST_MAX_MESSAGES = 128;\n/**\n * If peer score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, accept messages from\n * this peer up to this time duration.\n */\nexport const ACCEPT_FROM_WHITELIST_DURATION_MS = 1000;\n/**\n * The default MeshMessageDeliveriesWindow to be used in metrics.\n */\nexport const DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS = 1000;\n/** Wait for 1 more heartbeats before clearing a backoff */\nexport const BACKOFF_SLACK = 1;\n//# sourceMappingURL=constants.js.map","export const defaultDecodeRpcLimits = {\n maxSubscriptions: Infinity,\n maxMessages: Infinity,\n maxIhaveMessageIDs: Infinity,\n maxIwantMessageIDs: Infinity,\n maxControlMessages: Infinity,\n maxPeerInfos: Infinity\n};\n//# sourceMappingURL=decodeRpc.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { CodeError, decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var RPC;\n(function (RPC) {\n let SubOpts;\n (function (SubOpts) {\n let _codec;\n SubOpts.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscribe != null) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if (obj.topic != null) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n SubOpts.encode = (obj) => {\n return encodeMessage(obj, SubOpts.codec());\n };\n SubOpts.decode = (buf, opts) => {\n return decodeMessage(buf, SubOpts.codec(), opts);\n };\n })(SubOpts = RPC.SubOpts || (RPC.SubOpts = {}));\n let Message;\n (function (Message) {\n let _codec;\n Message.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.from != null) {\n w.uint32(10);\n w.bytes(obj.from);\n }\n if (obj.data != null) {\n w.uint32(18);\n w.bytes(obj.data);\n }\n if (obj.seqno != null) {\n w.uint32(26);\n w.bytes(obj.seqno);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(34);\n w.string(obj.topic);\n }\n if (obj.signature != null) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (obj.key != null) {\n w.uint32(50);\n w.bytes(obj.key);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n topic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.from = reader.bytes();\n break;\n }\n case 2: {\n obj.data = reader.bytes();\n break;\n }\n case 3: {\n obj.seqno = reader.bytes();\n break;\n }\n case 4: {\n obj.topic = reader.string();\n break;\n }\n case 5: {\n obj.signature = reader.bytes();\n break;\n }\n case 6: {\n obj.key = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Message.encode = (obj) => {\n return encodeMessage(obj, Message.codec());\n };\n Message.decode = (buf, opts) => {\n return decodeMessage(buf, Message.codec(), opts);\n };\n })(Message = RPC.Message || (RPC.Message = {}));\n let ControlMessage;\n (function (ControlMessage) {\n let _codec;\n ControlMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.ihave != null) {\n for (const value of obj.ihave) {\n w.uint32(10);\n RPC.ControlIHave.codec().encode(value, w);\n }\n }\n if (obj.iwant != null) {\n for (const value of obj.iwant) {\n w.uint32(18);\n RPC.ControlIWant.codec().encode(value, w);\n }\n }\n if (obj.graft != null) {\n for (const value of obj.graft) {\n w.uint32(26);\n RPC.ControlGraft.codec().encode(value, w);\n }\n }\n if (obj.prune != null) {\n for (const value of obj.prune) {\n w.uint32(34);\n RPC.ControlPrune.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n ihave: [],\n iwant: [],\n graft: [],\n prune: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.ihave != null && obj.ihave.length === opts.limits.ihave) {\n throw new CodeError('decode error - map field \"ihave\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.ihave.push(RPC.ControlIHave.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.iwant != null && obj.iwant.length === opts.limits.iwant) {\n throw new CodeError('decode error - map field \"iwant\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.iwant.push(RPC.ControlIWant.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n if (opts.limits?.graft != null && obj.graft.length === opts.limits.graft) {\n throw new CodeError('decode error - map field \"graft\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.graft.push(RPC.ControlGraft.codec().decode(reader, reader.uint32()));\n break;\n }\n case 4: {\n if (opts.limits?.prune != null && obj.prune.length === opts.limits.prune) {\n throw new CodeError('decode error - map field \"prune\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.prune.push(RPC.ControlPrune.codec().decode(reader, reader.uint32()));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlMessage.encode = (obj) => {\n return encodeMessage(obj, ControlMessage.codec());\n };\n ControlMessage.decode = (buf, opts) => {\n return decodeMessage(buf, ControlMessage.codec(), opts);\n };\n })(ControlMessage = RPC.ControlMessage || (RPC.ControlMessage = {}));\n let ControlIHave;\n (function (ControlIHave) {\n let _codec;\n ControlIHave.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIHave.encode = (obj) => {\n return encodeMessage(obj, ControlIHave.codec());\n };\n ControlIHave.decode = (buf, opts) => {\n return decodeMessage(buf, ControlIHave.codec(), opts);\n };\n })(ControlIHave = RPC.ControlIHave || (RPC.ControlIHave = {}));\n let ControlIWant;\n (function (ControlIWant) {\n let _codec;\n ControlIWant.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIWant.encode = (obj) => {\n return encodeMessage(obj, ControlIWant.codec());\n };\n ControlIWant.decode = (buf, opts) => {\n return decodeMessage(buf, ControlIWant.codec(), opts);\n };\n })(ControlIWant = RPC.ControlIWant || (RPC.ControlIWant = {}));\n let ControlGraft;\n (function (ControlGraft) {\n let _codec;\n ControlGraft.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlGraft.encode = (obj) => {\n return encodeMessage(obj, ControlGraft.codec());\n };\n ControlGraft.decode = (buf, opts) => {\n return decodeMessage(buf, ControlGraft.codec(), opts);\n };\n })(ControlGraft = RPC.ControlGraft || (RPC.ControlGraft = {}));\n let ControlPrune;\n (function (ControlPrune) {\n let _codec;\n ControlPrune.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.peers != null) {\n for (const value of obj.peers) {\n w.uint32(18);\n RPC.PeerInfo.codec().encode(value, w);\n }\n }\n if (obj.backoff != null) {\n w.uint32(24);\n w.uint64Number(obj.backoff);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peers: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.peers != null && obj.peers.length === opts.limits.peers) {\n throw new CodeError('decode error - map field \"peers\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.peers.push(RPC.PeerInfo.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.backoff = reader.uint64Number();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlPrune.encode = (obj) => {\n return encodeMessage(obj, ControlPrune.codec());\n };\n ControlPrune.decode = (buf, opts) => {\n return decodeMessage(buf, ControlPrune.codec(), opts);\n };\n })(ControlPrune = RPC.ControlPrune || (RPC.ControlPrune = {}));\n let PeerInfo;\n (function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerID != null) {\n w.uint32(10);\n w.bytes(obj.peerID);\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(18);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.peerID = reader.bytes();\n break;\n }\n case 2: {\n obj.signedPeerRecord = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return encodeMessage(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return decodeMessage(buf, PeerInfo.codec(), opts);\n };\n })(PeerInfo = RPC.PeerInfo || (RPC.PeerInfo = {}));\n let _codec;\n RPC.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscriptions != null) {\n for (const value of obj.subscriptions) {\n w.uint32(10);\n RPC.SubOpts.codec().encode(value, w);\n }\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(18);\n RPC.Message.codec().encode(value, w);\n }\n }\n if (obj.control != null) {\n w.uint32(26);\n RPC.ControlMessage.codec().encode(obj.control, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscriptions: [],\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.subscriptions != null && obj.subscriptions.length === opts.limits.subscriptions) {\n throw new CodeError('decode error - map field \"subscriptions\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.subscriptions.push(RPC.SubOpts.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messages.push(RPC.Message.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.control = RPC.ControlMessage.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RPC.encode = (obj) => {\n return encodeMessage(obj, RPC.codec());\n };\n RPC.decode = (buf, opts) => {\n return decodeMessage(buf, RPC.codec(), opts);\n };\n})(RPC || (RPC = {}));\n//# sourceMappingURL=rpc.js.map","import { TopicValidatorResult } from '@libp2p/interface';\nexport var SignaturePolicy;\n(function (SignaturePolicy) {\n /**\n * On the producing side:\n * - Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * - Enforce the fields to be present, reject otherwise.\n * - Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\n SignaturePolicy[\"StrictSign\"] = \"StrictSign\";\n /**\n * On the producing side:\n * - Build messages without the signature, key, from and seqno fields.\n * - The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * - Enforce the fields to be absent, reject otherwise.\n * - Propagate only if the fields are absent, reject otherwise.\n * - A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\n SignaturePolicy[\"StrictNoSign\"] = \"StrictNoSign\";\n})(SignaturePolicy || (SignaturePolicy = {}));\nexport var PublishConfigType;\n(function (PublishConfigType) {\n PublishConfigType[PublishConfigType[\"Signing\"] = 0] = \"Signing\";\n PublishConfigType[PublishConfigType[\"Anonymous\"] = 1] = \"Anonymous\";\n})(PublishConfigType || (PublishConfigType = {}));\nexport var RejectReason;\n(function (RejectReason) {\n /**\n * The message failed the configured validation during decoding.\n * SelfOrigin is considered a ValidationError\n */\n RejectReason[\"Error\"] = \"error\";\n /**\n * Custom validator fn reported status IGNORE.\n */\n RejectReason[\"Ignore\"] = \"ignore\";\n /**\n * Custom validator fn reported status REJECT.\n */\n RejectReason[\"Reject\"] = \"reject\";\n /**\n * The peer that sent the message OR the source from field is blacklisted.\n * Causes messages to be ignored, not penalized, neither do score record creation.\n */\n RejectReason[\"Blacklisted\"] = \"blacklisted\";\n})(RejectReason || (RejectReason = {}));\nexport var ValidateError;\n(function (ValidateError) {\n /// The message has an invalid signature,\n ValidateError[\"InvalidSignature\"] = \"invalid_signature\";\n /// The sequence number was the incorrect size\n ValidateError[\"InvalidSeqno\"] = \"invalid_seqno\";\n /// The PeerId was invalid\n ValidateError[\"InvalidPeerId\"] = \"invalid_peerid\";\n /// Signature existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n ValidateError[\"SignaturePresent\"] = \"signature_present\";\n /// Sequence number existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n ValidateError[\"SeqnoPresent\"] = \"seqno_present\";\n /// Message source existed when validation has been sent to\n /// [`crate::behaviour::MessageAuthenticity::Anonymous`].\n ValidateError[\"FromPresent\"] = \"from_present\";\n /// The data transformation failed.\n ValidateError[\"TransformFailed\"] = \"transform_failed\";\n})(ValidateError || (ValidateError = {}));\nexport var MessageStatus;\n(function (MessageStatus) {\n MessageStatus[\"duplicate\"] = \"duplicate\";\n MessageStatus[\"invalid\"] = \"invalid\";\n MessageStatus[\"valid\"] = \"valid\";\n})(MessageStatus || (MessageStatus = {}));\n/**\n * Typesafe conversion of MessageAcceptance -> RejectReason. TS ensures all values covered\n */\nexport function rejectReasonFromAcceptance(acceptance) {\n switch (acceptance) {\n case TopicValidatorResult.Ignore:\n return RejectReason.Ignore;\n case TopicValidatorResult.Reject:\n return RejectReason.Reject;\n default:\n throw new Error('Unreachable');\n }\n}\n//# sourceMappingURL=types.js.map","import { TopicValidatorResult } from '@libp2p/interface';\nimport { MessageStatus, RejectReason } from './types.js';\nexport var MessageSource;\n(function (MessageSource) {\n MessageSource[\"forward\"] = \"forward\";\n MessageSource[\"publish\"] = \"publish\";\n})(MessageSource || (MessageSource = {}));\nexport var InclusionReason;\n(function (InclusionReason) {\n /** Peer was a fanaout peer. */\n InclusionReason[\"Fanout\"] = \"fanout\";\n /** Included from random selection. */\n InclusionReason[\"Random\"] = \"random\";\n /** Peer subscribed. */\n InclusionReason[\"Subscribed\"] = \"subscribed\";\n /** On heartbeat, peer was included to fill the outbound quota. */\n InclusionReason[\"Outbound\"] = \"outbound\";\n /** On heartbeat, not enough peers in mesh */\n InclusionReason[\"NotEnough\"] = \"not_enough\";\n /** On heartbeat opportunistic grafting due to low mesh score */\n InclusionReason[\"Opportunistic\"] = \"opportunistic\";\n})(InclusionReason || (InclusionReason = {}));\n/// Reasons why a peer was removed from the mesh.\nexport var ChurnReason;\n(function (ChurnReason) {\n /// Peer disconnected.\n ChurnReason[\"Dc\"] = \"disconnected\";\n /// Peer had a bad score.\n ChurnReason[\"BadScore\"] = \"bad_score\";\n /// Peer sent a PRUNE.\n ChurnReason[\"Prune\"] = \"prune\";\n /// Too many peers.\n ChurnReason[\"Excess\"] = \"excess\";\n})(ChurnReason || (ChurnReason = {}));\n/// Kinds of reasons a peer's score has been penalized\nexport var ScorePenalty;\n(function (ScorePenalty) {\n /// A peer grafted before waiting the back-off time.\n ScorePenalty[\"GraftBackoff\"] = \"graft_backoff\";\n /// A Peer did not respond to an IWANT request in time.\n ScorePenalty[\"BrokenPromise\"] = \"broken_promise\";\n /// A Peer did not send enough messages as expected.\n ScorePenalty[\"MessageDeficit\"] = \"message_deficit\";\n /// Too many peers under one IP address.\n ScorePenalty[\"IPColocation\"] = \"IP_colocation\";\n})(ScorePenalty || (ScorePenalty = {}));\nexport var IHaveIgnoreReason;\n(function (IHaveIgnoreReason) {\n IHaveIgnoreReason[\"LowScore\"] = \"low_score\";\n IHaveIgnoreReason[\"MaxIhave\"] = \"max_ihave\";\n IHaveIgnoreReason[\"MaxIasked\"] = \"max_iasked\";\n})(IHaveIgnoreReason || (IHaveIgnoreReason = {}));\nexport var ScoreThreshold;\n(function (ScoreThreshold) {\n ScoreThreshold[\"graylist\"] = \"graylist\";\n ScoreThreshold[\"publish\"] = \"publish\";\n ScoreThreshold[\"gossip\"] = \"gossip\";\n ScoreThreshold[\"mesh\"] = \"mesh\";\n})(ScoreThreshold || (ScoreThreshold = {}));\n/**\n * A collection of metrics used throughout the Gossipsub behaviour.\n * NOTE: except for special reasons, do not add more than 1 label for frequent metrics,\n * there's a performance penalty as of June 2023.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type\nexport function getMetrics(register, topicStrToLabel, opts) {\n // Using function style instead of class to prevent having to re-declare all MetricsPrometheus types.\n return {\n /* Metrics for static config */\n protocolsEnabled: register.gauge({\n name: 'gossipsub_protocol',\n help: 'Status of enabled protocols',\n labelNames: ['protocol']\n }),\n /* Metrics per known topic */\n /**\n * Status of our subscription to this topic. This metric allows analyzing other topic metrics\n * filtered by our current subscription status.\n * = rust-libp2p `topic_subscription_status` */\n topicSubscriptionStatus: register.gauge({\n name: 'gossipsub_topic_subscription_status',\n help: 'Status of our subscription to this topic',\n labelNames: ['topicStr']\n }),\n /** Number of peers subscribed to each topic. This allows us to analyze a topic's behaviour\n * regardless of our subscription status. */\n topicPeersCount: register.gauge({\n name: 'gossipsub_topic_peer_count',\n help: 'Number of peers subscribed to each topic',\n labelNames: ['topicStr']\n }),\n /* Metrics regarding mesh state */\n /**\n * Number of peers in our mesh. This metric should be updated with the count of peers for a\n * topic in the mesh regardless of inclusion and churn events.\n * = rust-libp2p `mesh_peer_counts` */\n meshPeerCounts: register.gauge({\n name: 'gossipsub_mesh_peer_count',\n help: 'Number of peers in our mesh',\n labelNames: ['topicStr']\n }),\n /**\n * Number of times we include peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_inclusion_events` */\n meshPeerInclusionEventsFanout: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_fanout_total',\n help: 'Number of times we include peers in a topic mesh for fanout reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsRandom: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_random_total',\n help: 'Number of times we include peers in a topic mesh for random reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsSubscribed: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_subscribed_total',\n help: 'Number of times we include peers in a topic mesh for subscribed reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsOutbound: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_outbound_total',\n help: 'Number of times we include peers in a topic mesh for outbound reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsNotEnough: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_not_enough_total',\n help: 'Number of times we include peers in a topic mesh for not_enough reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsOpportunistic: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_opportunistic_total',\n help: 'Number of times we include peers in a topic mesh for opportunistic reasons',\n labelNames: ['topic']\n }),\n meshPeerInclusionEventsUnknown: register.gauge({\n name: 'gossipsub_mesh_peer_inclusion_events_unknown_total',\n help: 'Number of times we include peers in a topic mesh for unknown reasons',\n labelNames: ['topic']\n }),\n /**\n * Number of times we remove peers in a topic mesh for different reasons.\n * = rust-libp2p `mesh_peer_churn_events` */\n meshPeerChurnEventsDisconnected: register.gauge({\n name: 'gossipsub_peer_churn_events_disconnected_total',\n help: 'Number of times we remove peers in a topic mesh for disconnected reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsBadScore: register.gauge({\n name: 'gossipsub_peer_churn_events_bad_score_total',\n help: 'Number of times we remove peers in a topic mesh for bad_score reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsPrune: register.gauge({\n name: 'gossipsub_peer_churn_events_prune_total',\n help: 'Number of times we remove peers in a topic mesh for prune reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsExcess: register.gauge({\n name: 'gossipsub_peer_churn_events_excess_total',\n help: 'Number of times we remove peers in a topic mesh for excess reasons',\n labelNames: ['topic']\n }),\n meshPeerChurnEventsUnknown: register.gauge({\n name: 'gossipsub_peer_churn_events_unknown_total',\n help: 'Number of times we remove peers in a topic mesh for unknown reasons',\n labelNames: ['topic']\n }),\n /* General Metrics */\n /**\n * Gossipsub supports floodsub, gossipsub v1.0 and gossipsub v1.1. Peers are classified based\n * on which protocol they support. This metric keeps track of the number of peers that are\n * connected of each type. */\n peersPerProtocol: register.gauge({\n name: 'gossipsub_peers_per_protocol_count',\n help: 'Peers connected for each topic',\n labelNames: ['protocol']\n }),\n /** The time it takes to complete one iteration of the heartbeat. */\n heartbeatDuration: register.histogram({\n name: 'gossipsub_heartbeat_duration_seconds',\n help: 'The time it takes to complete one iteration of the heartbeat',\n // Should take <10ms, over 1s it's a huge issue that needs debugging, since a heartbeat will be cancelled\n buckets: [0.01, 0.1, 1]\n }),\n /** Heartbeat run took longer than heartbeat interval so next is skipped */\n heartbeatSkipped: register.gauge({\n name: 'gossipsub_heartbeat_skipped',\n help: 'Heartbeat run took longer than heartbeat interval so next is skipped'\n }),\n /**\n * Message validation results for each topic.\n * Invalid == Reject?\n * = rust-libp2p `invalid_messages`, `accepted_messages`, `ignored_messages`, `rejected_messages` */\n acceptedMessagesTotal: register.gauge({\n name: 'gossipsub_accepted_messages_total',\n help: 'Total accepted messages for each topic',\n labelNames: ['topic']\n }),\n ignoredMessagesTotal: register.gauge({\n name: 'gossipsub_ignored_messages_total',\n help: 'Total ignored messages for each topic',\n labelNames: ['topic']\n }),\n rejectedMessagesTotal: register.gauge({\n name: 'gossipsub_rejected_messages_total',\n help: 'Total rejected messages for each topic',\n labelNames: ['topic']\n }),\n unknownValidationResultsTotal: register.gauge({\n name: 'gossipsub_unknown_validation_results_total',\n help: 'Total unknown validation results for each topic',\n labelNames: ['topic']\n }),\n /**\n * When the user validates a message, it tries to re propagate it to its mesh peers. If the\n * message expires from the memcache before it can be validated, we count this a cache miss\n * and it is an indicator that the memcache size should be increased.\n * = rust-libp2p `mcache_misses` */\n asyncValidationMcacheHit: register.gauge({\n name: 'gossipsub_async_validation_mcache_hit_total',\n help: 'Async validation result reported by the user layer',\n labelNames: ['hit']\n }),\n asyncValidationDelayFromFirstSeenSec: register.histogram({\n name: 'gossipsub_async_validation_delay_from_first_seen',\n help: 'Async validation report delay from first seen in second',\n buckets: [0.01, 0.03, 0.1, 0.3, 1, 3, 10]\n }),\n asyncValidationUnknownFirstSeen: register.gauge({\n name: 'gossipsub_async_validation_unknown_first_seen_count_total',\n help: 'Async validation report unknown first seen value for message'\n }),\n // peer stream\n peerReadStreamError: register.gauge({\n name: 'gossipsub_peer_read_stream_err_count_total',\n help: 'Peer read stream error'\n }),\n // RPC outgoing. Track byte length + data structure sizes\n rpcRecvBytes: register.gauge({ name: 'gossipsub_rpc_recv_bytes_total', help: 'RPC recv' }),\n rpcRecvCount: register.gauge({ name: 'gossipsub_rpc_recv_count_total', help: 'RPC recv' }),\n rpcRecvSubscription: register.gauge({ name: 'gossipsub_rpc_recv_subscription_total', help: 'RPC recv' }),\n rpcRecvMessage: register.gauge({ name: 'gossipsub_rpc_recv_message_total', help: 'RPC recv' }),\n rpcRecvControl: register.gauge({ name: 'gossipsub_rpc_recv_control_total', help: 'RPC recv' }),\n rpcRecvIHave: register.gauge({ name: 'gossipsub_rpc_recv_ihave_total', help: 'RPC recv' }),\n rpcRecvIWant: register.gauge({ name: 'gossipsub_rpc_recv_iwant_total', help: 'RPC recv' }),\n rpcRecvGraft: register.gauge({ name: 'gossipsub_rpc_recv_graft_total', help: 'RPC recv' }),\n rpcRecvPrune: register.gauge({ name: 'gossipsub_rpc_recv_prune_total', help: 'RPC recv' }),\n rpcDataError: register.gauge({ name: 'gossipsub_rpc_data_err_count_total', help: 'RPC data error' }),\n rpcRecvError: register.gauge({ name: 'gossipsub_rpc_recv_err_count_total', help: 'RPC recv error' }),\n /** Total count of RPC dropped because acceptFrom() == false */\n rpcRecvNotAccepted: register.gauge({\n name: 'gossipsub_rpc_rcv_not_accepted_total',\n help: 'Total count of RPC dropped because acceptFrom() == false'\n }),\n // RPC incoming. Track byte length + data structure sizes\n rpcSentBytes: register.gauge({ name: 'gossipsub_rpc_sent_bytes_total', help: 'RPC sent' }),\n rpcSentCount: register.gauge({ name: 'gossipsub_rpc_sent_count_total', help: 'RPC sent' }),\n rpcSentSubscription: register.gauge({ name: 'gossipsub_rpc_sent_subscription_total', help: 'RPC sent' }),\n rpcSentMessage: register.gauge({ name: 'gossipsub_rpc_sent_message_total', help: 'RPC sent' }),\n rpcSentControl: register.gauge({ name: 'gossipsub_rpc_sent_control_total', help: 'RPC sent' }),\n rpcSentIHave: register.gauge({ name: 'gossipsub_rpc_sent_ihave_total', help: 'RPC sent' }),\n rpcSentIWant: register.gauge({ name: 'gossipsub_rpc_sent_iwant_total', help: 'RPC sent' }),\n rpcSentGraft: register.gauge({ name: 'gossipsub_rpc_sent_graft_total', help: 'RPC sent' }),\n rpcSentPrune: register.gauge({ name: 'gossipsub_rpc_sent_prune_total', help: 'RPC sent' }),\n // publish message. Track peers sent to and bytes\n /** Total count of msg published by topic */\n msgPublishCount: register.gauge({\n name: 'gossipsub_msg_publish_count_total',\n help: 'Total count of msg published by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we publish a msg to */\n msgPublishPeersByTopic: register.gauge({\n name: 'gossipsub_msg_publish_peers_total',\n help: 'Total count of peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of peers (by group) that we publish a msg to */\n directPeersPublishedTotal: register.gauge({\n name: 'gossipsub_direct_peers_published_total',\n help: 'Total direct peers that we publish a msg to',\n labelNames: ['topic']\n }),\n floodsubPeersPublishedTotal: register.gauge({\n name: 'gossipsub_floodsub_peers_published_total',\n help: 'Total floodsub peers that we publish a msg to',\n labelNames: ['topic']\n }),\n meshPeersPublishedTotal: register.gauge({\n name: 'gossipsub_mesh_peers_published_total',\n help: 'Total mesh peers that we publish a msg to',\n labelNames: ['topic']\n }),\n fanoutPeersPublishedTotal: register.gauge({\n name: 'gossipsub_fanout_peers_published_total',\n help: 'Total fanout peers that we publish a msg to',\n labelNames: ['topic']\n }),\n /** Total count of msg publish data.length bytes */\n msgPublishBytes: register.gauge({\n name: 'gossipsub_msg_publish_bytes_total',\n help: 'Total count of msg publish data.length bytes',\n labelNames: ['topic']\n }),\n /** Total time in seconds to publish a message */\n msgPublishTime: register.histogram({\n name: 'gossipsub_msg_publish_seconds',\n help: 'Total time in seconds to publish a message',\n buckets: [0.001, 0.002, 0.005, 0.01, 0.1, 0.5, 1],\n labelNames: ['topic']\n }),\n /** Total count of msg forwarded by topic */\n msgForwardCount: register.gauge({\n name: 'gossipsub_msg_forward_count_total',\n help: 'Total count of msg forwarded by topic',\n labelNames: ['topic']\n }),\n /** Total count of peers that we forward a msg to */\n msgForwardPeers: register.gauge({\n name: 'gossipsub_msg_forward_peers_total',\n help: 'Total count of peers that we forward a msg to',\n labelNames: ['topic']\n }),\n /** Total count of recv msgs before any validation */\n msgReceivedPreValidation: register.gauge({\n name: 'gossipsub_msg_received_prevalidation_total',\n help: 'Total count of recv msgs before any validation',\n labelNames: ['topic']\n }),\n /** Total count of recv msgs error */\n msgReceivedError: register.gauge({\n name: 'gossipsub_msg_received_error_total',\n help: 'Total count of recv msgs error',\n labelNames: ['topic']\n }),\n /** Tracks distribution of recv msgs by duplicate, invalid, valid */\n prevalidationInvalidTotal: register.gauge({\n name: 'gossipsub_pre_validation_invalid_total',\n help: 'Total count of invalid messages received',\n labelNames: ['topic']\n }),\n prevalidationValidTotal: register.gauge({\n name: 'gossipsub_pre_validation_valid_total',\n help: 'Total count of valid messages received',\n labelNames: ['topic']\n }),\n prevalidationDuplicateTotal: register.gauge({\n name: 'gossipsub_pre_validation_duplicate_total',\n help: 'Total count of duplicate messages received',\n labelNames: ['topic']\n }),\n prevalidationUnknownTotal: register.gauge({\n name: 'gossipsub_pre_validation_unknown_status_total',\n help: 'Total count of unknown_status messages received',\n labelNames: ['topic']\n }),\n /** Tracks specific reason of invalid */\n msgReceivedInvalid: register.gauge({\n name: 'gossipsub_msg_received_invalid_total',\n help: 'Tracks specific reason of invalid',\n labelNames: ['error']\n }),\n msgReceivedInvalidByTopic: register.gauge({\n name: 'gossipsub_msg_received_invalid_by_topic_total',\n help: 'Tracks specific invalid message by topic',\n labelNames: ['topic']\n }),\n /** Track duplicate message delivery time */\n duplicateMsgDeliveryDelay: register.histogram({\n name: 'gossisub_duplicate_msg_delivery_delay_seconds',\n help: 'Time since the 1st duplicated message validated',\n labelNames: ['topic'],\n buckets: [\n 0.25 * opts.maxMeshMessageDeliveriesWindowSec,\n 0.5 * opts.maxMeshMessageDeliveriesWindowSec,\n Number(opts.maxMeshMessageDeliveriesWindowSec),\n 2 * opts.maxMeshMessageDeliveriesWindowSec,\n 4 * opts.maxMeshMessageDeliveriesWindowSec\n ]\n }),\n /** Total count of late msg delivery total by topic */\n duplicateMsgLateDelivery: register.gauge({\n name: 'gossisub_duplicate_msg_late_delivery_total',\n help: 'Total count of late duplicate message delivery by topic, which triggers P3 penalty',\n labelNames: ['topic']\n }),\n duplicateMsgIgnored: register.gauge({\n name: 'gossisub_ignored_published_duplicate_msgs_total',\n help: 'Total count of published duplicate message ignored by topic',\n labelNames: ['topic']\n }),\n /* Metrics related to scoring */\n /** Total times score() is called */\n scoreFnCalls: register.gauge({\n name: 'gossipsub_score_fn_calls_total',\n help: 'Total times score() is called'\n }),\n /** Total times score() call actually computed computeScore(), no cache */\n scoreFnRuns: register.gauge({\n name: 'gossipsub_score_fn_runs_total',\n help: 'Total times score() call actually computed computeScore(), no cache'\n }),\n scoreCachedDelta: register.histogram({\n name: 'gossipsub_score_cache_delta',\n help: 'Delta of score between cached values that expired',\n buckets: [10, 100, 1000]\n }),\n /** Current count of peers by score threshold */\n peersByScoreThreshold: register.gauge({\n name: 'gossipsub_peers_by_score_threshold_count',\n help: 'Current count of peers by score threshold',\n labelNames: ['threshold']\n }),\n score: register.avgMinMax({\n name: 'gossipsub_score',\n help: 'Avg min max of gossip scores'\n }),\n /**\n * Separate score weights\n * Need to use 2-label metrics in this case to debug the score weights\n **/\n scoreWeights: register.avgMinMax({\n name: 'gossipsub_score_weights',\n help: 'Separate score weights',\n labelNames: ['topic', 'p']\n }),\n /** Histogram of the scores for each mesh topic. */\n // TODO: Not implemented\n scorePerMesh: register.avgMinMax({\n name: 'gossipsub_score_per_mesh',\n help: 'Histogram of the scores for each mesh topic',\n labelNames: ['topic']\n }),\n /** A counter of the kind of penalties being applied to peers. */\n // TODO: Not fully implemented\n scoringPenalties: register.gauge({\n name: 'gossipsub_scoring_penalties_total',\n help: 'A counter of the kind of penalties being applied to peers',\n labelNames: ['penalty']\n }),\n behaviourPenalty: register.histogram({\n name: 'gossipsub_peer_stat_behaviour_penalty',\n help: 'Current peer stat behaviour_penalty at each scrape',\n buckets: [\n 0.25 * opts.behaviourPenaltyThreshold,\n 0.5 * opts.behaviourPenaltyThreshold,\n Number(opts.behaviourPenaltyThreshold),\n 2 * opts.behaviourPenaltyThreshold,\n 4 * opts.behaviourPenaltyThreshold\n ]\n }),\n // TODO:\n // - iasked per peer (on heartbeat)\n // - when promise is resolved, track messages from promises\n /** Total received IHAVE messages that we ignore for some reason */\n ihaveRcvIgnored: register.gauge({\n name: 'gossipsub_ihave_rcv_ignored_total',\n help: 'Total received IHAVE messages that we ignore for some reason',\n labelNames: ['reason']\n }),\n /** Total received IHAVE messages by topic */\n ihaveRcvMsgids: register.gauge({\n name: 'gossipsub_ihave_rcv_msgids_total',\n help: 'Total received IHAVE messages by topic',\n labelNames: ['topic']\n }),\n /**\n * Total messages per topic we don't have. Not actual requests.\n * The number of times we have decided that an IWANT control message is required for this\n * topic. A very high metric might indicate an underperforming network.\n * = rust-libp2p `topic_iwant_msgs` */\n ihaveRcvNotSeenMsgids: register.gauge({\n name: 'gossipsub_ihave_rcv_not_seen_msgids_total',\n help: 'Total messages per topic we do not have, not actual requests',\n labelNames: ['topic']\n }),\n /** Total received IWANT messages by topic */\n iwantRcvMsgids: register.gauge({\n name: 'gossipsub_iwant_rcv_msgids_total',\n help: 'Total received IWANT messages by topic',\n labelNames: ['topic']\n }),\n /** Total requested messageIDs that we don't have */\n iwantRcvDonthaveMsgids: register.gauge({\n name: 'gossipsub_iwant_rcv_dont_have_msgids_total',\n help: 'Total requested messageIDs that we do not have'\n }),\n iwantPromiseStarted: register.gauge({\n name: 'gossipsub_iwant_promise_sent_total',\n help: 'Total count of started IWANT promises'\n }),\n /** Total count of resolved IWANT promises */\n iwantPromiseResolved: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_total',\n help: 'Total count of resolved IWANT promises'\n }),\n /** Total count of resolved IWANT promises from duplicate messages */\n iwantPromiseResolvedFromDuplicate: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_from_duplicate_total',\n help: 'Total count of resolved IWANT promises from duplicate messages'\n }),\n /** Total count of peers we have asked IWANT promises that are resolved */\n iwantPromiseResolvedPeers: register.gauge({\n name: 'gossipsub_iwant_promise_resolved_peers',\n help: 'Total count of peers we have asked IWANT promises that are resolved'\n }),\n iwantPromiseBroken: register.gauge({\n name: 'gossipsub_iwant_promise_broken',\n help: 'Total count of broken IWANT promises'\n }),\n iwantMessagePruned: register.gauge({\n name: 'gossipsub_iwant_message_pruned',\n help: 'Total count of pruned IWANT messages'\n }),\n /** Histogram of delivery time of resolved IWANT promises */\n iwantPromiseDeliveryTime: register.histogram({\n name: 'gossipsub_iwant_promise_delivery_seconds',\n help: 'Histogram of delivery time of resolved IWANT promises',\n buckets: [\n 0.5 * opts.gossipPromiseExpireSec,\n Number(opts.gossipPromiseExpireSec),\n 2 * opts.gossipPromiseExpireSec,\n 4 * opts.gossipPromiseExpireSec\n ]\n }),\n iwantPromiseUntracked: register.gauge({\n name: 'gossip_iwant_promise_untracked',\n help: 'Total count of untracked IWANT promise'\n }),\n /** Backoff time */\n connectedPeersBackoffSec: register.histogram({\n name: 'gossipsub_connected_peers_backoff_seconds',\n help: 'Backoff time in seconds',\n // Using 1 seconds as minimum as that's close to the heartbeat duration, no need for more resolution.\n // As per spec, backoff times are 10 seconds for UnsubscribeBackoff and 60 seconds for PruneBackoff.\n // Higher values of 60 seconds should not occur, but we add 120 seconds just in case\n // https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md#overview-of-new-parameters\n buckets: [1, 2, 4, 10, 20, 60, 120]\n }),\n /* Data structure sizes */\n /** Unbounded cache sizes */\n cacheSize: register.gauge({\n name: 'gossipsub_cache_size',\n help: 'Unbounded cache sizes',\n labelNames: ['cache']\n }),\n /** Current mcache msg count */\n mcacheSize: register.gauge({\n name: 'gossipsub_mcache_size',\n help: 'Current mcache msg count'\n }),\n mcacheNotValidatedCount: register.gauge({\n name: 'gossipsub_mcache_not_validated_count',\n help: 'Current mcache msg count not validated'\n }),\n fastMsgIdCacheCollision: register.gauge({\n name: 'gossipsub_fastmsgid_cache_collision_total',\n help: 'Total count of key collisions on fastmsgid cache put'\n }),\n newConnectionCount: register.gauge({\n name: 'gossipsub_new_connection_total',\n help: 'Total new connection by status',\n labelNames: ['status']\n }),\n topicStrToLabel,\n toTopic(topicStr) {\n return this.topicStrToLabel.get(topicStr) ?? topicStr;\n },\n /** We joined a topic */\n onJoin(topicStr) {\n this.topicSubscriptionStatus.set({ topicStr }, 1);\n this.meshPeerCounts.set({ topicStr }, 0); // Reset count\n },\n /** We left a topic */\n onLeave(topicStr) {\n this.topicSubscriptionStatus.set({ topicStr }, 0);\n this.meshPeerCounts.set({ topicStr }, 0); // Reset count\n },\n /** Register the inclusion of peers in our mesh due to some reason. */\n onAddToMesh(topicStr, reason, count) {\n const topic = this.toTopic(topicStr);\n switch (reason) {\n case InclusionReason.Fanout:\n this.meshPeerInclusionEventsFanout.inc({ topic }, count);\n break;\n case InclusionReason.Random:\n this.meshPeerInclusionEventsRandom.inc({ topic }, count);\n break;\n case InclusionReason.Subscribed:\n this.meshPeerInclusionEventsSubscribed.inc({ topic }, count);\n break;\n case InclusionReason.Outbound:\n this.meshPeerInclusionEventsOutbound.inc({ topic }, count);\n break;\n case InclusionReason.NotEnough:\n this.meshPeerInclusionEventsNotEnough.inc({ topic }, count);\n break;\n case InclusionReason.Opportunistic:\n this.meshPeerInclusionEventsOpportunistic.inc({ topic }, count);\n break;\n default:\n this.meshPeerInclusionEventsUnknown.inc({ topic }, count);\n break;\n }\n },\n /** Register the removal of peers in our mesh due to some reason */\n // - remove_peer_from_mesh()\n // - heartbeat() Churn::BadScore\n // - heartbeat() Churn::Excess\n // - on_disconnect() Churn::Ds\n onRemoveFromMesh(topicStr, reason, count) {\n const topic = this.toTopic(topicStr);\n switch (reason) {\n case ChurnReason.Dc:\n this.meshPeerChurnEventsDisconnected.inc({ topic }, count);\n break;\n case ChurnReason.BadScore:\n this.meshPeerChurnEventsBadScore.inc({ topic }, count);\n break;\n case ChurnReason.Prune:\n this.meshPeerChurnEventsPrune.inc({ topic }, count);\n break;\n case ChurnReason.Excess:\n this.meshPeerChurnEventsExcess.inc({ topic }, count);\n break;\n default:\n this.meshPeerChurnEventsUnknown.inc({ topic }, count);\n break;\n }\n },\n /**\n * Update validation result to metrics\n *\n * @param messageRecord - null means the message's mcache record was not known at the time of acceptance report\n */\n onReportValidation(messageRecord, acceptance, firstSeenTimestampMs) {\n this.asyncValidationMcacheHit.inc({ hit: messageRecord != null ? 'hit' : 'miss' });\n if (messageRecord != null) {\n const topic = this.toTopic(messageRecord.message.topic);\n switch (acceptance) {\n case TopicValidatorResult.Accept:\n this.acceptedMessagesTotal.inc({ topic });\n break;\n case TopicValidatorResult.Ignore:\n this.ignoredMessagesTotal.inc({ topic });\n break;\n case TopicValidatorResult.Reject:\n this.rejectedMessagesTotal.inc({ topic });\n break;\n default:\n this.unknownValidationResultsTotal.inc({ topic });\n break;\n }\n }\n if (firstSeenTimestampMs != null) {\n this.asyncValidationDelayFromFirstSeenSec.observe((Date.now() - firstSeenTimestampMs) / 1000);\n }\n else {\n this.asyncValidationUnknownFirstSeen.inc();\n }\n },\n /**\n * - in handle_graft() Penalty::GraftBackoff\n * - in apply_iwant_penalties() Penalty::BrokenPromise\n * - in metric_score() P3 Penalty::MessageDeficit\n * - in metric_score() P6 Penalty::IPColocation\n */\n onScorePenalty(penalty) {\n // Can this be labeled by topic too?\n this.scoringPenalties.inc({ penalty }, 1);\n },\n onIhaveRcv(topicStr, ihave, idonthave) {\n const topic = this.toTopic(topicStr);\n this.ihaveRcvMsgids.inc({ topic }, ihave);\n this.ihaveRcvNotSeenMsgids.inc({ topic }, idonthave);\n },\n onIwantRcv(iwantByTopic, iwantDonthave) {\n for (const [topicStr, iwant] of iwantByTopic) {\n const topic = this.toTopic(topicStr);\n this.iwantRcvMsgids.inc({ topic }, iwant);\n }\n this.iwantRcvDonthaveMsgids.inc(iwantDonthave);\n },\n onForwardMsg(topicStr, tosendCount) {\n const topic = this.toTopic(topicStr);\n this.msgForwardCount.inc({ topic }, 1);\n this.msgForwardPeers.inc({ topic }, tosendCount);\n },\n onPublishMsg(topicStr, tosendGroupCount, tosendCount, dataLen, ms) {\n const topic = this.toTopic(topicStr);\n this.msgPublishCount.inc({ topic }, 1);\n this.msgPublishBytes.inc({ topic }, tosendCount * dataLen);\n this.msgPublishPeersByTopic.inc({ topic }, tosendCount);\n this.directPeersPublishedTotal.inc({ topic }, tosendGroupCount.direct);\n this.floodsubPeersPublishedTotal.inc({ topic }, tosendGroupCount.floodsub);\n this.meshPeersPublishedTotal.inc({ topic }, tosendGroupCount.mesh);\n this.fanoutPeersPublishedTotal.inc({ topic }, tosendGroupCount.fanout);\n this.msgPublishTime.observe({ topic }, ms / 1000);\n },\n onMsgRecvPreValidation(topicStr) {\n const topic = this.toTopic(topicStr);\n this.msgReceivedPreValidation.inc({ topic }, 1);\n },\n onMsgRecvError(topicStr) {\n const topic = this.toTopic(topicStr);\n this.msgReceivedError.inc({ topic }, 1);\n },\n onPrevalidationResult(topicStr, status) {\n const topic = this.toTopic(topicStr);\n switch (status) {\n case MessageStatus.duplicate:\n this.prevalidationDuplicateTotal.inc({ topic });\n break;\n case MessageStatus.invalid:\n this.prevalidationInvalidTotal.inc({ topic });\n break;\n case MessageStatus.valid:\n this.prevalidationValidTotal.inc({ topic });\n break;\n default:\n this.prevalidationUnknownTotal.inc({ topic });\n break;\n }\n },\n onMsgRecvInvalid(topicStr, reason) {\n const topic = this.toTopic(topicStr);\n const error = reason.reason === RejectReason.Error ? reason.error : reason.reason;\n this.msgReceivedInvalid.inc({ error }, 1);\n this.msgReceivedInvalidByTopic.inc({ topic }, 1);\n },\n onDuplicateMsgDelivery(topicStr, deliveryDelayMs, isLateDelivery) {\n const topic = this.toTopic(topicStr);\n this.duplicateMsgDeliveryDelay.observe({ topic }, deliveryDelayMs / 1000);\n if (isLateDelivery) {\n this.duplicateMsgLateDelivery.inc({ topic }, 1);\n }\n },\n onPublishDuplicateMsg(topicStr) {\n const topic = this.toTopic(topicStr);\n this.duplicateMsgIgnored.inc({ topic }, 1);\n },\n onPeerReadStreamError() {\n this.peerReadStreamError.inc(1);\n },\n onRpcRecvError() {\n this.rpcRecvError.inc(1);\n },\n onRpcDataError() {\n this.rpcDataError.inc(1);\n },\n onRpcRecv(rpc, rpcBytes) {\n this.rpcRecvBytes.inc(rpcBytes);\n this.rpcRecvCount.inc(1);\n if (rpc.subscriptions != null)\n this.rpcRecvSubscription.inc(rpc.subscriptions.length);\n if (rpc.messages != null)\n this.rpcRecvMessage.inc(rpc.messages.length);\n if (rpc.control != null) {\n this.rpcRecvControl.inc(1);\n if (rpc.control.ihave != null)\n this.rpcRecvIHave.inc(rpc.control.ihave.length);\n if (rpc.control.iwant != null)\n this.rpcRecvIWant.inc(rpc.control.iwant.length);\n if (rpc.control.graft != null)\n this.rpcRecvGraft.inc(rpc.control.graft.length);\n if (rpc.control.prune != null)\n this.rpcRecvPrune.inc(rpc.control.prune.length);\n }\n },\n onRpcSent(rpc, rpcBytes) {\n this.rpcSentBytes.inc(rpcBytes);\n this.rpcSentCount.inc(1);\n if (rpc.subscriptions != null)\n this.rpcSentSubscription.inc(rpc.subscriptions.length);\n if (rpc.messages != null)\n this.rpcSentMessage.inc(rpc.messages.length);\n if (rpc.control != null) {\n const ihave = rpc.control.ihave?.length ?? 0;\n const iwant = rpc.control.iwant?.length ?? 0;\n const graft = rpc.control.graft?.length ?? 0;\n const prune = rpc.control.prune?.length ?? 0;\n if (ihave > 0)\n this.rpcSentIHave.inc(ihave);\n if (iwant > 0)\n this.rpcSentIWant.inc(iwant);\n if (graft > 0)\n this.rpcSentGraft.inc(graft);\n if (prune > 0)\n this.rpcSentPrune.inc(prune);\n if (ihave > 0 || iwant > 0 || graft > 0 || prune > 0)\n this.rpcSentControl.inc(1);\n }\n },\n registerScores(scores, scoreThresholds) {\n let graylist = 0;\n let publish = 0;\n let gossip = 0;\n let mesh = 0;\n for (const score of scores) {\n if (score >= scoreThresholds.graylistThreshold)\n graylist++;\n if (score >= scoreThresholds.publishThreshold)\n publish++;\n if (score >= scoreThresholds.gossipThreshold)\n gossip++;\n if (score >= 0)\n mesh++;\n }\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.graylist }, graylist);\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.publish }, publish);\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.gossip }, gossip);\n this.peersByScoreThreshold.set({ threshold: ScoreThreshold.mesh }, mesh);\n // Register full score too\n this.score.set(scores);\n },\n registerScoreWeights(sw) {\n for (const [topic, wsTopic] of sw.byTopic) {\n this.scoreWeights.set({ topic, p: 'p1' }, wsTopic.p1w);\n this.scoreWeights.set({ topic, p: 'p2' }, wsTopic.p2w);\n this.scoreWeights.set({ topic, p: 'p3' }, wsTopic.p3w);\n this.scoreWeights.set({ topic, p: 'p3b' }, wsTopic.p3bw);\n this.scoreWeights.set({ topic, p: 'p4' }, wsTopic.p4w);\n }\n this.scoreWeights.set({ p: 'p5' }, sw.p5w);\n this.scoreWeights.set({ p: 'p6' }, sw.p6w);\n this.scoreWeights.set({ p: 'p7' }, sw.p7w);\n },\n registerScorePerMesh(mesh, scoreByPeer) {\n const peersPerTopicLabel = new Map();\n mesh.forEach((peers, topicStr) => {\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = this.topicStrToLabel.get(topicStr) ?? 'unknown';\n let peersInMesh = peersPerTopicLabel.get(topicLabel);\n if (peersInMesh == null) {\n peersInMesh = new Set();\n peersPerTopicLabel.set(topicLabel, peersInMesh);\n }\n peers.forEach((p) => peersInMesh?.add(p));\n });\n for (const [topic, peers] of peersPerTopicLabel) {\n const meshScores = [];\n peers.forEach((peer) => {\n meshScores.push(scoreByPeer.get(peer) ?? 0);\n });\n this.scorePerMesh.set({ topic }, meshScores);\n }\n }\n };\n}\n//# sourceMappingURL=metrics.js.map","export class MessageCache {\n gossip;\n msgs = new Map();\n msgIdToStrFn;\n history = [];\n /** Track with accounting of messages in the mcache that are not yet validated */\n notValidatedCount = 0;\n /**\n * Holds history of messages in timebounded history arrays\n */\n constructor(\n /**\n * The number of indices in the cache history used for gossiping. That means that a message\n * won't get gossiped anymore when shift got called `gossip` many times after inserting the\n * message in the cache.\n */\n gossip, historyCapacity, msgIdToStrFn) {\n this.gossip = gossip;\n this.msgIdToStrFn = msgIdToStrFn;\n for (let i = 0; i < historyCapacity; i++) {\n this.history[i] = [];\n }\n }\n get size() {\n return this.msgs.size;\n }\n /**\n * Adds a message to the current window and the cache\n * Returns true if the message is not known and is inserted in the cache\n */\n put(messageId, msg, validated = false) {\n const { msgIdStr } = messageId;\n // Don't add duplicate entries to the cache.\n if (this.msgs.has(msgIdStr)) {\n return false;\n }\n this.msgs.set(msgIdStr, {\n message: msg,\n validated,\n originatingPeers: new Set(),\n iwantCounts: new Map()\n });\n this.history[0].push({ ...messageId, topic: msg.topic });\n if (!validated) {\n this.notValidatedCount++;\n }\n return true;\n }\n observeDuplicate(msgId, fromPeerIdStr) {\n const entry = this.msgs.get(msgId);\n if ((entry != null) &&\n // if the message is already validated, we don't need to store extra peers sending us\n // duplicates as the message has already been forwarded\n !entry.validated) {\n entry.originatingPeers.add(fromPeerIdStr);\n }\n }\n /**\n * Retrieves a message from the cache by its ID, if it is still present\n */\n get(msgId) {\n return this.msgs.get(this.msgIdToStrFn(msgId))?.message;\n }\n /**\n * Increases the iwant count for the given message by one and returns the message together\n * with the iwant if the message exists.\n */\n getWithIWantCount(msgIdStr, p) {\n const msg = this.msgs.get(msgIdStr);\n if (msg == null) {\n return null;\n }\n const count = (msg.iwantCounts.get(p) ?? 0) + 1;\n msg.iwantCounts.set(p, count);\n return { msg: msg.message, count };\n }\n /**\n * Retrieves a list of message IDs for a set of topics\n */\n getGossipIDs(topics) {\n const msgIdsByTopic = new Map();\n for (let i = 0; i < this.gossip; i++) {\n this.history[i].forEach((entry) => {\n const msg = this.msgs.get(entry.msgIdStr);\n if ((msg?.validated ?? false) && topics.has(entry.topic)) {\n let msgIds = msgIdsByTopic.get(entry.topic);\n if (msgIds == null) {\n msgIds = [];\n msgIdsByTopic.set(entry.topic, msgIds);\n }\n msgIds.push(entry.msgId);\n }\n });\n }\n return msgIdsByTopic;\n }\n /**\n * Gets a message with msgId and tags it as validated.\n * This function also returns the known peers that have sent us this message. This is used to\n * prevent us sending redundant messages to peers who have already propagated it.\n */\n validate(msgId) {\n const entry = this.msgs.get(msgId);\n if (entry == null) {\n return null;\n }\n if (!entry.validated) {\n this.notValidatedCount--;\n }\n const { message, originatingPeers } = entry;\n entry.validated = true;\n // Clear the known peers list (after a message is validated, it is forwarded and we no\n // longer need to store the originating peers).\n entry.originatingPeers = new Set();\n return { message, originatingPeers };\n }\n /**\n * Shifts the current window, discarding messages older than this.history.length of the cache\n */\n shift() {\n const lastCacheEntries = this.history[this.history.length - 1];\n lastCacheEntries.forEach((cacheEntry) => {\n const entry = this.msgs.get(cacheEntry.msgIdStr);\n if (entry != null) {\n this.msgs.delete(cacheEntry.msgIdStr);\n if (!entry.validated) {\n this.notValidatedCount--;\n }\n }\n });\n this.history.pop();\n this.history.unshift([]);\n }\n remove(msgId) {\n const entry = this.msgs.get(msgId);\n if (entry == null) {\n return null;\n }\n // Keep the message on the history vector, it will be dropped on a shift()\n this.msgs.delete(msgId);\n return entry;\n }\n}\n//# sourceMappingURL=message-cache.js.map","export const ERR_INVALID_PEER_SCORE_PARAMS = 'ERR_INVALID_PEER_SCORE_PARAMS';\nexport const ERR_INVALID_PEER_SCORE_THRESHOLDS = 'ERR_INVALID_PEER_SCORE_THRESHOLDS';\n//# sourceMappingURL=constants.js.map","import { CodeError } from '@libp2p/interface';\nimport { ERR_INVALID_PEER_SCORE_PARAMS } from './constants.js';\nexport const defaultPeerScoreParams = {\n topics: {},\n topicScoreCap: 10.0,\n appSpecificScore: () => 0.0,\n appSpecificWeight: 10.0,\n IPColocationFactorWeight: -5.0,\n IPColocationFactorThreshold: 10.0,\n IPColocationFactorWhitelist: new Set(),\n behaviourPenaltyWeight: -10.0,\n behaviourPenaltyThreshold: 0.0,\n behaviourPenaltyDecay: 0.2,\n decayInterval: 1000.0,\n decayToZero: 0.1,\n retainScore: 3600 * 1000\n};\nexport const defaultTopicScoreParams = {\n topicWeight: 0.5,\n timeInMeshWeight: 1,\n timeInMeshQuantum: 1,\n timeInMeshCap: 3600,\n firstMessageDeliveriesWeight: 1,\n firstMessageDeliveriesDecay: 0.5,\n firstMessageDeliveriesCap: 2000,\n meshMessageDeliveriesWeight: -1,\n meshMessageDeliveriesDecay: 0.5,\n meshMessageDeliveriesCap: 100,\n meshMessageDeliveriesThreshold: 20,\n meshMessageDeliveriesWindow: 10,\n meshMessageDeliveriesActivation: 5000,\n meshFailurePenaltyWeight: -1,\n meshFailurePenaltyDecay: 0.5,\n invalidMessageDeliveriesWeight: -1,\n invalidMessageDeliveriesDecay: 0.3\n};\nexport function createPeerScoreParams(p = {}) {\n return {\n ...defaultPeerScoreParams,\n ...p,\n topics: (p.topics != null)\n ? Object.entries(p.topics).reduce((topics, [topic, topicScoreParams]) => {\n topics[topic] = createTopicScoreParams(topicScoreParams);\n return topics;\n }, {})\n : {}\n };\n}\nexport function createTopicScoreParams(p = {}) {\n return {\n ...defaultTopicScoreParams,\n ...p\n };\n}\n// peer score parameter validation\nexport function validatePeerScoreParams(p) {\n for (const [topic, params] of Object.entries(p.topics)) {\n try {\n validateTopicScoreParams(params);\n }\n catch (e) {\n throw new CodeError(`invalid score parameters for topic ${topic}: ${e.message}`, ERR_INVALID_PEER_SCORE_PARAMS);\n }\n }\n // check that the topic score is 0 or something positive\n if (p.topicScoreCap < 0) {\n throw new CodeError('invalid topic score cap; must be positive (or 0 for no cap)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check that we have an app specific score; the weight can be anything (but expected positive)\n if (p.appSpecificScore === null || p.appSpecificScore === undefined) {\n throw new CodeError('missing application specific score function', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check the IP colocation factor\n if (p.IPColocationFactorWeight > 0) {\n throw new CodeError('invalid IPColocationFactorWeight; must be negative (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.IPColocationFactorWeight !== 0 && p.IPColocationFactorThreshold < 1) {\n throw new CodeError('invalid IPColocationFactorThreshold; must be at least 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check the behaviour penalty\n if (p.behaviourPenaltyWeight > 0) {\n throw new CodeError('invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.behaviourPenaltyWeight !== 0 && (p.behaviourPenaltyDecay <= 0 || p.behaviourPenaltyDecay >= 1)) {\n throw new CodeError('invalid BehaviourPenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check the decay parameters\n if (p.decayInterval < 1000) {\n throw new CodeError('invalid DecayInterval; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.decayToZero <= 0 || p.decayToZero >= 1) {\n throw new CodeError('invalid DecayToZero; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // no need to check the score retention; a value of 0 means that we don't retain scores\n}\n// eslint-disable-next-line complexity\nexport function validateTopicScoreParams(p) {\n // make sure we have a sane topic weight\n if (p.topicWeight < 0) {\n throw new CodeError('invalid topic weight; must be >= 0', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check P1\n if (p.timeInMeshQuantum === 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be non zero', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.timeInMeshWeight < 0) {\n throw new CodeError('invalid TimeInMeshWeight; must be positive (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshQuantum <= 0) {\n throw new CodeError('invalid TimeInMeshQuantum; must be positive', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.timeInMeshWeight !== 0 && p.timeInMeshCap <= 0) {\n throw new CodeError('invalid TimeInMeshCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check P2\n if (p.firstMessageDeliveriesWeight < 0) {\n throw new CodeError('invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.firstMessageDeliveriesWeight !== 0 &&\n (p.firstMessageDeliveriesDecay <= 0 || p.firstMessageDeliveriesDecay >= 1)) {\n throw new CodeError('invalid FirstMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.firstMessageDeliveriesWeight !== 0 && p.firstMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid FirstMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check P3\n if (p.meshMessageDeliveriesWeight > 0) {\n throw new CodeError('invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshMessageDeliveriesWeight !== 0 && (p.meshMessageDeliveriesDecay <= 0 || p.meshMessageDeliveriesDecay >= 1)) {\n throw new CodeError('invalid MeshMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesCap <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesCap; must be positive', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesThreshold <= 0) {\n throw new CodeError('invalid MeshMessageDeliveriesThreshold; must be positive', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshMessageDeliveriesWindow < 0) {\n throw new CodeError('invalid MeshMessageDeliveriesWindow; must be non-negative', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshMessageDeliveriesWeight !== 0 && p.meshMessageDeliveriesActivation < 1000) {\n throw new CodeError('invalid MeshMessageDeliveriesActivation; must be at least 1s', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check P3b\n if (p.meshFailurePenaltyWeight > 0) {\n throw new CodeError('invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.meshFailurePenaltyWeight !== 0 && (p.meshFailurePenaltyDecay <= 0 || p.meshFailurePenaltyDecay >= 1)) {\n throw new CodeError('invalid MeshFailurePenaltyDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n // check P4\n if (p.invalidMessageDeliveriesWeight > 0) {\n throw new CodeError('invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n if (p.invalidMessageDeliveriesDecay <= 0 || p.invalidMessageDeliveriesDecay >= 1) {\n throw new CodeError('invalid InvalidMessageDeliveriesDecay; must be between 0 and 1', ERR_INVALID_PEER_SCORE_PARAMS);\n }\n}\n//# sourceMappingURL=peer-score-params.js.map","import { CodeError } from '@libp2p/interface';\nimport { ERR_INVALID_PEER_SCORE_THRESHOLDS } from './constants.js';\nexport const defaultPeerScoreThresholds = {\n gossipThreshold: -10,\n publishThreshold: -50,\n graylistThreshold: -80,\n acceptPXThreshold: 10,\n opportunisticGraftThreshold: 20\n};\nexport function createPeerScoreThresholds(p = {}) {\n return {\n ...defaultPeerScoreThresholds,\n ...p\n };\n}\nexport function validatePeerScoreThresholds(p) {\n if (p.gossipThreshold > 0) {\n throw new CodeError('invalid gossip threshold; it must be <= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS);\n }\n if (p.publishThreshold > 0 || p.publishThreshold > p.gossipThreshold) {\n throw new CodeError('invalid publish threshold; it must be <= 0 and <= gossip threshold', ERR_INVALID_PEER_SCORE_THRESHOLDS);\n }\n if (p.graylistThreshold > 0 || p.graylistThreshold > p.publishThreshold) {\n throw new CodeError('invalid graylist threshold; it must be <= 0 and <= publish threshold', ERR_INVALID_PEER_SCORE_THRESHOLDS);\n }\n if (p.acceptPXThreshold < 0) {\n throw new CodeError('invalid accept PX threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS);\n }\n if (p.opportunisticGraftThreshold < 0) {\n throw new CodeError('invalid opportunistic grafting threshold; it must be >= 0', ERR_INVALID_PEER_SCORE_THRESHOLDS);\n }\n}\n//# sourceMappingURL=peer-score-thresholds.js.map","/**\n * Exclude up to `ineed` items from a set if item meets condition `cond`\n */\nexport function removeItemsFromSet(superSet, ineed, cond = () => true) {\n const subset = new Set();\n if (ineed <= 0)\n return subset;\n for (const id of superSet) {\n if (subset.size >= ineed)\n break;\n if (cond(id)) {\n subset.add(id);\n superSet.delete(id);\n }\n }\n return subset;\n}\n/**\n * Exclude up to `ineed` items from a set\n */\nexport function removeFirstNItemsFromSet(superSet, ineed) {\n return removeItemsFromSet(superSet, ineed, () => true);\n}\nexport class MapDef extends Map {\n getDefault;\n constructor(getDefault) {\n super();\n this.getDefault = getDefault;\n }\n getOrDefault(key) {\n let value = super.get(key);\n if (value === undefined) {\n value = this.getDefault();\n this.set(key, value);\n }\n return value;\n }\n}\n//# sourceMappingURL=set.js.map","export function computeScore(peer, pstats, params, peerIPs) {\n let score = 0;\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n const topicParams = params.topics[topic];\n if (topicParams === undefined) {\n // we are not scoring this topic\n return;\n }\n let topicScore = 0;\n // P1: time in Mesh\n if (tstats.inMesh) {\n let p1 = tstats.meshTime / topicParams.timeInMeshQuantum;\n if (p1 > topicParams.timeInMeshCap) {\n p1 = topicParams.timeInMeshCap;\n }\n topicScore += p1 * topicParams.timeInMeshWeight;\n }\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries;\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap;\n }\n topicScore += p2 * topicParams.firstMessageDeliveriesWeight;\n // P3: mesh message deliveries\n if (tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries;\n const p3 = deficit * deficit;\n topicScore += p3 * topicParams.meshMessageDeliveriesWeight;\n }\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty;\n topicScore += p3b * topicParams.meshFailurePenaltyWeight;\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries;\n topicScore += p4 * topicParams.invalidMessageDeliveriesWeight;\n // update score, mixing with topic weight\n score += topicScore * topicParams.topicWeight;\n });\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap;\n }\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer);\n score += p5 * params.appSpecificWeight;\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return;\n }\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip);\n const numPeersInIP = (peersInIP != null) ? peersInIP.size : 0;\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold;\n const p6 = surplus * surplus;\n score += p6 * params.IPColocationFactorWeight;\n }\n });\n // P7: behavioural pattern penalty\n if (pstats.behaviourPenalty > params.behaviourPenaltyThreshold) {\n const excess = pstats.behaviourPenalty - params.behaviourPenaltyThreshold;\n const p7 = excess * excess;\n score += p7 * params.behaviourPenaltyWeight;\n }\n return score;\n}\n//# sourceMappingURL=compute-score.js.map","import Denque from 'denque';\nimport { TimeCacheDuration } from '../constants.js';\nexport var DeliveryRecordStatus;\n(function (DeliveryRecordStatus) {\n /**\n * we don't know (yet) if the message is valid\n */\n DeliveryRecordStatus[DeliveryRecordStatus[\"unknown\"] = 0] = \"unknown\";\n /**\n * we know the message is valid\n */\n DeliveryRecordStatus[DeliveryRecordStatus[\"valid\"] = 1] = \"valid\";\n /**\n * we know the message is invalid\n */\n DeliveryRecordStatus[DeliveryRecordStatus[\"invalid\"] = 2] = \"invalid\";\n /**\n * we were instructed by the validator to ignore the message\n */\n DeliveryRecordStatus[DeliveryRecordStatus[\"ignored\"] = 3] = \"ignored\";\n})(DeliveryRecordStatus || (DeliveryRecordStatus = {}));\n/**\n * Map of canonical message ID to DeliveryRecord\n *\n * Maintains an internal queue for efficient gc of old messages\n */\nexport class MessageDeliveries {\n records;\n queue;\n constructor() {\n this.records = new Map();\n this.queue = new Denque();\n }\n getRecord(msgIdStr) {\n return this.records.get(msgIdStr);\n }\n ensureRecord(msgIdStr) {\n let drec = this.records.get(msgIdStr);\n if (drec != null) {\n return drec;\n }\n // record doesn't exist yet\n // create record\n drec = {\n status: DeliveryRecordStatus.unknown,\n firstSeenTsMs: Date.now(),\n validated: 0,\n peers: new Set()\n };\n this.records.set(msgIdStr, drec);\n // and add msgId to the queue\n const entry = {\n msgId: msgIdStr,\n expire: Date.now() + TimeCacheDuration\n };\n this.queue.push(entry);\n return drec;\n }\n gc() {\n const now = Date.now();\n // queue is sorted by expiry time\n // remove expired messages, remove from queue until first un-expired message found\n let head = this.queue.peekFront();\n while ((head != null) && head.expire < now) {\n this.records.delete(head.msgId);\n this.queue.shift();\n head = this.queue.peekFront();\n }\n }\n clear() {\n this.records.clear();\n this.queue.clear();\n }\n}\n//# sourceMappingURL=message-deliveries.js.map","import { RejectReason } from '../types.js';\nimport { MapDef } from '../utils/set.js';\nimport { computeScore } from './compute-score.js';\nimport { MessageDeliveries, DeliveryRecordStatus } from './message-deliveries.js';\nimport { validatePeerScoreParams } from './peer-score-params.js';\nexport class PeerScore {\n params;\n metrics;\n /**\n * Per-peer stats for score calculation\n */\n peerStats = new Map();\n /**\n * IP colocation tracking; maps IP => set of peers.\n */\n peerIPs = new MapDef(() => new Set());\n /**\n * Cache score up to decayInterval if topic stats are unchanged.\n */\n scoreCache = new Map();\n /**\n * Recent message delivery timing/participants\n */\n deliveryRecords = new MessageDeliveries();\n _backgroundInterval;\n scoreCacheValidityMs;\n computeScore;\n log;\n constructor(params, metrics, componentLogger, opts) {\n this.params = params;\n this.metrics = metrics;\n validatePeerScoreParams(params);\n this.scoreCacheValidityMs = opts.scoreCacheValidityMs;\n this.computeScore = opts.computeScore ?? computeScore;\n this.log = componentLogger.forComponent('libp2p:gossipsub:score');\n }\n get size() {\n return this.peerStats.size;\n }\n /**\n * Start PeerScore instance\n */\n start() {\n if (this._backgroundInterval != null) {\n this.log('Peer score already running');\n return;\n }\n this._backgroundInterval = setInterval(() => { this.background(); }, this.params.decayInterval);\n this.log('started');\n }\n /**\n * Stop PeerScore instance\n */\n stop() {\n if (this._backgroundInterval == null) {\n this.log('Peer score already stopped');\n return;\n }\n clearInterval(this._backgroundInterval);\n delete this._backgroundInterval;\n this.peerIPs.clear();\n this.peerStats.clear();\n this.deliveryRecords.clear();\n this.log('stopped');\n }\n /**\n * Periodic maintenance\n */\n background() {\n this.refreshScores();\n this.deliveryRecords.gc();\n }\n dumpPeerScoreStats() {\n return Object.fromEntries(Array.from(this.peerStats.entries()).map(([peer, stats]) => [peer, stats]));\n }\n messageFirstSeenTimestampMs(msgIdStr) {\n const drec = this.deliveryRecords.getRecord(msgIdStr);\n return (drec != null) ? drec.firstSeenTsMs : null;\n }\n /**\n * Decays scores, and purges score records for disconnected peers once their expiry has elapsed.\n */\n refreshScores() {\n const now = Date.now();\n const decayToZero = this.params.decayToZero;\n this.peerStats.forEach((pstats, id) => {\n if (!pstats.connected) {\n // has the retention period expired?\n if (now > pstats.expire) {\n // yes, throw it away (but clean up the IP tracking first)\n this.removeIPsForPeer(id, pstats.knownIPs);\n this.peerStats.delete(id);\n this.scoreCache.delete(id);\n }\n // we don't decay retained scores, as the peer is not active.\n // this way the peer cannot reset a negative score by simply disconnecting and reconnecting,\n // unless the retention period has elapsed.\n // similarly, a well behaved peer does not lose its score by getting disconnected.\n return;\n }\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n const tparams = this.params.topics[topic];\n if (tparams === undefined) {\n // we are not scoring this topic\n // should be unreachable, we only add scored topics to pstats\n return;\n }\n // decay counters\n tstats.firstMessageDeliveries *= tparams.firstMessageDeliveriesDecay;\n if (tstats.firstMessageDeliveries < decayToZero) {\n tstats.firstMessageDeliveries = 0;\n }\n tstats.meshMessageDeliveries *= tparams.meshMessageDeliveriesDecay;\n if (tstats.meshMessageDeliveries < decayToZero) {\n tstats.meshMessageDeliveries = 0;\n }\n tstats.meshFailurePenalty *= tparams.meshFailurePenaltyDecay;\n if (tstats.meshFailurePenalty < decayToZero) {\n tstats.meshFailurePenalty = 0;\n }\n tstats.invalidMessageDeliveries *= tparams.invalidMessageDeliveriesDecay;\n if (tstats.invalidMessageDeliveries < decayToZero) {\n tstats.invalidMessageDeliveries = 0;\n }\n // update mesh time and activate mesh message delivery parameter if need be\n if (tstats.inMesh) {\n tstats.meshTime = now - tstats.graftTime;\n if (tstats.meshTime > tparams.meshMessageDeliveriesActivation) {\n tstats.meshMessageDeliveriesActive = true;\n }\n }\n });\n // decay P7 counter\n pstats.behaviourPenalty *= this.params.behaviourPenaltyDecay;\n if (pstats.behaviourPenalty < decayToZero) {\n pstats.behaviourPenalty = 0;\n }\n });\n }\n /**\n * Return the score for a peer\n */\n score(id) {\n this.metrics?.scoreFnCalls.inc();\n const pstats = this.peerStats.get(id);\n if (pstats == null) {\n return 0;\n }\n const now = Date.now();\n const cacheEntry = this.scoreCache.get(id);\n // Found cached score within validity period\n if ((cacheEntry != null) && cacheEntry.cacheUntil > now) {\n return cacheEntry.score;\n }\n this.metrics?.scoreFnRuns.inc();\n const score = this.computeScore(id, pstats, this.params, this.peerIPs);\n const cacheUntil = now + this.scoreCacheValidityMs;\n if (cacheEntry != null) {\n this.metrics?.scoreCachedDelta.observe(Math.abs(score - cacheEntry.score));\n cacheEntry.score = score;\n cacheEntry.cacheUntil = cacheUntil;\n }\n else {\n this.scoreCache.set(id, { score, cacheUntil });\n }\n return score;\n }\n /**\n * Apply a behavioural penalty to a peer\n */\n addPenalty(id, penalty, penaltyLabel) {\n const pstats = this.peerStats.get(id);\n if (pstats != null) {\n pstats.behaviourPenalty += penalty;\n this.metrics?.onScorePenalty(penaltyLabel);\n }\n }\n addPeer(id) {\n // create peer stats (not including topic stats for each topic to be scored)\n // topic stats will be added as needed\n const pstats = {\n connected: true,\n expire: 0,\n topics: {},\n knownIPs: new Set(),\n behaviourPenalty: 0\n };\n this.peerStats.set(id, pstats);\n }\n /** Adds a new IP to a peer, if the peer is not known the update is ignored */\n addIP(id, ip) {\n const pstats = this.peerStats.get(id);\n if (pstats != null) {\n pstats.knownIPs.add(ip);\n }\n this.peerIPs.getOrDefault(ip).add(id);\n }\n /** Remove peer association with IP */\n removeIP(id, ip) {\n const pstats = this.peerStats.get(id);\n if (pstats != null) {\n pstats.knownIPs.delete(ip);\n }\n const peersWithIP = this.peerIPs.get(ip);\n if (peersWithIP != null) {\n peersWithIP.delete(id);\n if (peersWithIP.size === 0) {\n this.peerIPs.delete(ip);\n }\n }\n }\n removePeer(id) {\n const pstats = this.peerStats.get(id);\n if (pstats == null) {\n return;\n }\n // decide whether to retain the score; this currently only retains non-positive scores\n // to dissuade attacks on the score function.\n if (this.score(id) > 0) {\n this.removeIPsForPeer(id, pstats.knownIPs);\n this.peerStats.delete(id);\n return;\n }\n // furthermore, when we decide to retain the score, the firstMessageDelivery counters are\n // reset to 0 and mesh delivery penalties applied.\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n tstats.firstMessageDeliveries = 0;\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold;\n if (tstats.inMesh && tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries;\n tstats.meshFailurePenalty += deficit * deficit;\n }\n tstats.inMesh = false;\n tstats.meshMessageDeliveriesActive = false;\n });\n pstats.connected = false;\n pstats.expire = Date.now() + this.params.retainScore;\n }\n /** Handles scoring functionality as a peer GRAFTs to a topic. */\n graft(id, topic) {\n const pstats = this.peerStats.get(id);\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic);\n if (tstats != null) {\n // if we are scoring the topic, update the mesh status.\n tstats.inMesh = true;\n tstats.graftTime = Date.now();\n tstats.meshTime = 0;\n tstats.meshMessageDeliveriesActive = false;\n }\n }\n }\n /** Handles scoring functionality as a peer PRUNEs from a topic. */\n prune(id, topic) {\n const pstats = this.peerStats.get(id);\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic);\n if (tstats != null) {\n // sticky mesh delivery rate failure penalty\n const threshold = this.params.topics[topic].meshMessageDeliveriesThreshold;\n if (tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold) {\n const deficit = threshold - tstats.meshMessageDeliveries;\n tstats.meshFailurePenalty += deficit * deficit;\n }\n tstats.meshMessageDeliveriesActive = false;\n tstats.inMesh = false;\n // TODO: Consider clearing score cache on important penalties\n // this.scoreCache.delete(id)\n }\n }\n }\n validateMessage(msgIdStr) {\n this.deliveryRecords.ensureRecord(msgIdStr);\n }\n deliverMessage(from, msgIdStr, topic) {\n this.markFirstMessageDelivery(from, topic);\n const drec = this.deliveryRecords.ensureRecord(msgIdStr);\n const now = Date.now();\n // defensive check that this is the first delivery trace -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n this.log('unexpected delivery: message from %s was first seen %s ago and has delivery status %s', from, now - drec.firstSeenTsMs, DeliveryRecordStatus[drec.status]);\n return;\n }\n // mark the message as valid and reward mesh peers that have already forwarded it to us\n drec.status = DeliveryRecordStatus.valid;\n drec.validated = now;\n drec.peers.forEach((p) => {\n // this check is to make sure a peer can't send us a message twice and get a double count\n // if it is a first delivery.\n if (p !== from.toString()) {\n this.markDuplicateMessageDelivery(p, topic);\n }\n });\n }\n /**\n * Similar to `rejectMessage` except does not require the message id or reason for an invalid message.\n */\n rejectInvalidMessage(from, topic) {\n this.markInvalidMessageDelivery(from, topic);\n }\n rejectMessage(from, msgIdStr, topic, reason) {\n // eslint-disable-next-line default-case\n switch (reason) {\n // these messages are not tracked, but the peer is penalized as they are invalid\n case RejectReason.Error:\n this.markInvalidMessageDelivery(from, topic);\n return;\n // we ignore those messages, so do nothing.\n case RejectReason.Blacklisted:\n return;\n // the rest are handled after record creation\n }\n const drec = this.deliveryRecords.ensureRecord(msgIdStr);\n // defensive check that this is the first rejection -- delivery status should be unknown\n if (drec.status !== DeliveryRecordStatus.unknown) {\n this.log('unexpected rejection: message from %s was first seen %s ago and has delivery status %d', from, Date.now() - drec.firstSeenTsMs, DeliveryRecordStatus[drec.status]);\n return;\n }\n if (reason === RejectReason.Ignore) {\n // we were explicitly instructed by the validator to ignore the message but not penalize the peer\n drec.status = DeliveryRecordStatus.ignored;\n drec.peers.clear();\n return;\n }\n // mark the message as invalid and penalize peers that have already forwarded it.\n drec.status = DeliveryRecordStatus.invalid;\n this.markInvalidMessageDelivery(from, topic);\n drec.peers.forEach((p) => {\n this.markInvalidMessageDelivery(p, topic);\n });\n // release the delivery time tracking map to free some memory early\n drec.peers.clear();\n }\n duplicateMessage(from, msgIdStr, topic) {\n const drec = this.deliveryRecords.ensureRecord(msgIdStr);\n if (drec.peers.has(from)) {\n // we have already seen this duplicate\n return;\n }\n // eslint-disable-next-line default-case\n switch (drec.status) {\n case DeliveryRecordStatus.unknown:\n // the message is being validated; track the peer delivery and wait for\n // the Deliver/Reject/Ignore notification.\n drec.peers.add(from);\n break;\n case DeliveryRecordStatus.valid:\n // mark the peer delivery time to only count a duplicate delivery once.\n drec.peers.add(from);\n this.markDuplicateMessageDelivery(from, topic, drec.validated);\n break;\n case DeliveryRecordStatus.invalid:\n // we no longer track delivery time\n this.markInvalidMessageDelivery(from, topic);\n break;\n case DeliveryRecordStatus.ignored:\n // the message was ignored; do nothing (we don't know if it was valid)\n break;\n }\n }\n /**\n * Increments the \"invalid message deliveries\" counter for all scored topics the message is published in.\n */\n markInvalidMessageDelivery(from, topic) {\n const pstats = this.peerStats.get(from);\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic);\n if (tstats != null) {\n tstats.invalidMessageDeliveries += 1;\n }\n }\n }\n /**\n * Increments the \"first message deliveries\" counter for all scored topics the message is published in,\n * as well as the \"mesh message deliveries\" counter, if the peer is in the mesh for the topic.\n * Messages already known (with the seenCache) are counted with markDuplicateMessageDelivery()\n */\n markFirstMessageDelivery(from, topic) {\n const pstats = this.peerStats.get(from);\n if (pstats != null) {\n const tstats = this.getPtopicStats(pstats, topic);\n if (tstats != null) {\n let cap = this.params.topics[topic].firstMessageDeliveriesCap;\n tstats.firstMessageDeliveries = Math.min(cap, tstats.firstMessageDeliveries + 1);\n if (tstats.inMesh) {\n cap = this.params.topics[topic].meshMessageDeliveriesCap;\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1);\n }\n }\n }\n }\n /**\n * Increments the \"mesh message deliveries\" counter for messages we've seen before,\n * as long the message was received within the P3 window.\n */\n markDuplicateMessageDelivery(from, topic, validatedTime) {\n const pstats = this.peerStats.get(from);\n if (pstats != null) {\n const now = validatedTime !== undefined ? Date.now() : 0;\n const tstats = this.getPtopicStats(pstats, topic);\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (tstats != null && tstats.inMesh) {\n const tparams = this.params.topics[topic];\n // check against the mesh delivery window -- if the validated time is passed as 0, then\n // the message was received before we finished validation and thus falls within the mesh\n // delivery window.\n if (validatedTime !== undefined) {\n const deliveryDelayMs = now - validatedTime;\n const isLateDelivery = deliveryDelayMs > tparams.meshMessageDeliveriesWindow;\n this.metrics?.onDuplicateMsgDelivery(topic, deliveryDelayMs, isLateDelivery);\n if (isLateDelivery) {\n return;\n }\n }\n const cap = tparams.meshMessageDeliveriesCap;\n tstats.meshMessageDeliveries = Math.min(cap, tstats.meshMessageDeliveries + 1);\n }\n }\n }\n /**\n * Removes an IP list from the tracking list for a peer.\n */\n removeIPsForPeer(id, ipsToRemove) {\n for (const ipToRemove of ipsToRemove) {\n const peerSet = this.peerIPs.get(ipToRemove);\n if (peerSet != null) {\n peerSet.delete(id);\n if (peerSet.size === 0) {\n this.peerIPs.delete(ipToRemove);\n }\n }\n }\n }\n /**\n * Returns topic stats if they exist, otherwise if the supplied parameters score the\n * topic, inserts the default stats and returns a reference to those. If neither apply, returns None.\n */\n getPtopicStats(pstats, topic) {\n let topicStats = pstats.topics[topic];\n if (topicStats !== undefined) {\n return topicStats;\n }\n if (this.params.topics[topic] !== undefined) {\n topicStats = {\n inMesh: false,\n graftTime: 0,\n meshTime: 0,\n firstMessageDeliveries: 0,\n meshMessageDeliveries: 0,\n meshMessageDeliveriesActive: false,\n meshFailurePenalty: 0,\n invalidMessageDeliveries: 0\n };\n pstats.topics[topic] = topicStats;\n return topicStats;\n }\n return null;\n }\n}\n//# sourceMappingURL=peer-score.js.map","export function computeScoreWeights(peer, pstats, params, peerIPs, topicStrToLabel) {\n let score = 0;\n const byTopic = new Map();\n // topic stores\n Object.entries(pstats.topics).forEach(([topic, tstats]) => {\n // the topic parameters\n // Aggregate by known topicLabel or throw to 'unknown'. This prevent too high cardinality\n const topicLabel = topicStrToLabel.get(topic) ?? 'unknown';\n const topicParams = params.topics[topic];\n if (topicParams === undefined) {\n // we are not scoring this topic\n return;\n }\n let topicScores = byTopic.get(topicLabel);\n if (topicScores == null) {\n topicScores = {\n p1w: 0,\n p2w: 0,\n p3w: 0,\n p3bw: 0,\n p4w: 0\n };\n byTopic.set(topicLabel, topicScores);\n }\n let p1w = 0;\n let p2w = 0;\n let p3w = 0;\n let p3bw = 0;\n let p4w = 0;\n // P1: time in Mesh\n if (tstats.inMesh) {\n const p1 = Math.max(tstats.meshTime / topicParams.timeInMeshQuantum, topicParams.timeInMeshCap);\n p1w += p1 * topicParams.timeInMeshWeight;\n }\n // P2: first message deliveries\n let p2 = tstats.firstMessageDeliveries;\n if (p2 > topicParams.firstMessageDeliveriesCap) {\n p2 = topicParams.firstMessageDeliveriesCap;\n }\n p2w += p2 * topicParams.firstMessageDeliveriesWeight;\n // P3: mesh message deliveries\n if (tstats.meshMessageDeliveriesActive &&\n tstats.meshMessageDeliveries < topicParams.meshMessageDeliveriesThreshold) {\n const deficit = topicParams.meshMessageDeliveriesThreshold - tstats.meshMessageDeliveries;\n const p3 = deficit * deficit;\n p3w += p3 * topicParams.meshMessageDeliveriesWeight;\n }\n // P3b:\n // NOTE: the weight of P3b is negative (validated in validateTopicScoreParams) so this detracts\n const p3b = tstats.meshFailurePenalty;\n p3bw += p3b * topicParams.meshFailurePenaltyWeight;\n // P4: invalid messages\n // NOTE: the weight of P4 is negative (validated in validateTopicScoreParams) so this detracts\n const p4 = tstats.invalidMessageDeliveries * tstats.invalidMessageDeliveries;\n p4w += p4 * topicParams.invalidMessageDeliveriesWeight;\n // update score, mixing with topic weight\n score += (p1w + p2w + p3w + p3bw + p4w) * topicParams.topicWeight;\n topicScores.p1w += p1w;\n topicScores.p2w += p2w;\n topicScores.p3w += p3w;\n topicScores.p3bw += p3bw;\n topicScores.p4w += p4w;\n });\n // apply the topic score cap, if any\n if (params.topicScoreCap > 0 && score > params.topicScoreCap) {\n score = params.topicScoreCap;\n // Proportionally apply cap to all individual contributions\n const capF = params.topicScoreCap / score;\n for (const ws of byTopic.values()) {\n ws.p1w *= capF;\n ws.p2w *= capF;\n ws.p3w *= capF;\n ws.p3bw *= capF;\n ws.p4w *= capF;\n }\n }\n let p5w = 0;\n let p6w = 0;\n let p7w = 0;\n // P5: application-specific score\n const p5 = params.appSpecificScore(peer);\n p5w += p5 * params.appSpecificWeight;\n // P6: IP colocation factor\n pstats.knownIPs.forEach((ip) => {\n if (params.IPColocationFactorWhitelist.has(ip)) {\n return;\n }\n // P6 has a cliff (IPColocationFactorThreshold)\n // It's only applied if at least that many peers are connected to us from that source IP addr.\n // It is quadratic, and the weight is negative (validated in validatePeerScoreParams)\n const peersInIP = peerIPs.get(ip);\n const numPeersInIP = (peersInIP != null) ? peersInIP.size : 0;\n if (numPeersInIP > params.IPColocationFactorThreshold) {\n const surplus = numPeersInIP - params.IPColocationFactorThreshold;\n const p6 = surplus * surplus;\n p6w += p6 * params.IPColocationFactorWeight;\n }\n });\n // P7: behavioural pattern penalty\n const p7 = pstats.behaviourPenalty * pstats.behaviourPenalty;\n p7w += p7 * params.behaviourPenaltyWeight;\n score += p5w + p6w + p7w;\n return {\n byTopic,\n p5w,\n p6w,\n p7w,\n score\n };\n}\nexport function computeAllPeersScoreWeights(peerIdStrs, peerStats, params, peerIPs, topicStrToLabel) {\n const sw = {\n byTopic: new Map(),\n p5w: [],\n p6w: [],\n p7w: [],\n score: []\n };\n for (const peerIdStr of peerIdStrs) {\n const pstats = peerStats.get(peerIdStr);\n if (pstats != null) {\n const swPeer = computeScoreWeights(peerIdStr, pstats, params, peerIPs, topicStrToLabel);\n for (const [topic, swPeerTopic] of swPeer.byTopic) {\n let swTopic = sw.byTopic.get(topic);\n if (swTopic == null) {\n swTopic = {\n p1w: [],\n p2w: [],\n p3w: [],\n p3bw: [],\n p4w: []\n };\n sw.byTopic.set(topic, swTopic);\n }\n swTopic.p1w.push(swPeerTopic.p1w);\n swTopic.p2w.push(swPeerTopic.p2w);\n swTopic.p3w.push(swPeerTopic.p3w);\n swTopic.p3bw.push(swPeerTopic.p3bw);\n swTopic.p4w.push(swPeerTopic.p4w);\n }\n sw.p5w.push(swPeer.p5w);\n sw.p6w.push(swPeer.p6w);\n sw.p7w.push(swPeer.p7w);\n sw.score.push(swPeer.score);\n }\n else {\n sw.p5w.push(0);\n sw.p6w.push(0);\n sw.p7w.push(0);\n sw.score.push(0);\n }\n }\n return sw;\n}\n//# sourceMappingURL=scoreMetrics.js.map","import { encode, decode } from 'it-length-prefixed';\nimport { pipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nexport class OutboundStream {\n rawStream;\n pushable;\n closeController;\n maxBufferSize;\n constructor(rawStream, errCallback, opts) {\n this.rawStream = rawStream;\n this.pushable = pushable();\n this.closeController = new AbortController();\n this.maxBufferSize = opts.maxBufferSize ?? Infinity;\n this.closeController.signal.addEventListener('abort', () => {\n rawStream.close()\n .catch(err => {\n rawStream.abort(err);\n });\n });\n pipe(this.pushable, this.rawStream).catch(errCallback);\n }\n get protocol() {\n // TODO remove this non-nullish assertion after https://github.com/libp2p/js-libp2p-interfaces/pull/265 is incorporated\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.rawStream.protocol;\n }\n push(data) {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);\n }\n this.pushable.push(encode.single(data));\n }\n /**\n * Same to push() but this is prefixed data so no need to encode length prefixed again\n */\n pushPrefixed(data) {\n if (this.pushable.readableLength > this.maxBufferSize) {\n throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);\n }\n this.pushable.push(data);\n }\n async close() {\n this.closeController.abort();\n // similar to pushable.end() but clear the internal buffer\n await this.pushable.return();\n }\n}\nexport class InboundStream {\n source;\n rawStream;\n closeController;\n constructor(rawStream, opts = {}) {\n this.rawStream = rawStream;\n this.closeController = new AbortController();\n this.closeController.signal.addEventListener('abort', () => {\n rawStream.close()\n .catch(err => {\n rawStream.abort(err);\n });\n });\n this.source = pipe(this.rawStream, (source) => decode(source, opts));\n }\n async close() {\n this.closeController.abort();\n }\n}\n//# sourceMappingURL=stream.js.map","import { RejectReason } from './types.js';\n/**\n * IWantTracer is an internal tracer that tracks IWANT requests in order to penalize\n * peers who don't follow up on IWANT requests after an IHAVE advertisement.\n * The tracking of promises is probabilistic to avoid using too much memory.\n *\n * Note: Do not confuse these 'promises' with JS Promise objects.\n * These 'promises' are merely expectations of a peer's behavior.\n */\nexport class IWantTracer {\n gossipsubIWantFollowupMs;\n msgIdToStrFn;\n metrics;\n /**\n * Promises to deliver a message\n * Map per message id, per peer, promise expiration time\n */\n promises = new Map();\n /**\n * First request time by msgId. Used for metrics to track expire times.\n * Necessary to know if peers are actually breaking promises or simply sending them a bit later\n */\n requestMsByMsg = new Map();\n requestMsByMsgExpire;\n constructor(gossipsubIWantFollowupMs, msgIdToStrFn, metrics) {\n this.gossipsubIWantFollowupMs = gossipsubIWantFollowupMs;\n this.msgIdToStrFn = msgIdToStrFn;\n this.metrics = metrics;\n this.requestMsByMsgExpire = 10 * gossipsubIWantFollowupMs;\n }\n get size() {\n return this.promises.size;\n }\n get requestMsByMsgSize() {\n return this.requestMsByMsg.size;\n }\n /**\n * Track a promise to deliver a message from a list of msgIds we are requesting\n */\n addPromise(from, msgIds) {\n // pick msgId randomly from the list\n const ix = Math.floor(Math.random() * msgIds.length);\n const msgId = msgIds[ix];\n const msgIdStr = this.msgIdToStrFn(msgId);\n let expireByPeer = this.promises.get(msgIdStr);\n if (expireByPeer == null) {\n expireByPeer = new Map();\n this.promises.set(msgIdStr, expireByPeer);\n }\n const now = Date.now();\n // If a promise for this message id and peer already exists we don't update the expiry\n if (!expireByPeer.has(from)) {\n expireByPeer.set(from, now + this.gossipsubIWantFollowupMs);\n if (this.metrics != null) {\n this.metrics.iwantPromiseStarted.inc(1);\n if (!this.requestMsByMsg.has(msgIdStr)) {\n this.requestMsByMsg.set(msgIdStr, now);\n }\n }\n }\n }\n /**\n * Returns the number of broken promises for each peer who didn't follow up on an IWANT request.\n *\n * This should be called not too often relative to the expire times, since it iterates over the whole data.\n */\n getBrokenPromises() {\n const now = Date.now();\n const result = new Map();\n let brokenPromises = 0;\n this.promises.forEach((expireByPeer, msgId) => {\n expireByPeer.forEach((expire, p) => {\n // the promise has been broken\n if (expire < now) {\n // add 1 to result\n result.set(p, (result.get(p) ?? 0) + 1);\n // delete from tracked promises\n expireByPeer.delete(p);\n // for metrics\n brokenPromises++;\n }\n });\n // clean up empty promises for a msgId\n if (expireByPeer.size === 0) {\n this.promises.delete(msgId);\n }\n });\n this.metrics?.iwantPromiseBroken.inc(brokenPromises);\n return result;\n }\n /**\n * Someone delivered a message, stop tracking promises for it\n */\n deliverMessage(msgIdStr, isDuplicate = false) {\n this.trackMessage(msgIdStr);\n const expireByPeer = this.promises.get(msgIdStr);\n // Expired promise, check requestMsByMsg\n if (expireByPeer != null) {\n this.promises.delete(msgIdStr);\n if (this.metrics != null) {\n this.metrics.iwantPromiseResolved.inc(1);\n if (isDuplicate)\n this.metrics.iwantPromiseResolvedFromDuplicate.inc(1);\n this.metrics.iwantPromiseResolvedPeers.inc(expireByPeer.size);\n }\n }\n }\n /**\n * A message got rejected, so we can stop tracking promises and let the score penalty apply from invalid message delivery,\n * unless its an obviously invalid message.\n */\n rejectMessage(msgIdStr, reason) {\n this.trackMessage(msgIdStr);\n // A message got rejected, so we can stop tracking promises and let the score penalty apply.\n // With the expection of obvious invalid messages\n switch (reason) {\n case RejectReason.Error:\n return;\n default:\n break;\n }\n this.promises.delete(msgIdStr);\n }\n clear() {\n this.promises.clear();\n }\n prune() {\n const maxMs = Date.now() - this.requestMsByMsgExpire;\n let count = 0;\n for (const [k, v] of this.requestMsByMsg.entries()) {\n if (v < maxMs) {\n // messages that stay too long in the requestMsByMsg map, delete\n this.requestMsByMsg.delete(k);\n count++;\n }\n else {\n // recent messages, keep them\n // sort by insertion order\n break;\n }\n }\n this.metrics?.iwantMessagePruned.inc(count);\n }\n trackMessage(msgIdStr) {\n if (this.metrics != null) {\n const requestMs = this.requestMsByMsg.get(msgIdStr);\n if (requestMs !== undefined) {\n this.metrics.iwantPromiseDeliveryTime.observe((Date.now() - requestMs) / 1000);\n this.requestMsByMsg.delete(msgIdStr);\n }\n }\n }\n}\n//# sourceMappingURL=tracer.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { StrictSign, StrictNoSign } from '@libp2p/interface';\nimport { peerIdFromBytes } from '@libp2p/peer-id';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RPC } from '../message/rpc.js';\nimport { PublishConfigType, ValidateError } from '../types.js';\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:');\nexport async function buildRawMessage(publishConfig, topic, originalData, transformedData) {\n switch (publishConfig.type) {\n case PublishConfigType.Signing: {\n const rpcMsg = {\n from: publishConfig.author.toBytes(),\n data: transformedData,\n seqno: randomBytes(8),\n topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n };\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsg)]);\n rpcMsg.signature = await publishConfig.privateKey.sign(bytes);\n rpcMsg.key = publishConfig.key;\n const msg = {\n type: 'signed',\n from: publishConfig.author,\n data: originalData,\n sequenceNumber: BigInt(`0x${uint8ArrayToString(rpcMsg.seqno, 'base16')}`),\n topic,\n signature: rpcMsg.signature,\n key: rpcMsg.key\n };\n return {\n raw: rpcMsg,\n msg\n };\n }\n case PublishConfigType.Anonymous: {\n return {\n raw: {\n from: undefined,\n data: transformedData,\n seqno: undefined,\n topic,\n signature: undefined,\n key: undefined\n },\n msg: {\n type: 'unsigned',\n data: originalData,\n topic\n }\n };\n }\n default:\n throw new Error('Unreachable');\n }\n}\nexport async function validateToRawMessage(signaturePolicy, msg) {\n // If strict-sign, verify all\n // If anonymous (no-sign), ensure no preven\n switch (signaturePolicy) {\n case StrictNoSign:\n if (msg.signature != null)\n return { valid: false, error: ValidateError.SignaturePresent };\n if (msg.seqno != null)\n return { valid: false, error: ValidateError.SeqnoPresent };\n if (msg.key != null)\n return { valid: false, error: ValidateError.FromPresent };\n return { valid: true, message: { type: 'unsigned', topic: msg.topic, data: msg.data ?? new Uint8Array(0) } };\n case StrictSign: {\n // Verify seqno\n if (msg.seqno == null)\n return { valid: false, error: ValidateError.InvalidSeqno };\n if (msg.seqno.length !== 8) {\n return { valid: false, error: ValidateError.InvalidSeqno };\n }\n if (msg.signature == null)\n return { valid: false, error: ValidateError.InvalidSignature };\n if (msg.from == null)\n return { valid: false, error: ValidateError.InvalidPeerId };\n let fromPeerId;\n try {\n // TODO: Fix PeerId types\n fromPeerId = peerIdFromBytes(msg.from);\n }\n catch (e) {\n return { valid: false, error: ValidateError.InvalidPeerId };\n }\n // - check from defined\n // - transform source to PeerId\n // - parse signature\n // - get .key, else from source\n // - check key == source if present\n // - verify sig\n let publicKey;\n if (msg.key != null) {\n publicKey = unmarshalPublicKey(msg.key);\n // TODO: Should `fromPeerId.pubKey` be optional?\n if (fromPeerId.publicKey !== undefined && !uint8ArrayEquals(publicKey.bytes, fromPeerId.publicKey)) {\n return { valid: false, error: ValidateError.InvalidPeerId };\n }\n }\n else {\n if (fromPeerId.publicKey == null) {\n return { valid: false, error: ValidateError.InvalidPeerId };\n }\n publicKey = unmarshalPublicKey(fromPeerId.publicKey);\n }\n const rpcMsgPreSign = {\n from: msg.from,\n data: msg.data,\n seqno: msg.seqno,\n topic: msg.topic,\n signature: undefined, // Exclude signature field for signing\n key: undefined // Exclude key field for signing\n };\n // Get the message in bytes, and prepend with the pubsub prefix\n // the signature is over the bytes \"libp2p-pubsub:\"\n const bytes = uint8ArrayConcat([SignPrefix, RPC.Message.encode(rpcMsgPreSign)]);\n if (!(await publicKey.verify(bytes, msg.signature))) {\n return { valid: false, error: ValidateError.InvalidSignature };\n }\n return {\n valid: true,\n message: {\n type: 'signed',\n from: fromPeerId,\n data: msg.data ?? new Uint8Array(0),\n sequenceNumber: BigInt(`0x${uint8ArrayToString(msg.seqno, 'base16')}`),\n topic: msg.topic,\n signature: msg.signature,\n key: msg.key ?? marshalPublicKey(publicKey)\n }\n };\n }\n default:\n throw new Error('Unreachable');\n }\n}\n//# sourceMappingURL=buildRawMessage.js.map","/**\n * Create a gossipsub RPC object\n */\nexport function createGossipRpc(messages = [], control) {\n return {\n subscriptions: [],\n messages,\n control: control !== undefined\n ? {\n graft: control.graft ?? [],\n prune: control.prune ?? [],\n ihave: control.ihave ?? [],\n iwant: control.iwant ?? []\n }\n : undefined\n };\n}\nexport function ensureControl(rpc) {\n if (rpc.control === undefined) {\n rpc.control = {\n graft: [],\n prune: [],\n ihave: [],\n iwant: []\n };\n }\n return rpc;\n}\n//# sourceMappingURL=create-gossip-rpc.js.map","import { toString } from 'uint8arrays/to-string';\n/**\n * Browser friendly function to convert Uint8Array message id to base64 string.\n */\nexport function messageIdToString(msgId) {\n return toString(msgId, 'base64');\n}\n//# sourceMappingURL=messageIdToString.js.map","/**\n * Pseudo-randomly shuffles an array\n *\n * Mutates the input array\n */\nexport function shuffle(arr) {\n if (arr.length <= 1) {\n return arr;\n }\n const randInt = () => {\n return Math.floor(Math.random() * Math.floor(arr.length));\n };\n for (let i = 0; i < arr.length; i++) {\n const j = randInt();\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n return arr;\n}\n//# sourceMappingURL=shuffle.js.map","import { msgId } from '@libp2p/pubsub/utils';\nimport { sha256 } from 'multiformats/hashes/sha2';\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport function msgIdFnStrictSign(msg) {\n if (msg.type !== 'signed') {\n throw new Error('expected signed message type');\n }\n // Should never happen\n if (msg.sequenceNumber == null)\n throw Error('missing seqno field');\n // TODO: Should use .from here or key?\n return msgId(msg.from.toBytes(), msg.sequenceNumber);\n}\n/**\n * Generate a message id, based on message `data`\n */\nexport async function msgIdFnStrictNoSign(msg) {\n return sha256.encode(msg.data);\n}\n//# sourceMappingURL=msgIdFn.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { CodeError } from '@libp2p/interface';\nimport { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { codes } from './errors.js';\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno() {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`);\n}\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key, seqno) => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16');\n const msgId = new Uint8Array(key.length + seqnoBytes.length);\n msgId.set(key, 0);\n msgId.set(seqnoBytes, key.length);\n return msgId;\n};\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data) => {\n return sha256.encode(data);\n};\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a, b) => {\n let bHas;\n if (Array.isArray(b)) {\n bHas = (val) => b.includes(val);\n }\n else {\n bHas = (val) => b.has(val);\n }\n for (const val of a) {\n if (bHas(val)) {\n return true;\n }\n }\n return false;\n};\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray) {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray];\n }\n return maybeArray;\n};\nconst isSigned = async (message) => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false;\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromBytes(message.from);\n if (fromID.publicKey != null) {\n return true;\n }\n if (message.key != null) {\n const signingID = await peerIdFromKeys(message.key);\n return signingID.equals(fromID);\n }\n return false;\n};\nexport const toMessage = async (message) => {\n if (message.from == null) {\n throw new CodeError('RPC message was missing from', codes.ERR_MISSING_FROM);\n }\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n };\n }\n const from = peerIdFromBytes(message.from);\n const msg = {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: message.key ?? from.publicKey ?? new Uint8Array(0)\n };\n if (msg.key.length === 0) {\n throw new CodeError('Signed RPC message was missing key', codes.ERR_MISSING_KEY);\n }\n return msg;\n};\nexport const toRpcMessage = (message) => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n };\n }\n return {\n data: message.data,\n topic: message.topic\n };\n};\nexport const bigIntToBytes = (num) => {\n let str = num.toString(16);\n if (str.length % 2 !== 0) {\n str = `0${str}`;\n }\n return uint8ArrayFromString(str, 'base16');\n};\nexport const bigIntFromBytes = (num) => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`);\n};\n//# sourceMappingURL=utils.js.map","import { convertToString } from '@multiformats/multiaddr/convert';\n// Protocols https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n// code size name\n// 4 32 ip4\n// 41 128 ip6\nvar Protocol;\n(function (Protocol) {\n Protocol[Protocol[\"ip4\"] = 4] = \"ip4\";\n Protocol[Protocol[\"ip6\"] = 41] = \"ip6\";\n})(Protocol || (Protocol = {}));\nexport function multiaddrToIPStr(multiaddr) {\n for (const tuple of multiaddr.tuples()) {\n switch (tuple[0]) {\n case Protocol.ip4:\n case Protocol.ip6:\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return convertToString(tuple[0], tuple[1]);\n default:\n break;\n }\n }\n return null;\n}\n//# sourceMappingURL=multiaddr.js.map","import { CustomEvent, TypedEventEmitter, StrictSign, StrictNoSign, TopicValidatorResult } from '@libp2p/interface';\nimport { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id';\nimport { encode } from 'it-length-prefixed';\nimport { pipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nimport * as constants from './constants.js';\nimport { ACCEPT_FROM_WHITELIST_DURATION_MS, ACCEPT_FROM_WHITELIST_MAX_MESSAGES, ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE, BACKOFF_SLACK } from './constants.js';\nimport { defaultDecodeRpcLimits } from './message/decodeRpc.js';\nimport { RPC } from './message/rpc.js';\nimport { MessageCache } from './message-cache.js';\nimport { ChurnReason, getMetrics, IHaveIgnoreReason, InclusionReason, ScorePenalty } from './metrics.js';\nimport { PeerScore, createPeerScoreParams, createPeerScoreThresholds } from './score/index.js';\nimport { computeAllPeersScoreWeights } from './score/scoreMetrics.js';\nimport { InboundStream, OutboundStream } from './stream.js';\nimport { IWantTracer } from './tracer.js';\nimport { ValidateError, MessageStatus, RejectReason, rejectReasonFromAcceptance } from './types.js';\nimport { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js';\nimport { createGossipRpc, ensureControl } from './utils/create-gossip-rpc.js';\nimport { shuffle, messageIdToString } from './utils/index.js';\nimport { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js';\nimport { multiaddrToIPStr } from './utils/multiaddr.js';\nimport { getPublishConfigFromPeerId } from './utils/publishConfig.js';\nimport { removeFirstNItemsFromSet, removeItemsFromSet } from './utils/set.js';\nimport { SimpleTimeCache } from './utils/time-cache.js';\nexport const multicodec = constants.GossipsubIDv11;\nvar GossipStatusCode;\n(function (GossipStatusCode) {\n GossipStatusCode[GossipStatusCode[\"started\"] = 0] = \"started\";\n GossipStatusCode[GossipStatusCode[\"stopped\"] = 1] = \"stopped\";\n})(GossipStatusCode || (GossipStatusCode = {}));\nexport class GossipSub extends TypedEventEmitter {\n /**\n * The signature policy to follow by default\n */\n globalSignaturePolicy;\n multicodecs = [constants.GossipsubIDv11, constants.GossipsubIDv10];\n publishConfig;\n dataTransform;\n // State\n peers = new Set();\n streamsInbound = new Map();\n streamsOutbound = new Map();\n /** Ensures outbound streams are created sequentially */\n outboundInflightQueue = pushable({ objectMode: true });\n /** Direct peers */\n direct = new Set();\n /** Floodsub peers */\n floodsubPeers = new Set();\n /** Cache of seen messages */\n seenCache;\n /**\n * Map of peer id and AcceptRequestWhileListEntry\n */\n acceptFromWhitelist = new Map();\n /**\n * Map of topics to which peers are subscribed to\n */\n topics = new Map();\n /**\n * List of our subscriptions\n */\n subscriptions = new Set();\n /**\n * Map of topic meshes\n * topic => peer id set\n */\n mesh = new Map();\n /**\n * Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership\n * topic => peer id set\n */\n fanout = new Map();\n /**\n * Map of last publish time for fanout topics\n * topic => last publish time\n */\n fanoutLastpub = new Map();\n /**\n * Map of pending messages to gossip\n * peer id => control messages\n */\n gossip = new Map();\n /**\n * Map of control messages\n * peer id => control message\n */\n control = new Map();\n /**\n * Number of IHAVEs received from peer in the last heartbeat\n */\n peerhave = new Map();\n /** Number of messages we have asked from peer in the last heartbeat */\n iasked = new Map();\n /** Prune backoff map */\n backoff = new Map();\n /**\n * Connection direction cache, marks peers with outbound connections\n * peer id => direction\n */\n outbound = new Map();\n msgIdFn;\n /**\n * A fast message id function used for internal message de-duplication\n */\n fastMsgIdFn;\n msgIdToStrFn;\n /** Maps fast message-id to canonical message-id */\n fastMsgIdCache;\n /**\n * Short term cache for published message ids. This is used for penalizing peers sending\n * our own messages back if the messages are anonymous or use a random author.\n */\n publishedMessageIds;\n /**\n * A message cache that contains the messages for last few heartbeat ticks\n */\n mcache;\n /** Peer score tracking */\n score;\n /**\n * Custom validator function per topic.\n * Must return or resolve quickly (< 100ms) to prevent causing penalties for late messages.\n * If you need to apply validation that may require longer times use `asyncValidation` option and callback the\n * validation result through `Gossipsub.reportValidationResult`\n */\n topicValidators = new Map();\n /**\n * Make this protected so child class may want to redirect to its own log.\n */\n log;\n /**\n * Number of heartbeats since the beginning of time\n * This allows us to amortize some resource cleanup -- eg: backoff cleanup\n */\n heartbeatTicks = 0;\n /**\n * Tracks IHAVE/IWANT promises broken by peers\n */\n gossipTracer;\n components;\n directPeerInitial = null;\n static multicodec = constants.GossipsubIDv11;\n // Options\n opts;\n decodeRpcLimits;\n metrics;\n status = { code: GossipStatusCode.stopped };\n maxInboundStreams;\n maxOutboundStreams;\n runOnTransientConnection;\n allowedTopics;\n heartbeatTimer = null;\n constructor(components, options = {}) {\n super();\n const opts = {\n fallbackToFloodsub: true,\n floodPublish: true,\n batchPublish: false,\n doPX: false,\n directPeers: [],\n D: constants.GossipsubD,\n Dlo: constants.GossipsubDlo,\n Dhi: constants.GossipsubDhi,\n Dscore: constants.GossipsubDscore,\n Dout: constants.GossipsubDout,\n Dlazy: constants.GossipsubDlazy,\n heartbeatInterval: constants.GossipsubHeartbeatInterval,\n fanoutTTL: constants.GossipsubFanoutTTL,\n mcacheLength: constants.GossipsubHistoryLength,\n mcacheGossip: constants.GossipsubHistoryGossip,\n seenTTL: constants.GossipsubSeenTTL,\n gossipsubIWantFollowupMs: constants.GossipsubIWantFollowupTime,\n prunePeers: constants.GossipsubPrunePeers,\n pruneBackoff: constants.GossipsubPruneBackoff,\n unsubcribeBackoff: constants.GossipsubUnsubscribeBackoff,\n graftFloodThreshold: constants.GossipsubGraftFloodThreshold,\n opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,\n opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,\n directConnectTicks: constants.GossipsubDirectConnectTicks,\n ...options,\n scoreParams: createPeerScoreParams(options.scoreParams),\n scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)\n };\n this.components = components;\n this.decodeRpcLimits = opts.decodeRpcLimits ?? defaultDecodeRpcLimits;\n this.globalSignaturePolicy = opts.globalSignaturePolicy ?? StrictSign;\n // Also wants to get notified of peers connected using floodsub\n if (opts.fallbackToFloodsub) {\n this.multicodecs.push(constants.FloodsubID);\n }\n // From pubsub\n this.log = components.logger.forComponent(opts.debugName ?? 'libp2p:gossipsub');\n // Gossipsub\n this.opts = opts;\n this.direct = new Set(opts.directPeers.map((p) => p.id.toString()));\n this.seenCache = new SimpleTimeCache({ validityMs: opts.seenTTL });\n this.publishedMessageIds = new SimpleTimeCache({ validityMs: opts.seenTTL });\n if (options.msgIdFn != null) {\n // Use custom function\n this.msgIdFn = options.msgIdFn;\n }\n else {\n switch (this.globalSignaturePolicy) {\n case StrictSign:\n this.msgIdFn = msgIdFnStrictSign;\n break;\n case StrictNoSign:\n this.msgIdFn = msgIdFnStrictNoSign;\n break;\n default:\n throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`);\n }\n }\n if (options.fastMsgIdFn != null) {\n this.fastMsgIdFn = options.fastMsgIdFn;\n this.fastMsgIdCache = new SimpleTimeCache({ validityMs: opts.seenTTL });\n }\n // By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.\n this.msgIdToStrFn = options.msgIdToStrFn ?? messageIdToString;\n this.mcache = options.messageCache ?? new MessageCache(opts.mcacheGossip, opts.mcacheLength, this.msgIdToStrFn);\n if (options.dataTransform != null) {\n this.dataTransform = options.dataTransform;\n }\n if (options.metricsRegister != null) {\n if (options.metricsTopicStrToLabel == null) {\n throw Error('Must set metricsTopicStrToLabel with metrics');\n }\n // in theory, each topic has its own meshMessageDeliveriesWindow param\n // however in lodestar, we configure it mostly the same so just pick the max of positive ones\n // (some topics have meshMessageDeliveriesWindow as 0)\n const maxMeshMessageDeliveriesWindowMs = Math.max(...Object.values(opts.scoreParams.topics).map((topicParam) => topicParam.meshMessageDeliveriesWindow), constants.DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS);\n const metrics = getMetrics(options.metricsRegister, options.metricsTopicStrToLabel, {\n gossipPromiseExpireSec: this.opts.gossipsubIWantFollowupMs / 1000,\n behaviourPenaltyThreshold: opts.scoreParams.behaviourPenaltyThreshold,\n maxMeshMessageDeliveriesWindowSec: maxMeshMessageDeliveriesWindowMs / 1000\n });\n metrics.mcacheSize.addCollect(() => { this.onScrapeMetrics(metrics); });\n for (const protocol of this.multicodecs) {\n metrics.protocolsEnabled.set({ protocol }, 1);\n }\n this.metrics = metrics;\n }\n else {\n this.metrics = null;\n }\n this.gossipTracer = new IWantTracer(this.opts.gossipsubIWantFollowupMs, this.msgIdToStrFn, this.metrics);\n /**\n * libp2p\n */\n this.score = new PeerScore(this.opts.scoreParams, this.metrics, this.components.logger, {\n scoreCacheValidityMs: opts.heartbeatInterval\n });\n this.maxInboundStreams = options.maxInboundStreams;\n this.maxOutboundStreams = options.maxOutboundStreams;\n this.runOnTransientConnection = options.runOnTransientConnection;\n this.allowedTopics = (opts.allowedTopics != null) ? new Set(opts.allowedTopics) : null;\n }\n getPeers() {\n return [...this.peers.keys()].map((str) => peerIdFromString(str));\n }\n isStarted() {\n return this.status.code === GossipStatusCode.started;\n }\n // LIFECYCLE METHODS\n /**\n * Mounts the gossipsub protocol onto the libp2p node and sends our\n * our subscriptions to every peer connected\n */\n async start() {\n // From pubsub\n if (this.isStarted()) {\n return;\n }\n this.log('starting');\n this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.peerId);\n // Create the outbound inflight queue\n // This ensures that outbound stream creation happens sequentially\n this.outboundInflightQueue = pushable({ objectMode: true });\n pipe(this.outboundInflightQueue, async (source) => {\n for await (const { peerId, connection } of source) {\n await this.createOutboundStream(peerId, connection);\n }\n }).catch((e) => { this.log.error('outbound inflight queue error', e); });\n // set direct peer addresses in the address book\n await Promise.all(this.opts.directPeers.map(async (p) => {\n await this.components.peerStore.merge(p.id, {\n multiaddrs: p.addrs\n });\n }));\n const registrar = this.components.registrar;\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(this.multicodecs.map(async (multicodec) => registrar.handle(multicodec, this.onIncomingStream.bind(this), {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n })));\n // # How does Gossipsub interact with libp2p? Rough guide from Mar 2022\n //\n // ## Setup:\n // Gossipsub requests libp2p to callback, TBD\n //\n // `this.libp2p.handle()` registers a handler for `/meshsub/1.1.0` and other Gossipsub protocols\n // The handler callback is registered in libp2p Upgrader.protocols map.\n //\n // Upgrader receives an inbound connection from some transport and (`Upgrader.upgradeInbound`):\n // - Adds encryption (NOISE in our case)\n // - Multiplex stream\n // - Create a muxer and register that for each new stream call Upgrader.protocols handler\n //\n // ## Topology\n // - new instance of Topology (unlinked to libp2p) with handlers\n // - registar.register(topology)\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology = {\n onConnect: this.onPeerConnected.bind(this),\n onDisconnect: this.onPeerDisconnected.bind(this),\n notifyOnTransient: this.runOnTransientConnection\n };\n const registrarTopologyIds = await Promise.all(this.multicodecs.map(async (multicodec) => registrar.register(multicodec, topology)));\n // Schedule to start heartbeat after `GossipsubHeartbeatInitialDelay`\n const heartbeatTimeout = setTimeout(this.runHeartbeat, constants.GossipsubHeartbeatInitialDelay);\n // Then, run heartbeat every `heartbeatInterval` offset by `GossipsubHeartbeatInitialDelay`\n this.status = {\n code: GossipStatusCode.started,\n registrarTopologyIds,\n heartbeatTimeout,\n hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay\n };\n this.score.start();\n // connect to direct peers\n this.directPeerInitial = setTimeout(() => {\n Promise.resolve()\n .then(async () => {\n await Promise.all(Array.from(this.direct).map(async (id) => this.connect(id)));\n })\n .catch((err) => {\n this.log(err);\n });\n }, constants.GossipsubDirectConnectInitialDelay);\n this.log('started');\n }\n /**\n * Unmounts the gossipsub protocol and shuts down every connection\n */\n async stop() {\n this.log('stopping');\n // From pubsub\n if (this.status.code !== GossipStatusCode.started) {\n return;\n }\n const { registrarTopologyIds } = this.status;\n this.status = { code: GossipStatusCode.stopped };\n // unregister protocol and handlers\n const registrar = this.components.registrar;\n await Promise.all(this.multicodecs.map(async (multicodec) => registrar.unhandle(multicodec)));\n registrarTopologyIds.forEach((id) => { registrar.unregister(id); });\n this.outboundInflightQueue.end();\n const closePromises = [];\n for (const outboundStream of this.streamsOutbound.values()) {\n closePromises.push(outboundStream.close());\n }\n this.streamsOutbound.clear();\n for (const inboundStream of this.streamsInbound.values()) {\n closePromises.push(inboundStream.close());\n }\n this.streamsInbound.clear();\n await Promise.all(closePromises);\n this.peers.clear();\n this.subscriptions.clear();\n // Gossipsub\n if (this.heartbeatTimer != null) {\n this.heartbeatTimer.cancel();\n this.heartbeatTimer = null;\n }\n this.score.stop();\n this.mesh.clear();\n this.fanout.clear();\n this.fanoutLastpub.clear();\n this.gossip.clear();\n this.control.clear();\n this.peerhave.clear();\n this.iasked.clear();\n this.backoff.clear();\n this.outbound.clear();\n this.gossipTracer.clear();\n this.seenCache.clear();\n if (this.fastMsgIdCache != null)\n this.fastMsgIdCache.clear();\n if (this.directPeerInitial != null)\n clearTimeout(this.directPeerInitial);\n this.log('stopped');\n }\n /** FOR DEBUG ONLY - Dump peer stats for all peers. Data is cloned, safe to mutate */\n dumpPeerScoreStats() {\n return this.score.dumpPeerScoreStats();\n }\n /**\n * On an inbound stream opened\n */\n onIncomingStream({ stream, connection }) {\n if (!this.isStarted()) {\n return;\n }\n const peerId = connection.remotePeer;\n // add peer to router\n this.addPeer(peerId, connection.direction, connection.remoteAddr);\n // create inbound stream\n this.createInboundStream(peerId, stream);\n // attempt to create outbound stream\n this.outboundInflightQueue.push({ peerId, connection });\n }\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n onPeerConnected(peerId, connection) {\n this.metrics?.newConnectionCount.inc({ status: connection.status });\n // libp2p may emit a closed connection and never issue peer:disconnect event\n // see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/398\n if (!this.isStarted() || connection.status !== 'open') {\n return;\n }\n this.addPeer(peerId, connection.direction, connection.remoteAddr);\n this.outboundInflightQueue.push({ peerId, connection });\n }\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n onPeerDisconnected(peerId) {\n this.log('connection ended %p', peerId);\n this.removePeer(peerId);\n }\n async createOutboundStream(peerId, connection) {\n if (!this.isStarted()) {\n return;\n }\n const id = peerId.toString();\n if (!this.peers.has(id)) {\n return;\n }\n // TODO make this behavior more robust\n // This behavior is different than for inbound streams\n // If an outbound stream already exists, don't create a new stream\n if (this.streamsOutbound.has(id)) {\n return;\n }\n try {\n const stream = new OutboundStream(await connection.newStream(this.multicodecs, {\n runOnTransientConnection: this.runOnTransientConnection\n }), (e) => { this.log.error('outbound pipe error', e); }, { maxBufferSize: this.opts.maxOutboundBufferSize });\n this.log('create outbound stream %p', peerId);\n this.streamsOutbound.set(id, stream);\n const protocol = stream.protocol;\n if (protocol === constants.FloodsubID) {\n this.floodsubPeers.add(id);\n }\n this.metrics?.peersPerProtocol.inc({ protocol }, 1);\n // Immediately send own subscriptions via the newly attached stream\n if (this.subscriptions.size > 0) {\n this.log('send subscriptions to', id);\n this.sendSubscriptions(id, Array.from(this.subscriptions), true);\n }\n }\n catch (e) {\n this.log.error('createOutboundStream error', e);\n }\n }\n createInboundStream(peerId, stream) {\n if (!this.isStarted()) {\n return;\n }\n const id = peerId.toString();\n if (!this.peers.has(id)) {\n return;\n }\n // TODO make this behavior more robust\n // This behavior is different than for outbound streams\n // If a peer initiates a new inbound connection\n // we assume that one is the new canonical inbound stream\n const priorInboundStream = this.streamsInbound.get(id);\n if (priorInboundStream !== undefined) {\n this.log('replacing existing inbound steam %s', id);\n priorInboundStream.close().catch((err) => { this.log.error(err); });\n }\n this.log('create inbound stream %s', id);\n const inboundStream = new InboundStream(stream, { maxDataLength: this.opts.maxInboundDataLength });\n this.streamsInbound.set(id, inboundStream);\n this.pipePeerReadStream(peerId, inboundStream.source).catch((err) => { this.log(err); });\n }\n /**\n * Add a peer to the router\n */\n addPeer(peerId, direction, addr) {\n const id = peerId.toString();\n if (!this.peers.has(id)) {\n this.log('new peer %p', peerId);\n this.peers.add(id);\n // Add to peer scoring\n this.score.addPeer(id);\n const currentIP = multiaddrToIPStr(addr);\n if (currentIP !== null) {\n this.score.addIP(id, currentIP);\n }\n else {\n this.log('Added peer has no IP in current address %s %s', id, addr.toString());\n }\n // track the connection direction. Don't allow to unset outbound\n if (!this.outbound.has(id)) {\n this.outbound.set(id, direction === 'outbound');\n }\n }\n }\n /**\n * Removes a peer from the router\n */\n removePeer(peerId) {\n const id = peerId.toString();\n if (!this.peers.has(id)) {\n return;\n }\n // delete peer\n this.log('delete peer %p', peerId);\n this.peers.delete(id);\n const outboundStream = this.streamsOutbound.get(id);\n const inboundStream = this.streamsInbound.get(id);\n if (outboundStream != null) {\n this.metrics?.peersPerProtocol.inc({ protocol: outboundStream.protocol }, -1);\n }\n // close streams\n outboundStream?.close().catch((err) => { this.log.error(err); });\n inboundStream?.close().catch((err) => { this.log.error(err); });\n // remove streams\n this.streamsOutbound.delete(id);\n this.streamsInbound.delete(id);\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(id);\n }\n // Remove this peer from the mesh\n for (const [topicStr, peers] of this.mesh) {\n if (peers.delete(id)) {\n this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1);\n }\n }\n // Remove this peer from the fanout\n for (const peers of this.fanout.values()) {\n peers.delete(id);\n }\n // Remove from floodsubPeers\n this.floodsubPeers.delete(id);\n // Remove from gossip mapping\n this.gossip.delete(id);\n // Remove from control mapping\n this.control.delete(id);\n // Remove from backoff mapping\n this.outbound.delete(id);\n // Remove from peer scoring\n this.score.removePeer(id);\n this.acceptFromWhitelist.delete(id);\n }\n // API METHODS\n get started() {\n return this.status.code === GossipStatusCode.started;\n }\n /**\n * Get a the peer-ids in a topic mesh\n */\n getMeshPeers(topic) {\n const peersInTopic = this.mesh.get(topic);\n return (peersInTopic != null) ? Array.from(peersInTopic) : [];\n }\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers(topic) {\n const peersInTopic = this.topics.get(topic);\n return ((peersInTopic != null) ? Array.from(peersInTopic) : []).map((str) => peerIdFromString(str));\n }\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics() {\n return Array.from(this.subscriptions);\n }\n // TODO: Reviewing Pubsub API\n // MESSAGE METHODS\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n async pipePeerReadStream(peerId, stream) {\n try {\n await pipe(stream, async (source) => {\n for await (const data of source) {\n try {\n // TODO: Check max gossip message size, before decodeRpc()\n const rpcBytes = data.subarray();\n // Note: This function may throw, it must be wrapped in a try {} catch {} to prevent closing the stream.\n // TODO: What should we do if the entire RPC is invalid?\n const rpc = RPC.decode(rpcBytes, {\n limits: {\n subscriptions: this.decodeRpcLimits.maxSubscriptions,\n messages: this.decodeRpcLimits.maxMessages,\n control$: {\n ihave: this.decodeRpcLimits.maxIhaveMessageIDs,\n iwant: this.decodeRpcLimits.maxIwantMessageIDs,\n graft: this.decodeRpcLimits.maxControlMessages,\n prune: this.decodeRpcLimits.maxControlMessages,\n prune$: {\n peers: this.decodeRpcLimits.maxPeerInfos\n }\n }\n }\n });\n this.metrics?.onRpcRecv(rpc, rpcBytes.length);\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n if (this.opts.awaitRpcHandler) {\n try {\n await this.handleReceivedRpc(peerId, rpc);\n }\n catch (err) {\n this.metrics?.onRpcRecvError();\n this.log(err);\n }\n }\n else {\n this.handleReceivedRpc(peerId, rpc).catch((err) => {\n this.metrics?.onRpcRecvError();\n this.log(err);\n });\n }\n }\n catch (e) {\n this.metrics?.onRpcDataError();\n this.log(e);\n }\n }\n });\n }\n catch (err) {\n this.metrics?.onPeerReadStreamError();\n this.handlePeerReadStreamError(err, peerId);\n }\n }\n /**\n * Handle error when read stream pipe throws, less of the functional use but more\n * to for testing purposes to spy on the error handling\n * */\n handlePeerReadStreamError(err, peerId) {\n this.log.error(err);\n this.onPeerDisconnected(peerId);\n }\n /**\n * Handles an rpc request from a peer\n */\n async handleReceivedRpc(from, rpc) {\n // Check if peer is graylisted in which case we ignore the event\n if (!this.acceptFrom(from.toString())) {\n this.log('received message from unacceptable peer %p', from);\n this.metrics?.rpcRecvNotAccepted.inc();\n return;\n }\n const subscriptions = (rpc.subscriptions != null) ? rpc.subscriptions.length : 0;\n const messages = (rpc.messages != null) ? rpc.messages.length : 0;\n let ihave = 0;\n let iwant = 0;\n let graft = 0;\n let prune = 0;\n if (rpc.control != null) {\n if (rpc.control.ihave != null)\n ihave = rpc.control.ihave.length;\n if (rpc.control.iwant != null)\n iwant = rpc.control.iwant.length;\n if (rpc.control.graft != null)\n graft = rpc.control.graft.length;\n if (rpc.control.prune != null)\n prune = rpc.control.prune.length;\n }\n this.log(`rpc.from ${from.toString()} subscriptions ${subscriptions} messages ${messages} ihave ${ihave} iwant ${iwant} graft ${graft} prune ${prune}`);\n // Handle received subscriptions\n if ((rpc.subscriptions != null) && rpc.subscriptions.length > 0) {\n // update peer subscriptions\n const subscriptions = [];\n rpc.subscriptions.forEach((subOpt) => {\n const topic = subOpt.topic;\n const subscribe = subOpt.subscribe === true;\n if (topic != null) {\n if ((this.allowedTopics != null) && !this.allowedTopics.has(topic)) {\n // Not allowed: subscription data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n return;\n }\n this.handleReceivedSubscription(from, topic, subscribe);\n subscriptions.push({ topic, subscribe });\n }\n });\n this.safeDispatchEvent('subscription-change', {\n detail: { peerId: from, subscriptions }\n });\n }\n // Handle messages\n // TODO: (up to limit)\n for (const message of rpc.messages) {\n if ((this.allowedTopics != null) && !this.allowedTopics.has(message.topic)) {\n // Not allowed: message cache data-structures are not bounded by topic count\n // TODO: Should apply behaviour penalties?\n continue;\n }\n const handleReceivedMessagePromise = this.handleReceivedMessage(from, message)\n // Should never throw, but handle just in case\n .catch((err) => {\n this.metrics?.onMsgRecvError(message.topic);\n this.log(err);\n });\n if (this.opts.awaitRpcMessageHandler) {\n await handleReceivedMessagePromise;\n }\n }\n // Handle control messages\n if (rpc.control != null) {\n await this.handleControlMessage(from.toString(), rpc.control);\n }\n }\n /**\n * Handles a subscription change from a peer\n */\n handleReceivedSubscription(from, topic, subscribe) {\n this.log('subscription update from %p topic %s', from, topic);\n let topicSet = this.topics.get(topic);\n if (topicSet == null) {\n topicSet = new Set();\n this.topics.set(topic, topicSet);\n }\n if (subscribe) {\n // subscribe peer to new topic\n topicSet.add(from.toString());\n }\n else {\n // unsubscribe from existing topic\n topicSet.delete(from.toString());\n }\n // TODO: rust-libp2p has A LOT more logic here\n }\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n async handleReceivedMessage(from, rpcMsg) {\n this.metrics?.onMsgRecvPreValidation(rpcMsg.topic);\n const validationResult = await this.validateReceivedMessage(from, rpcMsg);\n this.metrics?.onPrevalidationResult(rpcMsg.topic, validationResult.code);\n const validationCode = validationResult.code;\n switch (validationCode) {\n case MessageStatus.duplicate:\n // Report the duplicate\n this.score.duplicateMessage(from.toString(), validationResult.msgIdStr, rpcMsg.topic);\n // due to the collision of fastMsgIdFn, 2 different messages may end up the same fastMsgId\n // so we need to also mark the duplicate message as delivered or the promise is not resolved\n // and peer gets penalized. See https://github.com/ChainSafe/js-libp2p-gossipsub/pull/385\n this.gossipTracer.deliverMessage(validationResult.msgIdStr, true);\n this.mcache.observeDuplicate(validationResult.msgIdStr, from.toString());\n return;\n case MessageStatus.invalid:\n // invalid messages received\n // metrics.register_invalid_message(&raw_message.topic)\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n if (validationResult.msgIdStr != null) {\n const msgIdStr = validationResult.msgIdStr;\n this.score.rejectMessage(from.toString(), msgIdStr, rpcMsg.topic, validationResult.reason);\n this.gossipTracer.rejectMessage(msgIdStr, validationResult.reason);\n }\n else {\n this.score.rejectInvalidMessage(from.toString(), rpcMsg.topic);\n }\n this.metrics?.onMsgRecvInvalid(rpcMsg.topic, validationResult);\n return;\n case MessageStatus.valid:\n // Tells score that message arrived (but is maybe not fully validated yet).\n // Consider the message as delivered for gossip promises.\n this.score.validateMessage(validationResult.messageId.msgIdStr);\n this.gossipTracer.deliverMessage(validationResult.messageId.msgIdStr);\n // Add the message to our memcache\n // if no validation is required, mark the message as validated\n this.mcache.put(validationResult.messageId, rpcMsg, !this.opts.asyncValidation);\n // Dispatch the message to the user if we are subscribed to the topic\n if (this.subscriptions.has(rpcMsg.topic)) {\n const isFromSelf = this.components.peerId.equals(from);\n if (!isFromSelf || this.opts.emitSelf) {\n super.dispatchEvent(new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: from,\n msgId: validationResult.messageId.msgIdStr,\n msg: validationResult.msg\n }\n }));\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: validationResult.msg }));\n }\n }\n // Forward the message to mesh peers, if no validation is required\n // If asyncValidation is ON, expect the app layer to call reportMessageValidationResult(), then forward\n if (!this.opts.asyncValidation) {\n // TODO: in rust-libp2p\n // .forward_msg(&msg_id, raw_message, Some(propagation_source))\n this.forwardMessage(validationResult.messageId.msgIdStr, rpcMsg, from.toString());\n }\n break;\n default:\n throw new Error(`Invalid validation result: ${validationCode}`);\n }\n }\n /**\n * Handles a newly received message from an RPC.\n * May forward to all peers in the mesh.\n */\n async validateReceivedMessage(propagationSource, rpcMsg) {\n // Fast message ID stuff\n const fastMsgIdStr = this.fastMsgIdFn?.(rpcMsg);\n const msgIdCached = fastMsgIdStr !== undefined ? this.fastMsgIdCache?.get(fastMsgIdStr) : undefined;\n if (msgIdCached != null) {\n // This message has been seen previously. Ignore it\n return { code: MessageStatus.duplicate, msgIdStr: msgIdCached };\n }\n // Perform basic validation on message and convert to RawGossipsubMessage for fastMsgIdFn()\n const validationResult = await validateToRawMessage(this.globalSignaturePolicy, rpcMsg);\n if (!validationResult.valid) {\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: validationResult.error };\n }\n const msg = validationResult.message;\n // Try and perform the data transform to the message. If it fails, consider it invalid.\n try {\n if (this.dataTransform != null) {\n msg.data = this.dataTransform.inboundTransform(rpcMsg.topic, msg.data);\n }\n }\n catch (e) {\n this.log('Invalid message, transform failed', e);\n return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed };\n }\n // TODO: Check if message is from a blacklisted source or propagation origin\n // - Reject any message from a blacklisted peer\n // - Also reject any message that originated from a blacklisted peer\n // - reject messages claiming to be from ourselves but not locally published\n // Calculate the message id on the transformed data.\n const msgId = await this.msgIdFn(msg);\n const msgIdStr = this.msgIdToStrFn(msgId);\n const messageId = { msgId, msgIdStr };\n // Add the message to the duplicate caches\n if (fastMsgIdStr !== undefined && (this.fastMsgIdCache != null)) {\n const collision = this.fastMsgIdCache.put(fastMsgIdStr, msgIdStr);\n if (collision) {\n this.metrics?.fastMsgIdCacheCollision.inc();\n }\n }\n if (this.seenCache.has(msgIdStr)) {\n return { code: MessageStatus.duplicate, msgIdStr };\n }\n else {\n this.seenCache.put(msgIdStr);\n }\n // (Optional) Provide custom validation here with dynamic validators per topic\n // NOTE: This custom topicValidator() must resolve fast (< 100ms) to allow scores\n // to not penalize peers for long validation times.\n const topicValidator = this.topicValidators.get(rpcMsg.topic);\n if (topicValidator != null) {\n let acceptance;\n // Use try {} catch {} in case topicValidator() is synchronous\n try {\n acceptance = await topicValidator(propagationSource, msg);\n }\n catch (e) {\n const errCode = e.code;\n if (errCode === constants.ERR_TOPIC_VALIDATOR_IGNORE)\n acceptance = TopicValidatorResult.Ignore;\n if (errCode === constants.ERR_TOPIC_VALIDATOR_REJECT)\n acceptance = TopicValidatorResult.Reject;\n else\n acceptance = TopicValidatorResult.Ignore;\n }\n if (acceptance !== TopicValidatorResult.Accept) {\n return { code: MessageStatus.invalid, reason: rejectReasonFromAcceptance(acceptance), msgIdStr };\n }\n }\n return { code: MessageStatus.valid, messageId, msg };\n }\n /**\n * Return score of a peer.\n */\n getScore(peerId) {\n return this.score.score(peerId);\n }\n /**\n * Send an rpc object to a peer with subscriptions\n */\n sendSubscriptions(toPeer, topics, subscribe) {\n this.sendRpc(toPeer, {\n subscriptions: topics.map((topic) => ({ topic, subscribe })),\n messages: []\n });\n }\n /**\n * Handles an rpc control message from a peer\n */\n async handleControlMessage(id, controlMsg) {\n if (controlMsg === undefined) {\n return;\n }\n const iwant = (controlMsg.ihave != null) ? this.handleIHave(id, controlMsg.ihave) : [];\n const ihave = (controlMsg.iwant != null) ? this.handleIWant(id, controlMsg.iwant) : [];\n const prune = (controlMsg.graft != null) ? await this.handleGraft(id, controlMsg.graft) : [];\n (controlMsg.prune != null) && (await this.handlePrune(id, controlMsg.prune));\n if ((iwant.length === 0) && (ihave.length === 0) && (prune.length === 0)) {\n return;\n }\n const sent = this.sendRpc(id, createGossipRpc(ihave, { iwant, prune }));\n const iwantMessageIds = iwant[0]?.messageIDs;\n if (iwantMessageIds != null) {\n if (sent) {\n this.gossipTracer.addPromise(id, iwantMessageIds);\n }\n else {\n this.metrics?.iwantPromiseUntracked.inc(1);\n }\n }\n }\n /**\n * Whether to accept a message from a peer\n */\n acceptFrom(id) {\n if (this.direct.has(id)) {\n return true;\n }\n const now = Date.now();\n const entry = this.acceptFromWhitelist.get(id);\n if ((entry != null) && entry.messagesAccepted < ACCEPT_FROM_WHITELIST_MAX_MESSAGES && entry.acceptUntil >= now) {\n entry.messagesAccepted += 1;\n return true;\n }\n const score = this.score.score(id);\n if (score >= ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE) {\n // peer is unlikely to be able to drop its score to `graylistThreshold`\n // after 128 messages or 1s\n this.acceptFromWhitelist.set(id, {\n messagesAccepted: 0,\n acceptUntil: now + ACCEPT_FROM_WHITELIST_DURATION_MS\n });\n }\n else {\n this.acceptFromWhitelist.delete(id);\n }\n return score >= this.opts.scoreThresholds.graylistThreshold;\n }\n /**\n * Handles IHAVE messages\n */\n handleIHave(id, ihave) {\n if (ihave.length === 0) {\n return [];\n }\n // we ignore IHAVE gossip from any peer whose score is below the gossips threshold\n const score = this.score.score(id);\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IHAVE: ignoring peer %s with score below threshold [ score = %d ]', id, score);\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.LowScore });\n return [];\n }\n // IHAVE flood protection\n const peerhave = (this.peerhave.get(id) ?? 0) + 1;\n this.peerhave.set(id, peerhave);\n if (peerhave > constants.GossipsubMaxIHaveMessages) {\n this.log('IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring', id, peerhave);\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIhave });\n return [];\n }\n const iasked = this.iasked.get(id) ?? 0;\n if (iasked >= constants.GossipsubMaxIHaveLength) {\n this.log('IHAVE: peer %s has already advertised too many messages (%d); ignoring', id, iasked);\n this.metrics?.ihaveRcvIgnored.inc({ reason: IHaveIgnoreReason.MaxIasked });\n return [];\n }\n // string msgId => msgId\n const iwant = new Map();\n ihave.forEach(({ topicID, messageIDs }) => {\n if (topicID == null || (messageIDs == null) || !this.mesh.has(topicID)) {\n return;\n }\n let idonthave = 0;\n messageIDs.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId);\n if (!this.seenCache.has(msgIdStr)) {\n iwant.set(msgIdStr, msgId);\n idonthave++;\n }\n });\n this.metrics?.onIhaveRcv(topicID, messageIDs.length, idonthave);\n });\n if (iwant.size === 0) {\n return [];\n }\n let iask = iwant.size;\n if (iask + iasked > constants.GossipsubMaxIHaveLength) {\n iask = constants.GossipsubMaxIHaveLength - iasked;\n }\n this.log('IHAVE: Asking for %d out of %d messages from %s', iask, iwant.size, id);\n let iwantList = Array.from(iwant.values());\n // ask in random order\n shuffle(iwantList);\n // truncate to the messages we are actually asking for and update the iasked counter\n iwantList = iwantList.slice(0, iask);\n this.iasked.set(id, iasked + iask);\n // do not add gossipTracer promise here until a successful sendRpc()\n return [\n {\n messageIDs: iwantList\n }\n ];\n }\n /**\n * Handles IWANT messages\n * Returns messages to send back to peer\n */\n handleIWant(id, iwant) {\n if (iwant.length === 0) {\n return [];\n }\n // we don't respond to IWANT requests from any per whose score is below the gossip threshold\n const score = this.score.score(id);\n if (score < this.opts.scoreThresholds.gossipThreshold) {\n this.log('IWANT: ignoring peer %s with score below threshold [score = %d]', id, score);\n return [];\n }\n const ihave = new Map();\n const iwantByTopic = new Map();\n let iwantDonthave = 0;\n iwant.forEach(({ messageIDs }) => {\n messageIDs?.forEach((msgId) => {\n const msgIdStr = this.msgIdToStrFn(msgId);\n const entry = this.mcache.getWithIWantCount(msgIdStr, id);\n if (entry == null) {\n iwantDonthave++;\n return;\n }\n iwantByTopic.set(entry.msg.topic, 1 + (iwantByTopic.get(entry.msg.topic) ?? 0));\n if (entry.count > constants.GossipsubGossipRetransmission) {\n this.log('IWANT: Peer %s has asked for message %s too many times: ignoring request', id, msgId);\n return;\n }\n ihave.set(msgIdStr, entry.msg);\n });\n });\n this.metrics?.onIwantRcv(iwantByTopic, iwantDonthave);\n if (ihave.size === 0) {\n this.log('IWANT: Could not provide any wanted messages to %s', id);\n return [];\n }\n this.log('IWANT: Sending %d messages to %s', ihave.size, id);\n return Array.from(ihave.values());\n }\n /**\n * Handles Graft messages\n */\n async handleGraft(id, graft) {\n const prune = [];\n const score = this.score.score(id);\n const now = Date.now();\n let doPX = this.opts.doPX;\n graft.forEach(({ topicID }) => {\n if (topicID == null) {\n return;\n }\n const peersInMesh = this.mesh.get(topicID);\n if (peersInMesh == null) {\n // don't do PX when there is an unknown topic to avoid leaking our peers\n doPX = false;\n // spam hardening: ignore GRAFTs for unknown topics\n return;\n }\n // check if peer is already in the mesh; if so do nothing\n if (peersInMesh.has(id)) {\n return;\n }\n // we don't GRAFT to/from direct peers; complain loudly if this happens\n if (this.direct.has(id)) {\n this.log('GRAFT: ignoring request from direct peer %s', id);\n // this is possibly a bug from a non-reciprical configuration; send a PRUNE\n prune.push(topicID);\n // but don't px\n doPX = false;\n return;\n }\n // make sure we are not backing off that peer\n const expire = this.backoff.get(topicID)?.get(id);\n if (typeof expire === 'number' && now < expire) {\n this.log('GRAFT: ignoring backed off peer %s', id);\n // add behavioral penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff);\n // no PX\n doPX = false;\n // check the flood cutoff -- is the GRAFT coming too fast?\n const floodCutoff = expire + this.opts.graftFloodThreshold - this.opts.pruneBackoff;\n if (now < floodCutoff) {\n // extra penalty\n this.score.addPenalty(id, 1, ScorePenalty.GraftBackoff);\n }\n // refresh the backoff\n this.addBackoff(id, topicID);\n prune.push(topicID);\n return;\n }\n // check the score\n if (score < 0) {\n // we don't GRAFT peers with negative score\n this.log('GRAFT: ignoring peer %s with negative score: score=%d, topic=%s', id, score, topicID);\n // we do send them PRUNE however, because it's a matter of protocol correctness\n prune.push(topicID);\n // but we won't PX to them\n doPX = false;\n // add/refresh backoff so that we don't reGRAFT too early even if the score decays\n this.addBackoff(id, topicID);\n return;\n }\n // check the number of mesh peers; if it is at (or over) Dhi, we only accept grafts\n // from peers with outbound connections; this is a defensive check to restrict potential\n // mesh takeover attacks combined with love bombing\n if (peersInMesh.size >= this.opts.Dhi && !(this.outbound.get(id) ?? false)) {\n prune.push(topicID);\n this.addBackoff(id, topicID);\n return;\n }\n this.log('GRAFT: Add mesh link from %s in %s', id, topicID);\n this.score.graft(id, topicID);\n peersInMesh.add(id);\n this.metrics?.onAddToMesh(topicID, InclusionReason.Subscribed, 1);\n });\n if (prune.length === 0) {\n return [];\n }\n const onUnsubscribe = false;\n return Promise.all(prune.map(async (topic) => this.makePrune(id, topic, doPX, onUnsubscribe)));\n }\n /**\n * Handles Prune messages\n */\n async handlePrune(id, prune) {\n const score = this.score.score(id);\n for (const { topicID, backoff, peers } of prune) {\n if (topicID == null) {\n continue;\n }\n const peersInMesh = this.mesh.get(topicID);\n if (peersInMesh == null) {\n return;\n }\n this.log('PRUNE: Remove mesh link to %s in %s', id, topicID);\n this.score.prune(id, topicID);\n if (peersInMesh.has(id)) {\n peersInMesh.delete(id);\n this.metrics?.onRemoveFromMesh(topicID, ChurnReason.Prune, 1);\n }\n // is there a backoff specified by the peer? if so obey it\n if (typeof backoff === 'number' && backoff > 0) {\n this.doAddBackoff(id, topicID, backoff * 1000);\n }\n else {\n this.addBackoff(id, topicID);\n }\n // PX\n if ((peers != null) && (peers.length > 0)) {\n // we ignore PX from peers with insufficient scores\n if (score < this.opts.scoreThresholds.acceptPXThreshold) {\n this.log('PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]', id, score, topicID);\n continue;\n }\n await this.pxConnect(peers);\n }\n }\n }\n /**\n * Add standard backoff log for a peer in a topic\n */\n addBackoff(id, topic) {\n this.doAddBackoff(id, topic, this.opts.pruneBackoff);\n }\n /**\n * Add backoff expiry interval for a peer in a topic\n *\n * @param id\n * @param topic\n * @param intervalMs - backoff duration in milliseconds\n */\n doAddBackoff(id, topic, intervalMs) {\n let backoff = this.backoff.get(topic);\n if (backoff == null) {\n backoff = new Map();\n this.backoff.set(topic, backoff);\n }\n const expire = Date.now() + intervalMs;\n const existingExpire = backoff.get(id) ?? 0;\n if (existingExpire < expire) {\n backoff.set(id, expire);\n }\n }\n /**\n * Apply penalties from broken IHAVE/IWANT promises\n */\n applyIwantPenalties() {\n this.gossipTracer.getBrokenPromises().forEach((count, p) => {\n this.log(\"peer %s didn't follow up in %d IWANT requests; adding penalty\", p, count);\n this.score.addPenalty(p, count, ScorePenalty.BrokenPromise);\n });\n }\n /**\n * Clear expired backoff expiries\n */\n clearBackoff() {\n // we only clear once every GossipsubPruneBackoffTicks ticks to avoid iterating over the maps too much\n if (this.heartbeatTicks % constants.GossipsubPruneBackoffTicks !== 0) {\n return;\n }\n const now = Date.now();\n this.backoff.forEach((backoff, topic) => {\n backoff.forEach((expire, id) => {\n // add some slack time to the expiration, see https://github.com/libp2p/specs/pull/289\n if (expire + BACKOFF_SLACK * this.opts.heartbeatInterval < now) {\n backoff.delete(id);\n }\n });\n if (backoff.size === 0) {\n this.backoff.delete(topic);\n }\n });\n }\n /**\n * Maybe reconnect to direct peers\n */\n async directConnect() {\n const toconnect = [];\n this.direct.forEach((id) => {\n if (!this.streamsOutbound.has(id)) {\n toconnect.push(id);\n }\n });\n await Promise.all(toconnect.map(async (id) => this.connect(id)));\n }\n /**\n * Maybe attempt connection given signed peer records\n */\n async pxConnect(peers) {\n if (peers.length > this.opts.prunePeers) {\n shuffle(peers);\n peers = peers.slice(0, this.opts.prunePeers);\n }\n const toconnect = [];\n await Promise.all(peers.map(async (pi) => {\n if (pi.peerID == null) {\n return;\n }\n const peer = peerIdFromBytes(pi.peerID);\n const p = peer.toString();\n if (this.peers.has(p)) {\n return;\n }\n if (pi.signedPeerRecord == null) {\n toconnect.push(p);\n return;\n }\n // The peer sent us a signed record\n // This is not a record from the peer who sent the record, but another peer who is connected with it\n // Ensure that it is valid\n try {\n if (!(await this.components.peerStore.consumePeerRecord(pi.signedPeerRecord, peer))) {\n this.log('bogus peer record obtained through px: could not add peer record to address book');\n return;\n }\n toconnect.push(p);\n }\n catch (e) {\n this.log('bogus peer record obtained through px: invalid signature or not a peer record');\n }\n }));\n if (toconnect.length === 0) {\n return;\n }\n await Promise.all(toconnect.map(async (id) => this.connect(id)));\n }\n /**\n * Connect to a peer using the gossipsub protocol\n */\n async connect(id) {\n this.log('Initiating connection with %s', id);\n const peerId = peerIdFromString(id);\n const connection = await this.components.connectionManager.openConnection(peerId);\n for (const multicodec of this.multicodecs) {\n for (const topology of this.components.registrar.getTopologies(multicodec)) {\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n /**\n * Subscribes to a topic\n */\n subscribe(topic) {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub has not started');\n }\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic);\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], true);\n }\n }\n this.join(topic);\n }\n /**\n * Unsubscribe to a topic\n */\n unsubscribe(topic) {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Pubsub is not started');\n }\n const wasSubscribed = this.subscriptions.delete(topic);\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed);\n if (wasSubscribed) {\n for (const peerId of this.peers.keys()) {\n this.sendSubscriptions(peerId, [topic], false);\n }\n }\n this.leave(topic);\n }\n /**\n * Join topic\n */\n join(topic) {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started');\n }\n // if we are already in the mesh, return\n if (this.mesh.has(topic)) {\n return;\n }\n this.log('JOIN %s', topic);\n this.metrics?.onJoin(topic);\n const toAdd = new Set();\n const backoff = this.backoff.get(topic);\n // check if we have mesh_n peers in fanout[topic] and add them to the mesh if we do,\n // removing the fanout entry.\n const fanoutPeers = this.fanout.get(topic);\n if (fanoutPeers != null) {\n // Remove fanout entry and the last published time\n this.fanout.delete(topic);\n this.fanoutLastpub.delete(topic);\n // remove explicit peers, peers with negative scores, and backoffed peers\n fanoutPeers.forEach((id) => {\n if (!this.direct.has(id) && this.score.score(id) >= 0 && ((backoff == null) || !backoff.has(id))) {\n toAdd.add(id);\n }\n });\n this.metrics?.onAddToMesh(topic, InclusionReason.Fanout, toAdd.size);\n }\n // check if we need to get more peers, which we randomly select\n if (toAdd.size < this.opts.D) {\n const fanoutCount = toAdd.size;\n const newPeers = this.getRandomGossipPeers(topic, this.opts.D, (id) => \n // filter direct peers and peers with negative score\n !toAdd.has(id) && !this.direct.has(id) && this.score.score(id) >= 0 && ((backoff == null) || !backoff.has(id)));\n newPeers.forEach((peer) => {\n toAdd.add(peer);\n });\n this.metrics?.onAddToMesh(topic, InclusionReason.Random, toAdd.size - fanoutCount);\n }\n this.mesh.set(topic, toAdd);\n toAdd.forEach((id) => {\n this.log('JOIN: Add mesh link to %s in %s', id, topic);\n this.sendGraft(id, topic);\n // rust-libp2p\n // - peer_score.graft()\n // - Self::control_pool_add()\n // - peer_added_to_mesh()\n });\n }\n /**\n * Leave topic\n */\n leave(topic) {\n if (this.status.code !== GossipStatusCode.started) {\n throw new Error('Gossipsub has not started');\n }\n this.log('LEAVE %s', topic);\n this.metrics?.onLeave(topic);\n // Send PRUNE to mesh peers\n const meshPeers = this.mesh.get(topic);\n if (meshPeers != null) {\n Promise.all(Array.from(meshPeers).map(async (id) => {\n this.log('LEAVE: Remove mesh link to %s in %s', id, topic);\n await this.sendPrune(id, topic);\n })).catch((err) => {\n this.log('Error sending prunes to mesh peers', err);\n });\n this.mesh.delete(topic);\n }\n }\n selectPeersToForward(topic, propagationSource, excludePeers) {\n const tosend = new Set();\n // Add explicit peers\n const peersInTopic = this.topics.get(topic);\n if (peersInTopic != null) {\n this.direct.forEach((peer) => {\n if (peersInTopic.has(peer) && propagationSource !== peer && !(excludePeers?.has(peer) ?? false)) {\n tosend.add(peer);\n }\n });\n // As of Mar 2022, spec + golang-libp2p include this while rust-libp2p does not\n // rust-libp2p: https://github.com/libp2p/rust-libp2p/blob/6cc3b4ec52c922bfcf562a29b5805c3150e37c75/protocols/gossipsub/src/behaviour.rs#L2693\n // spec: https://github.com/libp2p/specs/blob/10712c55ab309086a52eec7d25f294df4fa96528/pubsub/gossipsub/gossipsub-v1.0.md?plain=1#L361\n this.floodsubPeers.forEach((peer) => {\n if (peersInTopic.has(peer) &&\n propagationSource !== peer &&\n !(excludePeers?.has(peer) ?? false) &&\n this.score.score(peer) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(peer);\n }\n });\n }\n // add mesh peers\n const meshPeers = this.mesh.get(topic);\n if ((meshPeers != null) && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n if (propagationSource !== peer && !(excludePeers?.has(peer) ?? false)) {\n tosend.add(peer);\n }\n });\n }\n return tosend;\n }\n selectPeersToPublish(topic) {\n const tosend = new Set();\n const tosendCount = {\n direct: 0,\n floodsub: 0,\n mesh: 0,\n fanout: 0\n };\n const peersInTopic = this.topics.get(topic);\n if (peersInTopic != null) {\n // flood-publish behavior\n // send to direct peers and _all_ peers meeting the publishThreshold\n if (this.opts.floodPublish) {\n peersInTopic.forEach((id) => {\n if (this.direct.has(id)) {\n tosend.add(id);\n tosendCount.direct++;\n }\n else if (this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id);\n tosendCount.floodsub++;\n }\n });\n }\n else {\n // non-flood-publish behavior\n // send to direct peers, subscribed floodsub peers\n // and some mesh peers above publishThreshold\n // direct peers (if subscribed)\n this.direct.forEach((id) => {\n if (peersInTopic.has(id)) {\n tosend.add(id);\n tosendCount.direct++;\n }\n });\n // floodsub peers\n // Note: if there are no floodsub peers, we save a loop through peersInTopic Map\n this.floodsubPeers.forEach((id) => {\n if (peersInTopic.has(id) && this.score.score(id) >= this.opts.scoreThresholds.publishThreshold) {\n tosend.add(id);\n tosendCount.floodsub++;\n }\n });\n // Gossipsub peers handling\n const meshPeers = this.mesh.get(topic);\n if ((meshPeers != null) && meshPeers.size > 0) {\n meshPeers.forEach((peer) => {\n tosend.add(peer);\n tosendCount.mesh++;\n });\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n // We are not in the mesh for topic, use fanout peers\n else {\n const fanoutPeers = this.fanout.get(topic);\n if ((fanoutPeers != null) && fanoutPeers.size > 0) {\n fanoutPeers.forEach((peer) => {\n tosend.add(peer);\n tosendCount.fanout++;\n });\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n // We have no fanout peers, select mesh_n of them and add them to the fanout\n else {\n // If we are not in the fanout, then pick peers in topic above the publishThreshold\n const newFanoutPeers = this.getRandomGossipPeers(topic, this.opts.D, (id) => {\n return this.score.score(id) >= this.opts.scoreThresholds.publishThreshold;\n });\n // eslint-disable-next-line max-depth\n if (newFanoutPeers.size > 0) {\n this.fanout.set(topic, newFanoutPeers);\n newFanoutPeers.forEach((peer) => {\n tosend.add(peer);\n tosendCount.fanout++;\n });\n }\n }\n // We are publishing to fanout peers - update the time we published\n this.fanoutLastpub.set(topic, Date.now());\n }\n }\n }\n return { tosend, tosendCount };\n }\n /**\n * Forwards a message from our peers.\n *\n * For messages published by us (the app layer), this class uses `publish`\n */\n forwardMessage(msgIdStr, rawMsg, propagationSource, excludePeers) {\n // message is fully validated inform peer_score\n if (propagationSource != null) {\n this.score.deliverMessage(propagationSource, msgIdStr, rawMsg.topic);\n }\n const tosend = this.selectPeersToForward(rawMsg.topic, propagationSource, excludePeers);\n // Note: Don't throw if tosend is empty, we can have a mesh with a single peer\n // forward the message to peers\n tosend.forEach((id) => {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n this.sendRpc(id, createGossipRpc([rawMsg]));\n });\n this.metrics?.onForwardMsg(rawMsg.topic, tosend.size);\n }\n /**\n * App layer publishes a message to peers, return number of peers this message is published to\n * Note: `async` due to crypto only if `StrictSign`, otherwise it's a sync fn.\n *\n * For messages not from us, this class uses `forwardMessage`.\n */\n async publish(topic, data, opts) {\n const startMs = Date.now();\n const transformedData = (this.dataTransform != null) ? this.dataTransform.outboundTransform(topic, data) : data;\n if (this.publishConfig == null) {\n throw Error('PublishError.Uninitialized');\n }\n // Prepare raw message with user's publishConfig\n const { raw: rawMsg, msg } = await buildRawMessage(this.publishConfig, topic, data, transformedData);\n // calculate the message id from the un-transformed data\n const msgId = await this.msgIdFn(msg);\n const msgIdStr = this.msgIdToStrFn(msgId);\n // Current publish opt takes precedence global opts, while preserving false value\n const ignoreDuplicatePublishError = opts?.ignoreDuplicatePublishError ?? this.opts.ignoreDuplicatePublishError;\n if (this.seenCache.has(msgIdStr)) {\n // This message has already been seen. We don't re-publish messages that have already\n // been published on the network.\n if (ignoreDuplicatePublishError) {\n this.metrics?.onPublishDuplicateMsg(topic);\n return { recipients: [] };\n }\n throw Error('PublishError.Duplicate');\n }\n const { tosend, tosendCount } = this.selectPeersToPublish(topic);\n const willSendToSelf = this.opts.emitSelf && this.subscriptions.has(topic);\n // Current publish opt takes precedence global opts, while preserving false value\n const allowPublishToZeroPeers = opts?.allowPublishToZeroPeers ?? this.opts.allowPublishToZeroPeers;\n if (tosend.size === 0 && !allowPublishToZeroPeers && !willSendToSelf) {\n throw Error('PublishError.InsufficientPeers');\n }\n // If the message isn't a duplicate and we have sent it to some peers add it to the\n // duplicate cache and memcache.\n this.seenCache.put(msgIdStr);\n // all published messages are valid\n this.mcache.put({ msgId, msgIdStr }, rawMsg, true);\n // If the message is anonymous or has a random author add it to the published message ids cache.\n this.publishedMessageIds.put(msgIdStr);\n const batchPublish = opts?.batchPublish ?? this.opts.batchPublish;\n const rpc = createGossipRpc([rawMsg]);\n if (batchPublish) {\n this.sendRpcInBatch(tosend, rpc);\n }\n else {\n // Send to set of peers aggregated from direct, mesh, fanout\n for (const id of tosend) {\n // sendRpc may mutate RPC message on piggyback, create a new message for each peer\n const sent = this.sendRpc(id, rpc);\n // did not actually send the message\n if (!sent) {\n tosend.delete(id);\n }\n }\n }\n const durationMs = Date.now() - startMs;\n this.metrics?.onPublishMsg(topic, tosendCount, tosend.size, rawMsg.data != null ? rawMsg.data.length : 0, durationMs);\n // Dispatch the message to the user if we are subscribed to the topic\n if (willSendToSelf) {\n tosend.add(this.components.peerId.toString());\n super.dispatchEvent(new CustomEvent('gossipsub:message', {\n detail: {\n propagationSource: this.components.peerId,\n msgId: msgIdStr,\n msg\n }\n }));\n // TODO: Add option to switch between emit per topic or all messages in one\n super.dispatchEvent(new CustomEvent('message', { detail: msg }));\n }\n return {\n recipients: Array.from(tosend.values()).map((str) => peerIdFromString(str))\n };\n }\n /**\n * Send the same data in batch to tosend list without considering cached control messages\n * This is not only faster but also avoid allocating memory for each peer\n * see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/344\n */\n sendRpcInBatch(tosend, rpc) {\n const rpcBytes = RPC.encode(rpc);\n const prefixedData = encode.single(rpcBytes);\n for (const id of tosend) {\n const outboundStream = this.streamsOutbound.get(id);\n if (outboundStream == null) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`);\n tosend.delete(id);\n continue;\n }\n try {\n outboundStream.pushPrefixed(prefixedData);\n }\n catch (e) {\n tosend.delete(id);\n this.log.error(`Cannot send rpc to ${id}`, e);\n }\n this.metrics?.onRpcSent(rpc, rpcBytes.length);\n }\n }\n /**\n * This function should be called when `asyncValidation` is `true` after\n * the message got validated by the caller. Messages are stored in the `mcache` and\n * validation is expected to be fast enough that the messages should still exist in the cache.\n * There are three possible validation outcomes and the outcome is given in acceptance.\n *\n * If acceptance = `MessageAcceptance.Accept` the message will get propagated to the\n * network. The `propagation_source` parameter indicates who the message was received by and\n * will not be forwarded back to that peer.\n *\n * If acceptance = `MessageAcceptance.Reject` the message will be deleted from the memcache\n * and the P₄ penalty will be applied to the `propagationSource`.\n *\n * If acceptance = `MessageAcceptance.Ignore` the message will be deleted from the memcache\n * but no P₄ penalty will be applied.\n *\n * This function will return true if the message was found in the cache and false if was not\n * in the cache anymore.\n *\n * This should only be called once per message.\n */\n reportMessageValidationResult(msgId, propagationSource, acceptance) {\n let cacheEntry;\n if (acceptance === TopicValidatorResult.Accept) {\n cacheEntry = this.mcache.validate(msgId);\n if (cacheEntry != null) {\n const { message: rawMsg, originatingPeers } = cacheEntry;\n // message is fully validated inform peer_score\n this.score.deliverMessage(propagationSource, msgId, rawMsg.topic);\n this.forwardMessage(msgId, cacheEntry.message, propagationSource, originatingPeers);\n }\n // else, Message not in cache. Ignoring forwarding\n // eslint-disable-next-line @typescript-eslint/brace-style\n }\n // Not valid\n else {\n cacheEntry = this.mcache.remove(msgId);\n if (cacheEntry != null) {\n const rejectReason = rejectReasonFromAcceptance(acceptance);\n const { message: rawMsg, originatingPeers } = cacheEntry;\n // Tell peer_score about reject\n // Reject the original source, and any duplicates we've seen from other peers.\n this.score.rejectMessage(propagationSource, msgId, rawMsg.topic, rejectReason);\n for (const peer of originatingPeers) {\n this.score.rejectMessage(peer, msgId, rawMsg.topic, rejectReason);\n }\n }\n // else, Message not in cache. Ignoring forwarding\n }\n const firstSeenTimestampMs = this.score.messageFirstSeenTimestampMs(msgId);\n this.metrics?.onReportValidation(cacheEntry, acceptance, firstSeenTimestampMs);\n }\n /**\n * Sends a GRAFT message to a peer\n */\n sendGraft(id, topic) {\n const graft = [\n {\n topicID: topic\n }\n ];\n const out = createGossipRpc([], { graft });\n this.sendRpc(id, out);\n }\n /**\n * Sends a PRUNE message to a peer\n */\n async sendPrune(id, topic) {\n // this is only called from leave() function\n const onUnsubscribe = true;\n const prune = [await this.makePrune(id, topic, this.opts.doPX, onUnsubscribe)];\n const out = createGossipRpc([], { prune });\n this.sendRpc(id, out);\n }\n /**\n * Send an rpc object to a peer\n */\n sendRpc(id, rpc) {\n const outboundStream = this.streamsOutbound.get(id);\n if (outboundStream == null) {\n this.log(`Cannot send RPC to ${id} as there is no open stream to it available`);\n return false;\n }\n // piggyback control message retries\n const ctrl = this.control.get(id);\n if (ctrl != null) {\n this.piggybackControl(id, rpc, ctrl);\n this.control.delete(id);\n }\n // piggyback gossip\n const ihave = this.gossip.get(id);\n if (ihave != null) {\n this.piggybackGossip(id, rpc, ihave);\n this.gossip.delete(id);\n }\n const rpcBytes = RPC.encode(rpc);\n try {\n outboundStream.push(rpcBytes);\n }\n catch (e) {\n this.log.error(`Cannot send rpc to ${id}`, e);\n // if the peer had control messages or gossip, re-attach\n if (ctrl != null) {\n this.control.set(id, ctrl);\n }\n if (ihave != null) {\n this.gossip.set(id, ihave);\n }\n return false;\n }\n this.metrics?.onRpcSent(rpc, rpcBytes.length);\n return true;\n }\n /** Mutates `outRpc` adding graft and prune control messages */\n piggybackControl(id, outRpc, ctrl) {\n const rpc = ensureControl(outRpc);\n for (const graft of ctrl.graft) {\n if (graft.topicID != null && (this.mesh.get(graft.topicID)?.has(id) ?? false)) {\n rpc.control.graft.push(graft);\n }\n }\n for (const prune of ctrl.prune) {\n if (prune.topicID != null && !(this.mesh.get(prune.topicID)?.has(id) ?? false)) {\n rpc.control.prune.push(prune);\n }\n }\n }\n /** Mutates `outRpc` adding ihave control messages */\n piggybackGossip(id, outRpc, ihave) {\n const rpc = ensureControl(outRpc);\n rpc.control.ihave = ihave;\n }\n /**\n * Send graft and prune messages\n *\n * @param tograft - peer id => topic[]\n * @param toprune - peer id => topic[]\n */\n async sendGraftPrune(tograft, toprune, noPX) {\n const doPX = this.opts.doPX;\n const onUnsubscribe = false;\n for (const [id, topics] of tograft) {\n const graft = topics.map((topicID) => ({ topicID }));\n let prune = [];\n // If a peer also has prunes, process them now\n const pruning = toprune.get(id);\n if (pruning != null) {\n prune = await Promise.all(pruning.map(async (topicID) => this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false), onUnsubscribe)));\n toprune.delete(id);\n }\n this.sendRpc(id, createGossipRpc([], { graft, prune }));\n }\n for (const [id, topics] of toprune) {\n const prune = await Promise.all(topics.map(async (topicID) => this.makePrune(id, topicID, doPX && !(noPX.get(id) ?? false), onUnsubscribe)));\n this.sendRpc(id, createGossipRpc([], { prune }));\n }\n }\n /**\n * Emits gossip - Send IHAVE messages to a random set of gossip peers\n */\n emitGossip(peersToGossipByTopic) {\n const gossipIDsByTopic = this.mcache.getGossipIDs(new Set(peersToGossipByTopic.keys()));\n for (const [topic, peersToGossip] of peersToGossipByTopic) {\n this.doEmitGossip(topic, peersToGossip, gossipIDsByTopic.get(topic) ?? []);\n }\n }\n /**\n * Send gossip messages to GossipFactor peers above threshold with a minimum of D_lazy\n * Peers are randomly selected from the heartbeat which exclude mesh + fanout peers\n * We also exclude direct peers, as there is no reason to emit gossip to them\n *\n * @param topic\n * @param candidateToGossip - peers to gossip\n * @param messageIDs - message ids to gossip\n */\n doEmitGossip(topic, candidateToGossip, messageIDs) {\n if (messageIDs.length === 0) {\n return;\n }\n // shuffle to emit in random order\n shuffle(messageIDs);\n // if we are emitting more than GossipsubMaxIHaveLength ids, truncate the list\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // we do the truncation (with shuffling) per peer below\n this.log('too many messages for gossip; will truncate IHAVE list (%d messages)', messageIDs.length);\n }\n if (candidateToGossip.size === 0)\n return;\n let target = this.opts.Dlazy;\n const factor = constants.GossipsubGossipFactor * candidateToGossip.size;\n let peersToGossip = candidateToGossip;\n if (factor > target) {\n target = factor;\n }\n if (target > peersToGossip.size) {\n target = peersToGossip.size;\n }\n else {\n // only shuffle if needed\n peersToGossip = shuffle(Array.from(peersToGossip)).slice(0, target);\n }\n // Emit the IHAVE gossip to the selected peers up to the target\n peersToGossip.forEach((id) => {\n let peerMessageIDs = messageIDs;\n if (messageIDs.length > constants.GossipsubMaxIHaveLength) {\n // shuffle and slice message IDs per peer so that we emit a different set for each peer\n // we have enough reduncancy in the system that this will significantly increase the message\n // coverage when we do truncate\n peerMessageIDs = shuffle(peerMessageIDs.slice()).slice(0, constants.GossipsubMaxIHaveLength);\n }\n this.pushGossip(id, {\n topicID: topic,\n messageIDs: peerMessageIDs\n });\n });\n }\n /**\n * Flush gossip and control messages\n */\n flush() {\n // send gossip first, which will also piggyback control\n for (const [peer, ihave] of this.gossip.entries()) {\n this.gossip.delete(peer);\n this.sendRpc(peer, createGossipRpc([], { ihave }));\n }\n // send the remaining control messages\n for (const [peer, control] of this.control.entries()) {\n this.control.delete(peer);\n const out = createGossipRpc([], { graft: control.graft, prune: control.prune });\n this.sendRpc(peer, out);\n }\n }\n /**\n * Adds new IHAVE messages to pending gossip\n */\n pushGossip(id, controlIHaveMsgs) {\n this.log('Add gossip to %s', id);\n const gossip = this.gossip.get(id) ?? [];\n this.gossip.set(id, gossip.concat(controlIHaveMsgs));\n }\n /**\n * Make a PRUNE control message for a peer in a topic\n */\n async makePrune(id, topic, doPX, onUnsubscribe) {\n this.score.prune(id, topic);\n if (this.streamsOutbound.get(id)?.protocol === constants.GossipsubIDv10) {\n // Gossipsub v1.0 -- no backoff, the peer won't be able to parse it anyway\n return {\n topicID: topic,\n peers: []\n };\n }\n // backoff is measured in seconds\n // GossipsubPruneBackoff and GossipsubUnsubscribeBackoff are measured in milliseconds\n // The protobuf has it as a uint64\n const backoffMs = onUnsubscribe ? this.opts.unsubcribeBackoff : this.opts.pruneBackoff;\n const backoff = backoffMs / 1000;\n this.doAddBackoff(id, topic, backoffMs);\n if (!doPX) {\n return {\n topicID: topic,\n peers: [],\n backoff\n };\n }\n // select peers for Peer eXchange\n const peers = this.getRandomGossipPeers(topic, this.opts.prunePeers, (xid) => {\n return xid !== id && this.score.score(xid) >= 0;\n });\n const px = await Promise.all(Array.from(peers).map(async (peerId) => {\n // see if we have a signed record to send back; if we don't, just send\n // the peer ID and let the pruned peer find them in the DHT -- we can't trust\n // unsigned address records through PX anyways\n // Finding signed records in the DHT is not supported at the time of writing in js-libp2p\n const id = peerIdFromString(peerId);\n let peerInfo;\n try {\n peerInfo = await this.components.peerStore.get(id);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n return {\n peerID: id.toBytes(),\n signedPeerRecord: peerInfo?.peerRecordEnvelope\n };\n }));\n return {\n topicID: topic,\n peers: px,\n backoff\n };\n }\n runHeartbeat = () => {\n const timer = this.metrics?.heartbeatDuration.startTimer();\n this.heartbeat()\n .catch((err) => {\n this.log('Error running heartbeat', err);\n })\n .finally(() => {\n if (timer != null) {\n timer();\n }\n // Schedule the next run if still in started status\n if (this.status.code === GossipStatusCode.started) {\n // Clear previous timeout before overwriting `status.heartbeatTimeout`, it should be completed tho.\n clearTimeout(this.status.heartbeatTimeout);\n // NodeJS setInterval function is innexact, calls drift by a few miliseconds on each call.\n // To run the heartbeat precisely setTimeout() must be used recomputing the delay on every loop.\n let msToNextHeartbeat = this.opts.heartbeatInterval - ((Date.now() - this.status.hearbeatStartMs) % this.opts.heartbeatInterval);\n // If too close to next heartbeat, skip one\n if (msToNextHeartbeat < this.opts.heartbeatInterval * 0.25) {\n msToNextHeartbeat += this.opts.heartbeatInterval;\n this.metrics?.heartbeatSkipped.inc();\n }\n this.status.heartbeatTimeout = setTimeout(this.runHeartbeat, msToNextHeartbeat);\n }\n });\n };\n /**\n * Maintains the mesh and fanout maps in gossipsub.\n */\n async heartbeat() {\n const { D, Dlo, Dhi, Dscore, Dout, fanoutTTL } = this.opts;\n this.heartbeatTicks++;\n // cache scores throught the heartbeat\n const scores = new Map();\n const getScore = (id) => {\n let s = scores.get(id);\n if (s === undefined) {\n s = this.score.score(id);\n scores.set(id, s);\n }\n return s;\n };\n // peer id => topic[]\n const tograft = new Map();\n // peer id => topic[]\n const toprune = new Map();\n // peer id => don't px\n const noPX = new Map();\n // clean up expired backoffs\n this.clearBackoff();\n // clean up peerhave/iasked counters\n this.peerhave.clear();\n this.metrics?.cacheSize.set({ cache: 'iasked' }, this.iasked.size);\n this.iasked.clear();\n // apply IWANT request penalties\n this.applyIwantPenalties();\n // ensure direct peers are connected\n if (this.heartbeatTicks % this.opts.directConnectTicks === 0) {\n // we only do this every few ticks to allow pending connections to complete and account for restarts/downtime\n await this.directConnect();\n }\n // EXTRA: Prune caches\n this.fastMsgIdCache?.prune();\n this.seenCache.prune();\n this.gossipTracer.prune();\n this.publishedMessageIds.prune();\n /**\n * Instead of calling getRandomGossipPeers multiple times to:\n * + get more mesh peers\n * + more outbound peers\n * + oppportunistic grafting\n * + emitGossip\n *\n * We want to loop through the topic peers only a single time and prepare gossip peers for all topics to improve the performance\n */\n const peersToGossipByTopic = new Map();\n // maintain the mesh for topics we have joined\n // eslint-disable-next-line complexity\n this.mesh.forEach((peers, topic) => {\n const peersInTopic = this.topics.get(topic);\n const candidateMeshPeers = new Set();\n const peersToGossip = new Set();\n peersToGossipByTopic.set(topic, peersToGossip);\n if (peersInTopic != null) {\n const shuffledPeers = shuffle(Array.from(peersInTopic));\n const backoff = this.backoff.get(topic);\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id);\n if ((peerStreams != null) &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !peers.has(id) &&\n !this.direct.has(id)) {\n const score = getScore(id);\n if (((backoff == null) || !backoff.has(id)) && score >= 0)\n candidateMeshPeers.add(id);\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold)\n peersToGossip.add(id);\n }\n }\n }\n // prune/graft helper functions (defined per topic)\n const prunePeer = (id, reason) => {\n this.log('HEARTBEAT: Remove mesh link to %s in %s', id, topic);\n // no need to update peer score here as we do it in makePrune\n // add prune backoff record\n this.addBackoff(id, topic);\n // remove peer from mesh\n peers.delete(id);\n // after pruning a peer from mesh, we want to gossip topic to it if its score meet the gossip threshold\n if (getScore(id) >= this.opts.scoreThresholds.gossipThreshold)\n peersToGossip.add(id);\n this.metrics?.onRemoveFromMesh(topic, reason, 1);\n // add to toprune\n const topics = toprune.get(id);\n if (topics == null) {\n toprune.set(id, [topic]);\n }\n else {\n topics.push(topic);\n }\n };\n const graftPeer = (id, reason) => {\n this.log('HEARTBEAT: Add mesh link to %s in %s', id, topic);\n // update peer score\n this.score.graft(id, topic);\n // add peer to mesh\n peers.add(id);\n // when we add a new mesh peer, we don't want to gossip messages to it\n peersToGossip.delete(id);\n this.metrics?.onAddToMesh(topic, reason, 1);\n // add to tograft\n const topics = tograft.get(id);\n if (topics == null) {\n tograft.set(id, [topic]);\n }\n else {\n topics.push(topic);\n }\n };\n // drop all peers with negative score, without PX\n peers.forEach((id) => {\n const score = getScore(id);\n // Record the score\n if (score < 0) {\n this.log('HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s', id, score, topic);\n prunePeer(id, ChurnReason.BadScore);\n noPX.set(id, true);\n }\n });\n // do we have enough peers?\n if (peers.size < Dlo) {\n const ineed = D - peers.size;\n // slice up to first `ineed` items and remove them from candidateMeshPeers\n // same to `const newMeshPeers = candidateMeshPeers.slice(0, ineed)`\n const newMeshPeers = removeFirstNItemsFromSet(candidateMeshPeers, ineed);\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.NotEnough);\n });\n }\n // do we have to many peers?\n if (peers.size > Dhi) {\n let peersArray = Array.from(peers);\n // sort by score\n peersArray.sort((a, b) => getScore(b) - getScore(a));\n // We keep the first D_score peers by score and the remaining up to D randomly\n // under the constraint that we keep D_out peers in the mesh (if we have that many)\n peersArray = peersArray.slice(0, Dscore).concat(shuffle(peersArray.slice(Dscore)));\n // count the outbound peers we are keeping\n let outbound = 0;\n peersArray.slice(0, D).forEach((p) => {\n if (this.outbound.get(p) ?? false) {\n outbound++;\n }\n });\n // if it's less than D_out, bubble up some outbound peers from the random selection\n if (outbound < Dout) {\n const rotate = (i) => {\n // rotate the peersArray to the right and put the ith peer in the front\n const p = peersArray[i];\n for (let j = i; j > 0; j--) {\n peersArray[j] = peersArray[j - 1];\n }\n peersArray[0] = p;\n };\n // first bubble up all outbound peers already in the selection to the front\n if (outbound > 0) {\n let ihave = outbound;\n for (let i = 1; i < D && ihave > 0; i++) {\n // eslint-disable-next-line max-depth\n if (this.outbound.get(peersArray[i]) ?? false) {\n rotate(i);\n ihave--;\n }\n }\n }\n // now bubble up enough outbound peers outside the selection to the front\n let ineed = D - outbound;\n for (let i = D; i < peersArray.length && ineed > 0; i++) {\n if (this.outbound.get(peersArray[i]) ?? false) {\n rotate(i);\n ineed--;\n }\n }\n }\n // prune the excess peers\n peersArray.slice(D).forEach((p) => {\n prunePeer(p, ChurnReason.Excess);\n });\n }\n // do we have enough outbound peers?\n if (peers.size >= Dlo) {\n // count the outbound peers we have\n let outbound = 0;\n peers.forEach((p) => {\n if (this.outbound.get(p) ?? false) {\n outbound++;\n }\n });\n // if it's less than D_out, select some peers with outbound connections and graft them\n if (outbound < Dout) {\n const ineed = Dout - outbound;\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => this.outbound.get(id) === true);\n newMeshPeers.forEach((p) => {\n graftPeer(p, InclusionReason.Outbound);\n });\n }\n }\n // should we try to improve the mesh with opportunistic grafting?\n if (this.heartbeatTicks % this.opts.opportunisticGraftTicks === 0 && peers.size > 1) {\n // Opportunistic grafting works as follows: we check the median score of peers in the\n // mesh; if this score is below the opportunisticGraftThreshold, we select a few peers at\n // random with score over the median.\n // The intention is to (slowly) improve an underperforming mesh by introducing good\n // scoring peers that may have been gossiping at us. This allows us to get out of sticky\n // situations where we are stuck with poor peers and also recover from churn of good peers.\n // now compute the median peer score in the mesh\n const peersList = Array.from(peers).sort((a, b) => getScore(a) - getScore(b));\n const medianIndex = Math.floor(peers.size / 2);\n const medianScore = getScore(peersList[medianIndex]);\n // if the median score is below the threshold, select a better peer (if any) and GRAFT\n if (medianScore < this.opts.scoreThresholds.opportunisticGraftThreshold) {\n const ineed = this.opts.opportunisticGraftPeers;\n const newMeshPeers = removeItemsFromSet(candidateMeshPeers, ineed, (id) => getScore(id) > medianScore);\n for (const id of newMeshPeers) {\n this.log('HEARTBEAT: Opportunistically graft peer %s on topic %s', id, topic);\n graftPeer(id, InclusionReason.Opportunistic);\n }\n }\n }\n });\n // expire fanout for topics we haven't published to in a while\n const now = Date.now();\n this.fanoutLastpub.forEach((lastpb, topic) => {\n if (lastpb + fanoutTTL < now) {\n this.fanout.delete(topic);\n this.fanoutLastpub.delete(topic);\n }\n });\n // maintain our fanout for topics we are publishing but we have not joined\n this.fanout.forEach((fanoutPeers, topic) => {\n // checks whether our peers are still in the topic and have a score above the publish threshold\n const topicPeers = this.topics.get(topic);\n fanoutPeers.forEach((id) => {\n if (!(topicPeers?.has(id) ?? false) || getScore(id) < this.opts.scoreThresholds.publishThreshold) {\n fanoutPeers.delete(id);\n }\n });\n const peersInTopic = this.topics.get(topic);\n const candidateFanoutPeers = [];\n // the fanout map contains topics to which we are not subscribed.\n const peersToGossip = new Set();\n peersToGossipByTopic.set(topic, peersToGossip);\n if (peersInTopic != null) {\n const shuffledPeers = shuffle(Array.from(peersInTopic));\n for (const id of shuffledPeers) {\n const peerStreams = this.streamsOutbound.get(id);\n if ((peerStreams != null) &&\n this.multicodecs.includes(peerStreams.protocol) &&\n !fanoutPeers.has(id) &&\n !this.direct.has(id)) {\n const score = getScore(id);\n if (score >= this.opts.scoreThresholds.publishThreshold)\n candidateFanoutPeers.push(id);\n // instead of having to find gossip peers after heartbeat which require another loop\n // we prepare peers to gossip in a topic within heartbeat to improve performance\n if (score >= this.opts.scoreThresholds.gossipThreshold)\n peersToGossip.add(id);\n }\n }\n }\n // do we need more peers?\n if (fanoutPeers.size < D) {\n const ineed = D - fanoutPeers.size;\n candidateFanoutPeers.slice(0, ineed).forEach((id) => {\n fanoutPeers.add(id);\n peersToGossip?.delete(id);\n });\n }\n });\n this.emitGossip(peersToGossipByTopic);\n // send coalesced GRAFT/PRUNE messages (will piggyback gossip)\n await this.sendGraftPrune(tograft, toprune, noPX);\n // flush pending gossip that wasn't piggybacked above\n this.flush();\n // advance the message history window\n this.mcache.shift();\n this.dispatchEvent(new CustomEvent('gossipsub:heartbeat'));\n }\n /**\n * Given a topic, returns up to count peers subscribed to that topic\n * that pass an optional filter function\n *\n * @param topic\n * @param count\n * @param filter - a function to filter acceptable peers\n */\n getRandomGossipPeers(topic, count, filter = () => true) {\n const peersInTopic = this.topics.get(topic);\n if (peersInTopic == null) {\n return new Set();\n }\n // Adds all peers using our protocol\n // that also pass the filter function\n let peers = [];\n peersInTopic.forEach((id) => {\n const peerStreams = this.streamsOutbound.get(id);\n if (peerStreams == null) {\n return;\n }\n if (this.multicodecs.includes(peerStreams.protocol) && filter(id)) {\n peers.push(id);\n }\n });\n // Pseudo-randomly shuffles peers\n peers = shuffle(peers);\n if (count > 0 && peers.length > count) {\n peers = peers.slice(0, count);\n }\n return new Set(peers);\n }\n onScrapeMetrics(metrics) {\n /* Data structure sizes */\n metrics.mcacheSize.set(this.mcache.size);\n metrics.mcacheNotValidatedCount.set(this.mcache.notValidatedCount);\n // Arbitrary size\n metrics.cacheSize.set({ cache: 'direct' }, this.direct.size);\n metrics.cacheSize.set({ cache: 'seenCache' }, this.seenCache.size);\n metrics.cacheSize.set({ cache: 'fastMsgIdCache' }, this.fastMsgIdCache?.size ?? 0);\n metrics.cacheSize.set({ cache: 'publishedMessageIds' }, this.publishedMessageIds.size);\n metrics.cacheSize.set({ cache: 'mcache' }, this.mcache.size);\n metrics.cacheSize.set({ cache: 'score' }, this.score.size);\n metrics.cacheSize.set({ cache: 'gossipTracer.promises' }, this.gossipTracer.size);\n metrics.cacheSize.set({ cache: 'gossipTracer.requests' }, this.gossipTracer.requestMsByMsgSize);\n // Bounded by topic\n metrics.cacheSize.set({ cache: 'topics' }, this.topics.size);\n metrics.cacheSize.set({ cache: 'subscriptions' }, this.subscriptions.size);\n metrics.cacheSize.set({ cache: 'mesh' }, this.mesh.size);\n metrics.cacheSize.set({ cache: 'fanout' }, this.fanout.size);\n // Bounded by peer\n metrics.cacheSize.set({ cache: 'peers' }, this.peers.size);\n metrics.cacheSize.set({ cache: 'streamsOutbound' }, this.streamsOutbound.size);\n metrics.cacheSize.set({ cache: 'streamsInbound' }, this.streamsInbound.size);\n metrics.cacheSize.set({ cache: 'acceptFromWhitelist' }, this.acceptFromWhitelist.size);\n metrics.cacheSize.set({ cache: 'gossip' }, this.gossip.size);\n metrics.cacheSize.set({ cache: 'control' }, this.control.size);\n metrics.cacheSize.set({ cache: 'peerhave' }, this.peerhave.size);\n metrics.cacheSize.set({ cache: 'outbound' }, this.outbound.size);\n // 2D nested data structure\n let backoffSize = 0;\n const now = Date.now();\n metrics.connectedPeersBackoffSec.reset();\n for (const backoff of this.backoff.values()) {\n backoffSize += backoff.size;\n for (const [peer, expiredMs] of backoff.entries()) {\n if (this.peers.has(peer)) {\n metrics.connectedPeersBackoffSec.observe(Math.max(0, expiredMs - now) / 1000);\n }\n }\n }\n metrics.cacheSize.set({ cache: 'backoff' }, backoffSize);\n // Peer counts\n for (const [topicStr, peers] of this.topics) {\n metrics.topicPeersCount.set({ topicStr }, peers.size);\n }\n for (const [topicStr, peers] of this.mesh) {\n metrics.meshPeerCounts.set({ topicStr }, peers.size);\n }\n // Peer scores\n const scores = [];\n const scoreByPeer = new Map();\n metrics.behaviourPenalty.reset();\n for (const peerIdStr of this.peers.keys()) {\n const score = this.score.score(peerIdStr);\n scores.push(score);\n scoreByPeer.set(peerIdStr, score);\n metrics.behaviourPenalty.observe(this.score.peerStats.get(peerIdStr)?.behaviourPenalty ?? 0);\n }\n metrics.registerScores(scores, this.opts.scoreThresholds);\n // Breakdown score per mesh topicLabel\n metrics.registerScorePerMesh(this.mesh, scoreByPeer);\n // Breakdown on each score weight\n const sw = computeAllPeersScoreWeights(this.peers.keys(), this.score.peerStats, this.score.params, this.score.peerIPs, metrics.topicStrToLabel);\n metrics.registerScoreWeights(sw);\n }\n}\nexport function gossipsub(init = {}) {\n return (components) => new GossipSub(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * This is similar to https://github.com/daviddias/time-cache/blob/master/src/index.js\n * for our own need, we don't use lodash throttle to improve performance.\n * This gives 4x - 5x performance gain compared to npm TimeCache\n */\nexport class SimpleTimeCache {\n entries = new Map();\n validityMs;\n constructor(opts) {\n this.validityMs = opts.validityMs;\n // allow negative validityMs so that this does not cache anything, spec test compliance.spec.js\n // sends duplicate messages and expect peer to receive all. Application likely uses positive validityMs\n }\n get size() {\n return this.entries.size;\n }\n /** Returns true if there was a key collision and the entry is dropped */\n put(key, value) {\n if (this.entries.has(key)) {\n // Key collisions break insertion order in the entries cache, which break prune logic.\n // prune relies on each iterated entry to have strictly ascending validUntilMs, else it\n // won't prune expired entries and SimpleTimeCache will grow unexpectedly.\n // As of Oct 2022 NodeJS v16, inserting the same key twice with different value does not\n // change the key position in the iterator stream. A unit test asserts this behaviour.\n return true;\n }\n this.entries.set(key, { value, validUntilMs: Date.now() + this.validityMs });\n return false;\n }\n prune() {\n const now = Date.now();\n for (const [k, v] of this.entries.entries()) {\n if (v.validUntilMs < now) {\n this.entries.delete(k);\n }\n else {\n // Entries are inserted with strictly ascending validUntilMs.\n // Stop early to save iterations\n break;\n }\n }\n }\n has(key) {\n return this.entries.has(key);\n }\n get(key) {\n const value = this.entries.get(key);\n return (value != null) && value.validUntilMs >= Date.now() ? value.value : undefined;\n }\n clear() {\n this.entries.clear();\n }\n}\n//# sourceMappingURL=time-cache.js.map","import { unmarshalPrivateKey } from '@libp2p/crypto/keys';\nimport { StrictSign, StrictNoSign } from '@libp2p/interface';\nimport { PublishConfigType } from '../types.js';\n/**\n * Prepare a PublishConfig object from a PeerId.\n */\nexport async function getPublishConfigFromPeerId(signaturePolicy, peerId) {\n switch (signaturePolicy) {\n case StrictSign: {\n if (peerId == null) {\n throw Error('Must provide PeerId');\n }\n if (peerId.privateKey == null) {\n throw Error('Cannot sign message, no private key present');\n }\n if (peerId.publicKey == null) {\n throw Error('Cannot sign message, no public key present');\n }\n // Transform privateKey once at initialization time instead of once per message\n const privateKey = await unmarshalPrivateKey(peerId.privateKey);\n return {\n type: PublishConfigType.Signing,\n author: peerId,\n key: peerId.publicKey,\n privateKey\n };\n }\n case StrictNoSign:\n return {\n type: PublishConfigType.Anonymous\n };\n default:\n throw new Error(`Unknown signature policy \"${signaturePolicy}\"`);\n }\n}\n//# sourceMappingURL=publishConfig.js.map","export const second = 1000;\nexport const minute = 60 * second;\n/**\n * RelayCodec is the libp2p identifier for the waku relay protocol\n */\nexport const RelayCodecs = [\"/vac/waku/relay/2.0.0\"];\n/**\n * RelayGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to RelayGossipFactor * (total number of non-mesh peers), or\n * RelayDlazy, whichever is greater.\n */\nexport const RelayGossipFactor = 0.25;\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const RelayHeartbeatInitialDelay = 100;\n/**\n * RelayHeartbeatInterval controls the time between heartbeats.\n */\nexport const RelayHeartbeatInterval = second;\n/**\n * RelayPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to RelayPrunePeers other peers that we\n * know of.\n */\nexport const RelayPrunePeers = 16;\n/**\n * RelayPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of RelayPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least RelayPruneBackoff\n * before attempting to re-graft.\n */\nexport const RelayPruneBackoff = minute;\n/**\n * RelayFanoutTTL controls how long we keep track of the fanout state. If it's been\n * RelayFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const RelayFanoutTTL = minute;\n/**\n * RelayOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every RelayOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const RelayOpportunisticGraftTicks = 60;\n/**\n * RelayOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const RelayOpportunisticGraftPeers = 2;\n/**\n * RelayMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const RelayMaxIHaveLength = 5000;\n//# sourceMappingURL=constants.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { TopicValidatorResult } from \"@libp2p/interface\";\nimport { proto_message as proto } from \"@waku/proto\";\nimport { Logger } from \"@waku/utils\";\nconst log = new Logger(\"relay\");\nexport function messageValidator(peer, message) {\n const startTime = performance.now();\n log.info(`validating message from ${peer} received on ${message.topic}`);\n let result = TopicValidatorResult.Accept;\n try {\n const protoMessage = proto.WakuMessage.decode(message.data);\n if (!protoMessage.contentTopic ||\n !protoMessage.contentTopic.length ||\n !protoMessage.payload ||\n !protoMessage.payload.length) {\n result = TopicValidatorResult.Reject;\n }\n }\n catch (e) {\n result = TopicValidatorResult.Reject;\n }\n const endTime = performance.now();\n const timeTakenMs = endTime - startTime;\n if (timeTakenMs > 100) {\n log.warn(`message validation took ${timeTakenMs}ms for peer ${peer} on topic ${message.topic}. This should be less than 100ms.`);\n }\n else {\n log.info(`message validation took ${timeTakenMs}ms for peer ${peer} on topic ${message.topic}`);\n }\n return result;\n}\n//# sourceMappingURL=message_validator.js.map","import { GossipSub } from \"@chainsafe/libp2p-gossipsub\";\nimport { SignaturePolicy } from \"@chainsafe/libp2p-gossipsub/types\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { DefaultPubsubTopic, ProtocolError } from \"@waku/interfaces\";\nimport { isWireSizeUnderCap, toAsyncIterator } from \"@waku/utils\";\nimport { pushOrInitMapSet } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport { RelayCodecs } from \"./constants.js\";\nimport { messageValidator } from \"./message_validator.js\";\nimport { TopicOnlyDecoder } from \"./topic_only_message.js\";\nconst log = new Logger(\"relay\");\n/**\n * Implements the [Waku v2 Relay protocol](https://rfc.vac.dev/spec/11/).\n * Throws if libp2p.pubsub does not support Waku Relay\n */\nclass Relay {\n pubsubTopics;\n defaultDecoder;\n static multicodec = RelayCodecs[0];\n gossipSub;\n /**\n * observers called when receiving new message.\n * Observers under key `\"\"` are always called.\n */\n observers;\n constructor(libp2p, pubsubTopics) {\n if (!this.isRelayPubsub(libp2p.services.pubsub)) {\n throw Error(`Failed to initialize Relay. libp2p.pubsub does not support ${Relay.multicodec}`);\n }\n this.gossipSub = libp2p.services.pubsub;\n this.pubsubTopics = new Set(pubsubTopics);\n if (this.gossipSub.isStarted()) {\n this.subscribeToAllTopics();\n }\n this.observers = new Map();\n // Default PubsubTopic decoder\n // TODO: User might want to decide what decoder should be used (e.g. for RLN)\n this.defaultDecoder = new TopicOnlyDecoder();\n }\n /**\n * Mounts the gossipsub protocol onto the libp2p node\n * and subscribes to all the topics.\n *\n * @override\n * @returns {void}\n */\n async start() {\n if (this.gossipSub.isStarted()) {\n throw Error(\"GossipSub already started.\");\n }\n await this.gossipSub.start();\n this.subscribeToAllTopics();\n }\n /**\n * Send Waku message.\n */\n async send(encoder, message) {\n const successes = [];\n const { pubsubTopic } = encoder;\n if (!this.pubsubTopics.has(pubsubTopic)) {\n log.error(\"Failed to send waku relay: topic not configured\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ]\n };\n }\n const msg = await encoder.toWire(message);\n if (!msg) {\n log.error(\"Failed to encode message, aborting publish\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.ENCODE_FAILED\n }\n ]\n };\n }\n if (!isWireSizeUnderCap(msg)) {\n log.error(\"Failed to send waku relay: message is bigger that 1MB\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.SIZE_TOO_BIG\n }\n ]\n };\n }\n const { recipients } = await this.gossipSub.publish(pubsubTopic, msg);\n return {\n successes: recipients,\n failures: []\n };\n }\n subscribe(decoders, callback) {\n const observers = [];\n for (const decoder of Array.isArray(decoders) ? decoders : [decoders]) {\n const { pubsubTopic } = decoder;\n const ctObs = this.observers.get(pubsubTopic) ?? new Map();\n const observer = { pubsubTopic, decoder, callback };\n pushOrInitMapSet(ctObs, decoder.contentTopic, observer);\n this.observers.set(pubsubTopic, ctObs);\n observers.push([pubsubTopic, observer]);\n }\n return () => {\n this.removeObservers(observers);\n };\n }\n removeObservers(observers) {\n for (const [pubsubTopic, observer] of observers) {\n const ctObs = this.observers.get(pubsubTopic);\n if (!ctObs)\n continue;\n const contentTopic = observer.decoder.contentTopic;\n const _obs = ctObs.get(contentTopic);\n if (!_obs)\n continue;\n _obs.delete(observer);\n ctObs.set(contentTopic, _obs);\n this.observers.set(pubsubTopic, ctObs);\n }\n }\n toSubscriptionIterator(decoders) {\n return toAsyncIterator(this, decoders);\n }\n getActiveSubscriptions() {\n const map = new Map();\n for (const pubsubTopic of this.pubsubTopics) {\n map.set(pubsubTopic, Array.from(this.observers.keys()));\n }\n return map;\n }\n getMeshPeers(topic = DefaultPubsubTopic) {\n return this.gossipSub.getMeshPeers(topic);\n }\n subscribeToAllTopics() {\n for (const pubsubTopic of this.pubsubTopics) {\n this.gossipSubSubscribe(pubsubTopic);\n }\n }\n async processIncomingMessage(pubsubTopic, bytes) {\n const topicOnlyMsg = await this.defaultDecoder.fromWireToProtoObj(bytes);\n if (!topicOnlyMsg || !topicOnlyMsg.contentTopic) {\n log.warn(\"Message does not have a content topic, skipping\");\n return;\n }\n // Retrieve the map of content topics for the given pubsubTopic\n const contentTopicMap = this.observers.get(pubsubTopic);\n if (!contentTopicMap) {\n return;\n }\n // Retrieve the set of observers for the given contentTopic\n const observers = contentTopicMap.get(topicOnlyMsg.contentTopic);\n if (!observers) {\n return;\n }\n await Promise.all(Array.from(observers).map(({ decoder, callback }) => {\n return (async () => {\n try {\n const protoMsg = await decoder.fromWireToProtoObj(bytes);\n if (!protoMsg) {\n log.error(\"Internal error: message previously decoded failed on 2nd pass.\");\n return;\n }\n const msg = await decoder.fromProtoObj(pubsubTopic, protoMsg);\n if (msg) {\n await callback(msg);\n }\n else {\n log.error(\"Failed to decode messages on\", topicOnlyMsg.contentTopic);\n }\n }\n catch (error) {\n log.error(\"Error while decoding message:\", error);\n }\n })();\n }));\n }\n /**\n * Subscribe to a pubsub topic and start emitting Waku messages to observers.\n *\n * @override\n */\n gossipSubSubscribe(pubsubTopic) {\n this.gossipSub.addEventListener(\"gossipsub:message\", (event) => {\n if (event.detail.msg.topic !== pubsubTopic)\n return;\n this.processIncomingMessage(event.detail.msg.topic, event.detail.msg.data).catch((e) => log.error(\"Failed to process incoming message\", e));\n });\n this.gossipSub.topicValidators.set(pubsubTopic, messageValidator);\n this.gossipSub.subscribe(pubsubTopic);\n }\n isRelayPubsub(pubsub) {\n return pubsub?.multicodecs?.includes(Relay.multicodec) ?? false;\n }\n}\nexport function wakuRelay(pubsubTopics) {\n return (libp2p) => new Relay(libp2p, pubsubTopics);\n}\nexport function wakuGossipSub(init = {}) {\n return (components) => {\n init = {\n ...init,\n msgIdFn: ({ data }) => sha256(data),\n // Ensure that no signature is included nor expected in the messages.\n globalSignaturePolicy: SignaturePolicy.StrictNoSign,\n fallbackToFloodsub: false\n };\n const pubsub = new GossipSub(components, init);\n pubsub.multicodecs = RelayCodecs;\n return pubsub;\n };\n}\n//# sourceMappingURL=index.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\nimport debug from 'debug';\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64 } from 'multiformats/bases/base64';\nimport { truncatePeerId } from './utils.js';\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v);\n};\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v) => {\n return v == null ? 'undefined' : base32.baseEncode(v);\n};\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v) => {\n return v == null ? 'undefined' : base64.baseEncode(v);\n};\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\nfunction createDisabledLogger(namespace) {\n const logger = () => { };\n logger.enabled = false;\n logger.color = '';\n logger.diff = 0;\n logger.log = () => { };\n logger.namespace = namespace;\n logger.destroy = () => true;\n logger.extend = () => logger;\n return logger;\n}\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger(peerId, options = {}) {\n return prefixLogger(truncatePeerId(peerId, options));\n}\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger(prefix) {\n return {\n forComponent(name) {\n return logger(`${prefix}:${name}`);\n }\n };\n}\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger() {\n return {\n forComponent(name) {\n return logger(name);\n }\n };\n}\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger(name) {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`);\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map(r => r.toString()).find(n => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`);\n }\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n });\n}\nexport function disable() {\n debug.disable();\n}\nexport function enable(namespaces) {\n debug.enable(namespaces);\n}\nexport function enabled(namespaces) {\n return debug.enabled(namespaces);\n}\n//# sourceMappingURL=index.js.map","/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable(iter, map) {\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n const next = iter.next();\n const val = next.value;\n if (next.done === true || val == null) {\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n return {\n done: false,\n value: map(val)\n };\n }\n };\n return iterator;\n}\n//# sourceMappingURL=util.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { mapIterable } from './util.js';\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n set;\n constructor(set) {\n this.set = new Set();\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString());\n }\n }\n }\n get size() {\n return this.set.size;\n }\n [Symbol.iterator]() {\n return this.values();\n }\n add(peer) {\n this.set.add(peer.toString());\n }\n clear() {\n this.set.clear();\n }\n delete(peer) {\n this.set.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.set.entries(), (val) => {\n const peerId = peerIdFromString(val[0]);\n return [peerId, peerId];\n });\n }\n forEach(predicate) {\n this.set.forEach((str) => {\n const id = peerIdFromString(str);\n predicate(id, id, this);\n });\n }\n has(peer) {\n return this.set.has(peer.toString());\n }\n values() {\n return mapIterable(this.set.values(), (val) => {\n return peerIdFromString(val);\n });\n }\n intersection(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n difference(other) {\n const output = new PeerSet();\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n union(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n output.add(peerId);\n }\n for (const peerId of this) {\n output.add(peerId);\n }\n return output;\n }\n}\nexport function peerSet() {\n return new PeerSet();\n}\n//# sourceMappingURL=set.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Generate, import, and export PeerIDs.\n *\n * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.\n *\n * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.\n *\n * @example\n *\n * ```TypeScript\n * import { createEd25519PeerId } from '@libp2p/peer-id-factory'\n *\n * const peerId = await createEd25519PeerId()\n * console.log(peerId.toString())\n * ```\n *\n * ```bash\n * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD\n * ```\n */\nimport { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { PeerIdProto } from './proto.js';\nexport const createEd25519PeerId = async () => {\n const key = await generateKeyPair('Ed25519');\n const id = await createFromPrivKey(key);\n if (id.type === 'Ed25519') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport const createSecp256k1PeerId = async () => {\n const key = await generateKeyPair('secp256k1');\n const id = await createFromPrivKey(key);\n if (id.type === 'secp256k1') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport const createRSAPeerId = async (opts) => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048);\n const id = await createFromPrivKey(key);\n if (id.type === 'RSA') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport async function createFromPubKey(publicKey) {\n return peerIdFromKeys(marshalPublicKey(publicKey));\n}\nexport async function createFromPrivKey(privateKey) {\n return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey));\n}\nexport function exportToProtobuf(peerId, excludePrivateKey) {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n });\n}\nexport async function createFromProtobuf(buf) {\n const { id, privKey, pubKey } = PeerIdProto.decode(buf);\n return createFromParts(id ?? new Uint8Array(0), privKey, pubKey);\n}\nexport async function createFromJSON(obj) {\n return createFromParts(uint8ArrayFromString(obj.id, 'base58btc'), obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined, obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined);\n}\nasync function createFromParts(multihash, privKey, pubKey) {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey);\n return createFromPrivKey(key);\n }\n else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey);\n return createFromPubKey(key);\n }\n return peerIdFromBytes(multihash);\n}\n//# sourceMappingURL=index.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { mapIterable } from './util.js';\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n map;\n constructor(map) {\n this.map = new Map();\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value);\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n clear() {\n this.map.clear();\n }\n delete(peer) {\n return this.map.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.map.entries(), (val) => {\n return [peerIdFromString(val[0]), val[1]];\n });\n }\n forEach(fn) {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this);\n });\n }\n get(peer) {\n return this.map.get(peer.toString());\n }\n has(peer) {\n return this.map.has(peer.toString());\n }\n set(peer, value) {\n this.map.set(peer.toString(), value);\n }\n keys() {\n return mapIterable(this.map.keys(), (val) => {\n return peerIdFromString(val);\n });\n }\n values() {\n return this.map.values();\n }\n get size() {\n return this.map.size;\n }\n}\nexport function peerMap() {\n return new PeerMap();\n}\n//# sourceMappingURL=map.js.map","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n","const events = {};\nconst observable = (worker) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n if (worker.port != null) {\n worker.port.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n }\n};\nobservable.addEventListener = (type, fn) => {\n if (events[type] == null) {\n events[type] = [];\n }\n events[type].push(fn);\n};\nobservable.removeEventListener = (type, fn) => {\n if (events[type] == null) {\n return;\n }\n events[type] = events[type]\n .filter(listener => listener === fn);\n};\nobservable.dispatchEvent = function (type, worker, event) {\n if (events[type] == null) {\n return;\n }\n events[type].forEach(fn => fn(worker, event));\n};\nexport default observable;\n//# sourceMappingURL=index.js.map","export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read';\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read';\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read';\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write';\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write';\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write';\n//# sourceMappingURL=constants.js.map","import observer from 'observable-webworkers';\nimport { WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK } from './constants.js';\nimport { nanoid } from './utils.js';\nconst handleWorkerLockRequest = (emitter, masterEvent, requestType, releaseType, grantType) => {\n return (worker, event) => {\n if (event.data.type !== requestType) {\n return;\n }\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async () => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n });\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener);\n resolve();\n }\n };\n worker.addEventListener('message', releaseEventListener);\n });\n }\n }\n }));\n };\n};\nconst makeWorkerLockRequest = (name, requestType, grantType, releaseType) => {\n return async () => {\n const id = nanoid();\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n });\n return new Promise((resolve) => {\n const listener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n };\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener);\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n });\n });\n }\n };\n globalThis.addEventListener('message', listener);\n });\n };\n};\nconst defaultOptions = {\n singleProcess: false\n};\nexport default (options) => {\n options = Object.assign({}, defaultOptions, options);\n const isPrimary = Boolean(globalThis.document) || options.singleProcess;\n if (isPrimary) {\n const emitter = new EventTarget();\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK));\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK));\n return emitter;\n }\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n };\n};\n//# sourceMappingURL=browser.js.map","export const nanoid = (size = 21) => {\n return Math.random().toString().substring(2);\n};\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\nimport PQueue from 'p-queue';\nimport pTimeout from 'p-timeout';\nimport impl from './node.js';\nconst mutexes = {};\nlet implementation;\nasync function createReleaseable(queue, options) {\n let res;\n const p = new Promise((resolve) => {\n res = resolve;\n });\n void queue.add(async () => pTimeout((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve();\n });\n });\n })(), {\n milliseconds: options.timeout\n }));\n return p;\n}\nconst createMutex = (name, options) => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n };\n }\n const masterQueue = new PQueue({ concurrency: 1 });\n let readQueue;\n return {\n async readLock() {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options);\n }\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n });\n const localReadQueue = readQueue;\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options);\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start();\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null;\n }\n });\n });\n return readPromise;\n },\n async writeLock() {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null;\n return createReleaseable(masterQueue, options);\n }\n };\n};\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n};\nexport default function createMortice(options) {\n const opts = Object.assign({}, defaultOptions, options);\n if (implementation == null) {\n implementation = impl(opts);\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].readLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n implementation.addEventListener('requestWriteLock', async (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].writeLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n }\n }\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts);\n }\n return mutexes[opts.name];\n}\n//# sourceMappingURL=index.js.map","export const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS'\n};\n//# sourceMappingURL=errors.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Peer;\n(function (Peer) {\n let Peer$metadataEntry;\n (function (Peer$metadataEntry) {\n let _codec;\n Peer$metadataEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.value);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n key: '',\n value: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string();\n break;\n case 2:\n obj.value = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$metadataEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$metadataEntry.codec());\n };\n Peer$metadataEntry.decode = (buf) => {\n return decodeMessage(buf, Peer$metadataEntry.codec());\n };\n })(Peer$metadataEntry = Peer.Peer$metadataEntry || (Peer.Peer$metadataEntry = {}));\n let Peer$tagsEntry;\n (function (Peer$tagsEntry) {\n let _codec;\n Peer$tagsEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if (obj.value != null) {\n w.uint32(18);\n Tag.codec().encode(obj.value, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n key: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string();\n break;\n case 2:\n obj.value = Tag.codec().decode(reader, reader.uint32());\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$tagsEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$tagsEntry.codec());\n };\n Peer$tagsEntry.decode = (buf) => {\n return decodeMessage(buf, Peer$tagsEntry.codec());\n };\n })(Peer$tagsEntry = Peer.Peer$tagsEntry || (Peer.Peer$tagsEntry = {}));\n let _codec;\n Peer.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10);\n Address.codec().encode(value, w);\n }\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(18);\n w.string(value);\n }\n }\n if (obj.publicKey != null) {\n w.uint32(34);\n w.bytes(obj.publicKey);\n }\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42);\n w.bytes(obj.peerRecordEnvelope);\n }\n if (obj.metadata != null && obj.metadata.size !== 0) {\n for (const [key, value] of obj.metadata.entries()) {\n w.uint32(50);\n Peer.Peer$metadataEntry.codec().encode({ key, value }, w);\n }\n }\n if (obj.tags != null && obj.tags.size !== 0) {\n for (const [key, value] of obj.tags.entries()) {\n w.uint32(58);\n Peer.Peer$tagsEntry.codec().encode({ key, value }, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n addresses: [],\n protocols: [],\n metadata: new Map(),\n tags: new Map()\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()));\n break;\n case 2:\n obj.protocols.push(reader.string());\n break;\n case 4:\n obj.publicKey = reader.bytes();\n break;\n case 5:\n obj.peerRecordEnvelope = reader.bytes();\n break;\n case 6: {\n const entry = Peer.Peer$metadataEntry.codec().decode(reader, reader.uint32());\n obj.metadata.set(entry.key, entry.value);\n break;\n }\n case 7: {\n const entry = Peer.Peer$tagsEntry.codec().decode(reader, reader.uint32());\n obj.tags.set(entry.key, entry.value);\n break;\n }\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer.encode = (obj) => {\n return encodeMessage(obj, Peer.codec());\n };\n Peer.decode = (buf) => {\n return decodeMessage(buf, Peer.codec());\n };\n})(Peer || (Peer = {}));\nexport var Address;\n(function (Address) {\n let _codec;\n Address.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (obj.isCertified != null) {\n w.uint32(16);\n w.bool(obj.isCertified);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n case 2:\n obj.isCertified = reader.bool();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Address.encode = (obj) => {\n return encodeMessage(obj, Address.codec());\n };\n Address.decode = (buf) => {\n return decodeMessage(buf, Address.codec());\n };\n})(Address || (Address = {}));\nexport var Tag;\n(function (Tag) {\n let _codec;\n Tag.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.value != null && obj.value !== 0)) {\n w.uint32(8);\n w.uint32(obj.value);\n }\n if (obj.expiry != null) {\n w.uint32(16);\n w.uint64(obj.expiry);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n value: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.value = reader.uint32();\n break;\n case 2:\n obj.expiry = reader.uint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Tag.encode = (obj) => {\n return encodeMessage(obj, Tag.codec());\n };\n Tag.decode = (buf) => {\n return decodeMessage(buf, Tag.codec());\n };\n})(Tag || (Tag = {}));\n//# sourceMappingURL=peer.js.map","import { peerIdFromPeerId } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { Peer as PeerPB } from '../pb/peer.js';\nexport function bytesToPeer(peerId, buf) {\n const peer = PeerPB.decode(buf);\n if (peer.publicKey != null && peerId.publicKey == null) {\n peerId = peerIdFromPeerId({\n ...peerId,\n publicKey: peerId.publicKey\n });\n }\n const tags = new Map();\n // remove any expired tags\n const now = BigInt(Date.now());\n for (const [key, tag] of peer.tags.entries()) {\n if (tag.expiry != null && tag.expiry < now) {\n continue;\n }\n tags.set(key, tag);\n }\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr: ma, isCertified }) => {\n return {\n multiaddr: multiaddr(ma),\n isCertified: isCertified ?? false\n };\n }),\n metadata: peer.metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined,\n tags\n };\n}\n//# sourceMappingURL=bytes-to-peer.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst pathSepS = '/';\nconst pathSepB = new TextEncoder().encode(pathSepS);\nconst pathSep = pathSepB[0];\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n _buf;\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor(s, clean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s);\n }\n else if (s instanceof Uint8Array) {\n this._buf = s;\n }\n else {\n throw new Error('Invalid key, should be String of Uint8Array');\n }\n if (clean == null) {\n clean = true;\n }\n if (clean) {\n this.clean();\n }\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key');\n }\n }\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString(encoding = 'utf8') {\n return uint8ArrayToString(this._buf, encoding);\n }\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array() {\n return this._buf;\n }\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag]() {\n return `Key(${this.toString()})`;\n }\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces(list) {\n return new Key(list.join(pathSepS));\n }\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random() {\n return new Key(Math.random().toString().substring(2));\n }\n /**\n * @param {*} other\n */\n static asKey(other) {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other);\n }\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array());\n }\n return null;\n }\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean() {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB;\n }\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1);\n bytes.fill(pathSep, 0, 1);\n bytes.set(this._buf, 1);\n this._buf = bytes;\n }\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1);\n }\n }\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less(key) {\n const list1 = this.list();\n const list2 = key.list();\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false;\n }\n const c1 = list1[i];\n const c2 = list2[i];\n if (c1 < c2) {\n return true;\n }\n else if (c1 > c2) {\n return false;\n }\n }\n return list1.length < list2.length;\n }\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse() {\n return Key.withNamespaces(this.list().slice().reverse());\n }\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces() {\n return this.list();\n }\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace() {\n const ns = this.namespaces();\n return ns[ns.length - 1];\n }\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list() {\n return this.toString().split(pathSepS).slice(1);\n }\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type() {\n return namespaceType(this.baseNamespace());\n }\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name() {\n return namespaceValue(this.baseNamespace());\n }\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance(s) {\n return new Key(this.toString() + ':' + s);\n }\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path() {\n let p = this.parent().toString();\n if (!p.endsWith(pathSepS)) {\n p += pathSepS;\n }\n p += this.type();\n return new Key(p);\n }\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent() {\n const list = this.list();\n if (list.length === 1) {\n return new Key(pathSepS);\n }\n return new Key(list.slice(0, -1).join(pathSepS));\n }\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child(key) {\n if (this.toString() === pathSepS) {\n return key;\n }\n else if (key.toString() === pathSepS) {\n return this;\n }\n return new Key(this.toString() + key.toString(), false);\n }\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return other.toString().startsWith(this.toString());\n }\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return this.toString().startsWith(other.toString());\n }\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel() {\n return this.list().length === 1;\n }\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat(...keys) {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))]);\n }\n}\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType(ns) {\n const parts = ns.split(':');\n if (parts.length < 2) {\n return '';\n }\n return parts.slice(0, -1).join(':');\n}\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue(ns) {\n const parts = ns.split(':');\n return parts[parts.length - 1];\n}\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten(arr) {\n return ([]).concat(...arr);\n}\n//# sourceMappingURL=key.js.map","import { CodeError } from '@libp2p/interface';\nimport { isPeerId } from '@libp2p/interface';\nimport { Key } from 'interface-datastore/key';\nimport { codes } from '../errors.js';\nexport const NAMESPACE_COMMON = '/peers/';\nexport function peerIdToDatastoreKey(peerId) {\n if (!isPeerId(peerId) || peerId.type == null) {\n throw new CodeError('Invalid PeerId', codes.ERR_INVALID_PARAMETERS);\n }\n const b32key = peerId.toCID().toString();\n return new Key(`${NAMESPACE_COMMON}${b32key}`);\n}\n//# sourceMappingURL=peer-id-to-datastore-key.js.map","import { CodeError } from '@libp2p/interface';\nimport { isMultiaddr, multiaddr } from '@multiformats/multiaddr';\nimport { codes } from '../errors.js';\nexport async function dedupeFilterAndSortAddresses(peerId, filter, addresses) {\n const addressMap = new Map();\n for (const addr of addresses) {\n if (addr == null) {\n continue;\n }\n if (addr.multiaddr instanceof Uint8Array) {\n addr.multiaddr = multiaddr(addr.multiaddr);\n }\n if (!isMultiaddr(addr.multiaddr)) {\n throw new CodeError('Multiaddr was invalid', codes.ERR_INVALID_PARAMETERS);\n }\n if (!(await filter(peerId, addr.multiaddr))) {\n continue;\n }\n const isCertified = addr.isCertified ?? false;\n const maStr = addr.multiaddr.toString();\n const existingAddr = addressMap.get(maStr);\n if (existingAddr != null) {\n addr.isCertified = existingAddr.isCertified || isCertified;\n }\n else {\n addressMap.set(maStr, {\n multiaddr: addr.multiaddr,\n isCertified\n });\n }\n }\n return [...addressMap.values()]\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString());\n })\n .map(({ isCertified, multiaddr }) => ({\n isCertified,\n multiaddr: multiaddr.bytes\n }));\n}\n//# sourceMappingURL=dedupe-addresses.js.map","import { CodeError } from '@libp2p/interface';\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals';\nimport { codes } from '../errors.js';\nimport { dedupeFilterAndSortAddresses } from './dedupe-addresses.js';\nexport async function toPeerPB(peerId, data, strategy, options) {\n if (data == null) {\n throw new CodeError('Invalid PeerData', codes.ERR_INVALID_PARAMETERS);\n }\n if (data.publicKey != null && peerId.publicKey != null && !uint8arrayEquals(data.publicKey, peerId.publicKey)) {\n throw new CodeError('publicKey bytes do not match peer id publicKey bytes', codes.ERR_INVALID_PARAMETERS);\n }\n const existingPeer = options.existingPeer;\n if (existingPeer != null && !peerId.equals(existingPeer.id)) {\n throw new CodeError('peer id did not match existing peer id', codes.ERR_INVALID_PARAMETERS);\n }\n let addresses = existingPeer?.addresses ?? [];\n let protocols = new Set(existingPeer?.protocols ?? []);\n let metadata = existingPeer?.metadata ?? new Map();\n let tags = existingPeer?.tags ?? new Map();\n let peerRecordEnvelope = existingPeer?.peerRecordEnvelope;\n // when patching, we replace the original fields with passed values\n if (strategy === 'patch') {\n if (data.multiaddrs != null || data.addresses != null) {\n addresses = [];\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n }\n if (data.protocols != null) {\n protocols = new Set(data.protocols);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n metadata = createSortedMap(metadataEntries, {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n tags = createSortedMap(tagsEntries, {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n // when merging, we join the original fields with passed values\n if (strategy === 'merge') {\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n if (data.protocols != null) {\n protocols = new Set([...protocols, ...data.protocols]);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n for (const [key, value] of metadataEntries) {\n if (value == null) {\n metadata.delete(key);\n }\n else {\n metadata.set(key, value);\n }\n }\n metadata = createSortedMap([...metadata.entries()], {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n const mergedTags = new Map(tags);\n for (const [key, value] of tagsEntries) {\n if (value == null) {\n mergedTags.delete(key);\n }\n else {\n mergedTags.set(key, value);\n }\n }\n tags = createSortedMap([...mergedTags.entries()], {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n const output = {\n addresses: await dedupeFilterAndSortAddresses(peerId, options.addressFilter ?? (async () => true), addresses),\n protocols: [...protocols.values()].sort((a, b) => {\n return a.localeCompare(b);\n }),\n metadata,\n tags,\n publicKey: existingPeer?.id.publicKey ?? data.publicKey ?? peerId.publicKey,\n peerRecordEnvelope\n };\n // Ed25519 and secp256k1 have their public key embedded in them so no need to duplicate it\n if (peerId.type !== 'RSA') {\n delete output.publicKey;\n }\n return output;\n}\n/**\n * In JS maps are ordered by insertion order so create a new map with the\n * keys inserted in alphabetical order.\n */\nfunction createSortedMap(entries, options) {\n const output = new Map();\n for (const [key, value] of entries) {\n if (value == null) {\n continue;\n }\n options.validate(key, value);\n }\n for (const [key, value] of entries.sort(([a], [b]) => {\n return a.localeCompare(b);\n })) {\n if (value != null) {\n output.set(key, options.map?.(key, value) ?? value);\n }\n }\n return output;\n}\nfunction validateMetadata(key, value) {\n if (typeof key !== 'string') {\n throw new CodeError('Metadata key must be a string', codes.ERR_INVALID_PARAMETERS);\n }\n if (!(value instanceof Uint8Array)) {\n throw new CodeError('Metadata value must be a Uint8Array', codes.ERR_INVALID_PARAMETERS);\n }\n}\nfunction validateTag(key, tag) {\n if (typeof key !== 'string') {\n throw new CodeError('Tag name must be a string', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.value != null) {\n if (parseInt(`${tag.value}`, 10) !== tag.value) {\n throw new CodeError('Tag value must be an integer', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.value < 0 || tag.value > 100) {\n throw new CodeError('Tag value must be between 0-100', codes.ERR_INVALID_PARAMETERS);\n }\n }\n if (tag.ttl != null) {\n if (parseInt(`${tag.ttl}`, 10) !== tag.ttl) {\n throw new CodeError('Tag ttl must be an integer', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.ttl < 0) {\n throw new CodeError('Tag ttl must be between greater than 0', codes.ERR_INVALID_PARAMETERS);\n }\n }\n}\nfunction mapTag(key, tag) {\n let expiry;\n if (tag.expiry != null) {\n expiry = tag.expiry;\n }\n if (tag.ttl != null) {\n expiry = BigInt(Date.now() + Number(tag.ttl));\n }\n return {\n value: tag.value ?? 0,\n expiry\n };\n}\n//# sourceMappingURL=to-peer-pb.js.map","import { CodeError } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { peerIdFromBytes } from '@libp2p/peer-id';\nimport mortice, {} from 'mortice';\nimport { base32 } from 'multiformats/bases/base32';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { codes } from './errors.js';\nimport { Peer as PeerPB } from './pb/peer.js';\nimport { bytesToPeer } from './utils/bytes-to-peer.js';\nimport { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js';\nimport { toPeerPB } from './utils/to-peer-pb.js';\nfunction decodePeer(key, value, cache) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2];\n const buf = base32.decode(base32Str);\n const peerId = peerIdFromBytes(buf);\n const cached = cache.get(peerId);\n if (cached != null) {\n return cached;\n }\n const peer = bytesToPeer(peerId, value);\n cache.set(peerId, peer);\n return peer;\n}\nfunction mapQuery(query, cache) {\n if (query == null) {\n return {};\n }\n return {\n prefix: NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, cache));\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache));\n })\n };\n}\nexport class PersistentStore {\n peerId;\n datastore;\n lock;\n addressFilter;\n constructor(components, init = {}) {\n this.peerId = components.peerId;\n this.datastore = components.datastore;\n this.addressFilter = init.addressFilter;\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n });\n }\n async has(peerId) {\n return this.datastore.has(peerIdToDatastoreKey(peerId));\n }\n async delete(peerId) {\n if (this.peerId.equals(peerId)) {\n throw new CodeError('Cannot delete self peer', codes.ERR_INVALID_PARAMETERS);\n }\n await this.datastore.delete(peerIdToDatastoreKey(peerId));\n }\n async load(peerId) {\n const buf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n return bytesToPeer(peerId, buf);\n }\n async save(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async patch(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async merge(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async *all(query) {\n const peerCache = new PeerMap();\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {\n const peer = decodePeer(key, value, peerCache);\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue;\n }\n yield peer;\n }\n }\n async #findExistingPeer(peerId) {\n try {\n const existingBuf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n const existingPeer = bytesToPeer(peerId, existingBuf);\n return {\n existingBuf,\n existingPeer\n };\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n return {};\n }\n async #saveIfDifferent(peerId, peer, existingBuf, existingPeer) {\n const buf = PeerPB.encode(peer);\n if (existingBuf != null && uint8ArrayEquals(buf, existingBuf)) {\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: false\n };\n }\n await this.datastore.put(peerIdToDatastoreKey(peerId), buf);\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: true\n };\n }\n}\n//# sourceMappingURL=store.js.map","/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport all from 'it-all';\nimport { PersistentStore } from './store.js';\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore {\n store;\n events;\n peerId;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.events = components.events;\n this.peerId = components.peerId;\n this.store = new PersistentStore(components, init);\n }\n async forEach(fn, query) {\n this.log.trace('forEach await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('forEach got read lock');\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer);\n }\n }\n finally {\n this.log.trace('forEach release read lock');\n release();\n }\n }\n async all(query) {\n this.log.trace('all await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('all got read lock');\n try {\n return await all(this.store.all(query));\n }\n finally {\n this.log.trace('all release read lock');\n release();\n }\n }\n async delete(peerId) {\n this.log.trace('delete await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('delete got write lock');\n try {\n await this.store.delete(peerId);\n }\n finally {\n this.log.trace('delete release write lock');\n release();\n }\n }\n async has(peerId) {\n this.log.trace('has await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('has got read lock');\n try {\n return await this.store.has(peerId);\n }\n finally {\n this.log.trace('has release read lock');\n release();\n }\n }\n async get(peerId) {\n this.log.trace('get await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('get got read lock');\n try {\n return await this.store.load(peerId);\n }\n finally {\n this.log.trace('get release read lock');\n release();\n }\n }\n async save(id, data) {\n this.log.trace('save await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('save got write lock');\n try {\n const result = await this.store.save(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('save release write lock');\n release();\n }\n }\n async patch(id, data) {\n this.log.trace('patch await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('patch got write lock');\n try {\n const result = await this.store.patch(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('patch release write lock');\n release();\n }\n }\n async merge(id, data) {\n this.log.trace('merge await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('merge got write lock');\n try {\n const result = await this.store.merge(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('merge release write lock');\n release();\n }\n }\n async consumePeerRecord(buf, expectedPeer) {\n const envelope = await RecordEnvelope.openAndCertify(buf, PeerRecord.DOMAIN);\n if (expectedPeer?.equals(envelope.peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, envelope.peerId);\n return false;\n }\n const peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n let peer;\n try {\n peer = await this.get(envelope.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n return false;\n }\n }\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n });\n return true;\n }\n #emitIfUpdated(id, result) {\n if (!result.updated) {\n return;\n }\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result });\n }\n else {\n this.events.safeDispatchEvent('peer:update', { detail: result });\n }\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction drain(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n })();\n }\n else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\nexport default drain;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\nimport peek from 'it-peekable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction filter(source, fn) {\n let index = 0;\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source);\n const { value, done } = peekable.next();\n if (done === true) {\n return (function* () { }());\n }\n const res = fn(value, index++);\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function* () {\n if (await res) {\n yield value;\n }\n for await (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n const func = fn;\n return (function* () {\n if (res === true) {\n yield value;\n }\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry;\n }\n }\n })();\n}\nexport default filter;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\nfunction peekable(iterable) {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator];\n const queue = [];\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next();\n },\n push: (value) => {\n queue.push(value);\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n };\n }\n return iterator.next();\n },\n [symbol]() {\n return this;\n }\n };\n}\nexport default peekable;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\nimport all from 'it-all';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction sort(source, sorter) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n const arr = await all(source);\n yield* arr.sort(sorter);\n })();\n }\n return (function* () {\n const arr = all(source);\n yield* arr.sort(sorter);\n })();\n}\nexport default sort;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction take(source, limit) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for await (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n }\n return (function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n}\nexport default take;\n//# sourceMappingURL=index.js.map","import drain from 'it-drain';\nimport filter from 'it-filter';\nimport sort from 'it-sort';\nimport take from 'it-take';\nexport class BaseDatastore {\n put(key, val, options) {\n return Promise.reject(new Error('.put is not implemented'));\n }\n get(key, options) {\n return Promise.reject(new Error('.get is not implemented'));\n }\n has(key, options) {\n return Promise.reject(new Error('.has is not implemented'));\n }\n delete(key, options) {\n return Promise.reject(new Error('.delete is not implemented'));\n }\n async *putMany(source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options);\n yield key;\n }\n }\n async *getMany(source, options = {}) {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n };\n }\n }\n async *deleteMany(source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options);\n yield key;\n }\n }\n batch() {\n let puts = [];\n let dels = [];\n return {\n put(key, value) {\n puts.push({ key, value });\n },\n delete(key) {\n dels.push(key);\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options));\n puts = [];\n await drain(this.deleteMany(dels, options));\n dels = [];\n }\n };\n }\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_all(q, options) {\n throw new Error('._all is not implemented');\n }\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_allKeys(q, options) {\n throw new Error('._allKeys is not implemented');\n }\n query(q, options) {\n let it = this._all(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (e) => e.key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n let i = 0;\n const offset = q.offset;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n queryKeys(q, options) {\n let it = this._allKeys(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (key) => key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n const offset = q.offset;\n let i = 0;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n}\n//# sourceMappingURL=base.js.map","import { Key } from 'interface-datastore/key';\nimport { BaseDatastore } from './base.js';\nimport * as Errors from './errors.js';\nexport class MemoryDatastore extends BaseDatastore {\n data;\n constructor() {\n super();\n this.data = new Map();\n }\n put(key, val) {\n this.data.set(key.toString(), val);\n return key;\n }\n get(key) {\n const result = this.data.get(key.toString());\n if (result == null) {\n throw Errors.notFoundError();\n }\n return result;\n }\n has(key) {\n return this.data.has(key.toString());\n }\n delete(key) {\n this.data.delete(key.toString());\n }\n *_all() {\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value };\n }\n }\n *_allKeys() {\n for (const key of this.data.keys()) {\n yield new Key(key);\n }\n }\n}\n//# sourceMappingURL=memory.js.map","import errCode from 'err-code';\nexport function dbOpenFailedError(err) {\n err = err ?? new Error('Cannot open database');\n return errCode(err, 'ERR_DB_OPEN_FAILED');\n}\nexport function dbDeleteFailedError(err) {\n err = err ?? new Error('Delete failed');\n return errCode(err, 'ERR_DB_DELETE_FAILED');\n}\nexport function dbWriteFailedError(err) {\n err = err ?? new Error('Write failed');\n return errCode(err, 'ERR_DB_WRITE_FAILED');\n}\nexport function dbReadFailedError(err) {\n err = err ?? new Error('Read failed');\n return errCode(err, 'ERR_DB_READ_FAILED');\n}\nexport function notFoundError(err) {\n err = err ?? new Error('Not Found');\n return errCode(err, 'ERR_NOT_FOUND');\n}\nexport function abortedError(err) {\n err = err ?? new Error('Aborted');\n return errCode(err, 'ERR_ABORTED');\n}\n//# sourceMappingURL=errors.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { debounce } from './utils.js';\nconst defaultAddressFilter = (addrs) => addrs;\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId(ma, peerId) {\n const observedPeerIdStr = ma.getPeerId();\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = peerIdFromString(observedPeerIdStr);\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId.toString()}`));\n }\n }\n return ma;\n}\nexport class DefaultAddressManager {\n log;\n components;\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n listen;\n announce;\n observed;\n announceFilter;\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor(components, init = {}) {\n const { listen = [], announce = [] } = init;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:address-manager');\n this.listen = listen.map(ma => ma.toString());\n this.announce = new Set(announce.map(ma => ma.toString()));\n this.observed = new Map();\n this.announceFilter = init.announceFilter ?? defaultAddressFilter;\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = debounce(this._updatePeerStoreAddresses.bind(this), 1000);\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses();\n });\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses();\n });\n }\n _updatePeerStoreAddresses() {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat([...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => multiaddr(str))).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`);\n }\n return ma;\n });\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err); });\n }\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs() {\n return Array.from(this.listen).map((a) => multiaddr(a));\n }\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs() {\n return Array.from(this.announce).map((a) => multiaddr(a));\n }\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs() {\n return Array.from(this.observed).map(([a]) => multiaddr(a));\n }\n /**\n * Add peer observed addresses\n */\n addObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return;\n }\n this.observed.set(addrString, {\n confident: false\n });\n }\n confirmObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n };\n const startingConfidence = metadata.confident;\n this.observed.set(addrString, {\n confident: true\n });\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses();\n }\n }\n removeObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n this.observed.delete(addrString);\n }\n getAddresses() {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString());\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString());\n }\n // add observed addresses we are confident in\n addrs = addrs.concat(Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma));\n // dedupe multiaddrs\n const addrSet = new Set(addrs);\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => multiaddr(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma;\n }\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma;\n }\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`);\n });\n }\n}\n//# sourceMappingURL=index.js.map","export function debounce(func, wait) {\n let timeout;\n return function () {\n const later = function () {\n timeout = undefined;\n func();\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n}\n//# sourceMappingURL=utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { isStartable } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nclass DefaultComponents {\n components = {};\n _started = false;\n constructor(init = {}) {\n this.components = {};\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value;\n }\n if (this.components.logger == null) {\n this.components.logger = defaultLogger();\n }\n }\n isStarted() {\n return this._started;\n }\n async _invokeStartableMethod(methodName) {\n await Promise.all(Object.values(this.components)\n .filter(obj => isStartable(obj))\n .map(async (startable) => {\n await startable[methodName]?.();\n }));\n }\n async beforeStart() {\n await this._invokeStartableMethod('beforeStart');\n }\n async start() {\n await this._invokeStartableMethod('start');\n this._started = true;\n }\n async afterStart() {\n await this._invokeStartableMethod('afterStart');\n }\n async beforeStop() {\n await this._invokeStartableMethod('beforeStop');\n }\n async stop() {\n await this._invokeStartableMethod('stop');\n this._started = false;\n }\n async afterStop() {\n await this._invokeStartableMethod('afterStop');\n }\n}\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n];\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n];\nexport function defaultComponents(init = {}) {\n const components = new DefaultComponents(init);\n const proxy = new Proxy(components, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop];\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new CodeError(`${prop} not set`, 'ERR_SERVICE_MISSING');\n }\n return service;\n }\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value;\n }\n else {\n Reflect.set(target, prop, value);\n }\n return true;\n }\n });\n // @ts-expect-error component keys are proxied\n return proxy;\n}\n//# sourceMappingURL=components.js.map","export function isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nexport async function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nexport async function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { Netmask } from 'netmask';\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n];\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new Netmask(ipRange));\nfunction ipv4Check(ipAddr) {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr))\n return true;\n }\n return false;\n}\nfunction ipv6Check(ipAddr) {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr);\n}\nexport function isPrivateIp(ip) {\n if (isIPv4(ip))\n return ipv4Check(ip);\n else if (isIPv6(ip))\n return ipv6Check(ip);\n else\n return undefined;\n}\n//# sourceMappingURL=private-ip.js.map","import { isPrivateIp } from '@libp2p/utils/private-ip';\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nexport function connectionGater(gater = {}) {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr) => {\n const tuples = multiaddr.stringTuples();\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean(isPrivateIp(`${tuples[0][1]}`));\n }\n return false;\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n };\n}\n//# sourceMappingURL=connection-gater.browser.js.map","import { isPrivateIp } from '../private-ip.js';\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate(ma) {\n try {\n const { address } = ma.nodeAddress();\n return Boolean(isPrivateIp(address));\n }\n catch {\n return true;\n }\n}\n//# sourceMappingURL=is-private.js.map","/**\n * @packageDocumentation\n *\n * Provides strategies to sort a list of multiaddrs.\n *\n * @example\n *\n * ```typescript\n * import { publicAddressesFirst } from '@libp2p/utils/address-sort'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n *\n * const addresses = [\n * multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * multiaddr('/ip4/82.41.53.1/tcp/9000')\n * ].sort(publicAddressesFirst)\n *\n * console.info(addresses)\n * // ['/ip4/82.41.53.1/tcp/9000', '/ip4/127.0.0.1/tcp/9000']\n * ```\n */\nimport { Circuit } from '@multiformats/multiaddr-matcher';\nimport { isPrivate } from './multiaddr/is-private.js';\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nexport function publicAddressesFirst(a, b) {\n const isAPrivate = isPrivate(a.multiaddr);\n const isBPrivate = isPrivate(b.multiaddr);\n if (isAPrivate && !isBPrivate) {\n return 1;\n }\n else if (!isAPrivate && isBPrivate) {\n return -1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nexport function certifiedAddressesFirst(a, b) {\n if (a.isCertified && !b.isCertified) {\n return -1;\n }\n else if (!a.isCertified && b.isCertified) {\n return 1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * start of the array.\n */\nexport function circuitRelayAddressesLast(a, b) {\n const isACircuit = Circuit.exactMatch(a.multiaddr);\n const isBCircuit = Circuit.exactMatch(b.multiaddr);\n if (isACircuit && !isBCircuit) {\n return 1;\n }\n else if (!isACircuit && isBCircuit) {\n return -1;\n }\n return 0;\n}\nexport function defaultAddressSort(a, b) {\n const publicResult = publicAddressesFirst(a, b);\n if (publicResult !== 0) {\n return publicResult;\n }\n const relayResult = circuitRelayAddressesLast(a, b);\n if (relayResult !== 0) {\n return relayResult;\n }\n const certifiedResult = certifiedAddressesFirst(a, b);\n return certifiedResult;\n}\n//# sourceMappingURL=address-sort.js.map","/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent extends Event {\n constructor(type, detail) {\n super(type);\n this.detail = detail;\n }\n}\n//# sourceMappingURL=index.js.map","import { RecordType } from '../index.js';\nexport function getTypes(types) {\n const DEFAULT_TYPES = [\n RecordType.A\n ];\n if (types == null) {\n return DEFAULT_TYPES;\n }\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES;\n }\n return types;\n }\n return [\n types\n ];\n}\n//# sourceMappingURL=get-types.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RecordType } from '../index.js';\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60;\nexport function toDNSResponse(obj) {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n };\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n };\n })\n };\n}\n//# sourceMappingURL=to-dns-response.js.map","/* eslint-env browser */\nimport PQueue from 'p-queue';\nimport { CustomProgressEvent } from 'progress-events';\nimport { RecordType } from '../index.js';\nimport { getTypes } from '../utils/get-types.js';\nimport { toDNSResponse } from '../utils/to-dns-response.js';\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4;\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps(url, init = {}) {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n });\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams();\n searchParams.set('name', fqdn);\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type]);\n });\n options.onProgress?.(new CustomProgressEvent('dns:query', { detail: fqdn }));\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`);\n }\n const response = toDNSResponse(await res.json());\n options.onProgress?.(new CustomProgressEvent('dns:response', { detail: response }));\n return response;\n }, {\n signal: options.signal\n });\n if (response == null) {\n throw new Error('No DNS response received');\n }\n return response;\n };\n}\n//# sourceMappingURL=dns-json-over-https.js.map","/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\nimport { DNS as DNSClass } from './dns.js';\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport var RecordType;\n(function (RecordType) {\n RecordType[RecordType[\"A\"] = 1] = \"A\";\n RecordType[RecordType[\"CNAME\"] = 5] = \"CNAME\";\n RecordType[RecordType[\"TXT\"] = 16] = \"TXT\";\n RecordType[RecordType[\"AAAA\"] = 28] = \"AAAA\";\n})(RecordType || (RecordType = {}));\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32;\nexport function dns(init = {}) {\n return new DNSClass(init);\n}\n//# sourceMappingURL=index.js.map","import hashlru from 'hashlru';\nimport { RecordType } from '../index.js';\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js';\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n lru;\n constructor(maxSize) {\n this.lru = hashlru(maxSize);\n }\n get(fqdn, types) {\n let foundAllAnswers = true;\n const answers = [];\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type);\n if (cached.length === 0) {\n foundAllAnswers = false;\n break;\n }\n answers.push(...cached);\n }\n if (foundAllAnswers) {\n return toDNSResponse({ answers });\n }\n }\n getAnswers(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n const answers = this.lru.get(key);\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now();\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }));\n if (cachedAnswers.length === 0) {\n this.lru.remove(key);\n }\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers;\n }\n return [];\n }\n add(domain, answer) {\n const key = `${domain.toLowerCase()}-${answer.type}`;\n const answers = this.lru.get(key) ?? [];\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n });\n this.lru.set(key, answers);\n }\n remove(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n this.lru.remove(key);\n }\n clear() {\n this.lru.clear();\n }\n}\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache(size) {\n return new CachedAnswers(size);\n}\n//# sourceMappingURL=cache.js.map","import { CustomProgressEvent } from 'progress-events';\nimport { defaultResolver } from './resolvers/default.js';\nimport { cache } from './utils/cache.js';\nimport { getTypes } from './utils/get-types.js';\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000;\nexport class DNS {\n resolvers;\n cache;\n constructor(init) {\n this.resolvers = {};\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE);\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver];\n }\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`;\n }\n this.resolvers[tld] = resolver;\n });\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver();\n }\n }\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query(domain, options = {}) {\n const types = getTypes(options.types);\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined;\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent('dns:cache', { detail: cached }));\n return cached;\n }\n const tld = `${domain.split('.').pop()}.`;\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1;\n });\n const errors = [];\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break;\n }\n try {\n const result = await resolver(domain, {\n ...options,\n types\n });\n for (const answer of result.Answer) {\n this.cache.add(domain, answer);\n }\n return result;\n }\n catch (err) {\n errors.push(err);\n options.onProgress?.(new CustomProgressEvent('dns:error', { detail: err }));\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateError(errors, `DNS lookup of ${domain} ${types} failed`);\n }\n}\n//# sourceMappingURL=dns.js.map","import { dnsJsonOverHttps } from './dns-json-over-https.js';\nexport function defaultResolver() {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ];\n}\n//# sourceMappingURL=default.browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { dns, RecordType } from '@multiformats/dns';\nimport { multiaddr } from '../index.js';\nimport { getProtocol } from '../protocols-table.js';\nconst MAX_RECURSIVE_DEPTH = 32;\nconst { code: dnsaddrCode } = getProtocol('dnsaddr');\nexport const dnsaddrResolver = async function dnsaddrResolver(ma, options = {}) {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH;\n if (recursionLimit === 0) {\n throw new CodeError('Max recursive depth reached', 'ERR_MAX_RECURSIVE_DEPTH_REACHED');\n }\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? [];\n const resolver = options?.dns ?? dns();\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n RecordType.TXT\n ]\n });\n const peerId = ma.getPeerId();\n const output = [];\n for (const answer of result.Answer) {\n const addr = answer.data\n .replace(/[\"']/g, '')\n .trim()\n .split('=')[1];\n if (addr == null) {\n continue;\n }\n if (peerId != null && !addr.includes(peerId)) {\n continue;\n }\n const ma = multiaddr(addr);\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n });\n output.push(...resolved.map(ma => ma.toString()));\n }\n else {\n output.push(ma.toString());\n }\n }\n return output;\n};\n//# sourceMappingURL=dnsaddr.js.map","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","export var messages;\n(function (messages) {\n messages[\"NOT_STARTED_YET\"] = \"The libp2p node is not started yet\";\n messages[\"ERR_PROTECTOR_REQUIRED\"] = \"Private network is enforced, but no protector was provided\";\n messages[\"NOT_FOUND\"] = \"Not found\";\n})(messages || (messages = {}));\nexport var codes;\n(function (codes) {\n codes[\"ERR_PROTECTOR_REQUIRED\"] = \"ERR_PROTECTOR_REQUIRED\";\n codes[\"ERR_PEER_DIAL_INTERCEPTED\"] = \"ERR_PEER_DIAL_INTERCEPTED\";\n codes[\"ERR_CONNECTION_INTERCEPTED\"] = \"ERR_CONNECTION_INTERCEPTED\";\n codes[\"ERR_INVALID_PROTOCOLS_FOR_STREAM\"] = \"ERR_INVALID_PROTOCOLS_FOR_STREAM\";\n codes[\"ERR_CONNECTION_ENDED\"] = \"ERR_CONNECTION_ENDED\";\n codes[\"ERR_CONNECTION_FAILED\"] = \"ERR_CONNECTION_FAILED\";\n codes[\"ERR_NODE_NOT_STARTED\"] = \"ERR_NODE_NOT_STARTED\";\n codes[\"ERR_ALREADY_ABORTED\"] = \"ERR_ALREADY_ABORTED\";\n codes[\"ERR_TOO_MANY_ADDRESSES\"] = \"ERR_TOO_MANY_ADDRESSES\";\n codes[\"ERR_NO_VALID_ADDRESSES\"] = \"ERR_NO_VALID_ADDRESSES\";\n codes[\"ERR_RELAYED_DIAL\"] = \"ERR_RELAYED_DIAL\";\n codes[\"ERR_DIALED_SELF\"] = \"ERR_DIALED_SELF\";\n codes[\"ERR_DISCOVERED_SELF\"] = \"ERR_DISCOVERED_SELF\";\n codes[\"ERR_DUPLICATE_TRANSPORT\"] = \"ERR_DUPLICATE_TRANSPORT\";\n codes[\"ERR_ENCRYPTION_FAILED\"] = \"ERR_ENCRYPTION_FAILED\";\n codes[\"ERR_HOP_REQUEST_FAILED\"] = \"ERR_HOP_REQUEST_FAILED\";\n codes[\"ERR_INVALID_KEY\"] = \"ERR_INVALID_KEY\";\n codes[\"ERR_INVALID_MESSAGE\"] = \"ERR_INVALID_MESSAGE\";\n codes[\"ERR_INVALID_PARAMETERS\"] = \"ERR_INVALID_PARAMETERS\";\n codes[\"ERR_INVALID_PEER\"] = \"ERR_INVALID_PEER\";\n codes[\"ERR_MUXER_UNAVAILABLE\"] = \"ERR_MUXER_UNAVAILABLE\";\n codes[\"ERR_NOT_FOUND\"] = \"ERR_NOT_FOUND\";\n codes[\"ERR_TRANSPORT_UNAVAILABLE\"] = \"ERR_TRANSPORT_UNAVAILABLE\";\n codes[\"ERR_TRANSPORT_DIAL_FAILED\"] = \"ERR_TRANSPORT_DIAL_FAILED\";\n codes[\"ERR_UNSUPPORTED_PROTOCOL\"] = \"ERR_UNSUPPORTED_PROTOCOL\";\n codes[\"ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED\"] = \"ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED\";\n codes[\"ERR_INVALID_MULTIADDR\"] = \"ERR_INVALID_MULTIADDR\";\n codes[\"ERR_SIGNATURE_NOT_VALID\"] = \"ERR_SIGNATURE_NOT_VALID\";\n codes[\"ERR_FIND_SELF\"] = \"ERR_FIND_SELF\";\n codes[\"ERR_NO_ROUTERS_AVAILABLE\"] = \"ERR_NO_ROUTERS_AVAILABLE\";\n codes[\"ERR_CONNECTION_NOT_MULTIPLEXED\"] = \"ERR_CONNECTION_NOT_MULTIPLEXED\";\n codes[\"ERR_NO_DIAL_TOKENS\"] = \"ERR_NO_DIAL_TOKENS\";\n codes[\"ERR_INVALID_CMS\"] = \"ERR_INVALID_CMS\";\n codes[\"ERR_MISSING_KEYS\"] = \"ERR_MISSING_KEYS\";\n codes[\"ERR_NO_KEY\"] = \"ERR_NO_KEY\";\n codes[\"ERR_INVALID_KEY_NAME\"] = \"ERR_INVALID_KEY_NAME\";\n codes[\"ERR_INVALID_KEY_TYPE\"] = \"ERR_INVALID_KEY_TYPE\";\n codes[\"ERR_KEY_ALREADY_EXISTS\"] = \"ERR_KEY_ALREADY_EXISTS\";\n codes[\"ERR_INVALID_KEY_SIZE\"] = \"ERR_INVALID_KEY_SIZE\";\n codes[\"ERR_KEY_NOT_FOUND\"] = \"ERR_KEY_NOT_FOUND\";\n codes[\"ERR_OLD_KEY_NAME_INVALID\"] = \"ERR_OLD_KEY_NAME_INVALID\";\n codes[\"ERR_NEW_KEY_NAME_INVALID\"] = \"ERR_NEW_KEY_NAME_INVALID\";\n codes[\"ERR_PASSWORD_REQUIRED\"] = \"ERR_PASSWORD_REQUIRED\";\n codes[\"ERR_PEM_REQUIRED\"] = \"ERR_PEM_REQUIRED\";\n codes[\"ERR_CANNOT_READ_KEY\"] = \"ERR_CANNOT_READ_KEY\";\n codes[\"ERR_MISSING_PRIVATE_KEY\"] = \"ERR_MISSING_PRIVATE_KEY\";\n codes[\"ERR_MISSING_PUBLIC_KEY\"] = \"ERR_MISSING_PUBLIC_KEY\";\n codes[\"ERR_INVALID_OLD_PASS_TYPE\"] = \"ERR_INVALID_OLD_PASS_TYPE\";\n codes[\"ERR_INVALID_NEW_PASS_TYPE\"] = \"ERR_INVALID_NEW_PASS_TYPE\";\n codes[\"ERR_INVALID_PASS_LENGTH\"] = \"ERR_INVALID_PASS_LENGTH\";\n codes[\"ERR_NOT_IMPLEMENTED\"] = \"ERR_NOT_IMPLEMENTED\";\n codes[\"ERR_WRONG_PING_ACK\"] = \"ERR_WRONG_PING_ACK\";\n codes[\"ERR_INVALID_RECORD\"] = \"ERR_INVALID_RECORD\";\n codes[\"ERR_ALREADY_SUCCEEDED\"] = \"ERR_ALREADY_SUCCEEDED\";\n codes[\"ERR_NO_HANDLER_FOR_PROTOCOL\"] = \"ERR_NO_HANDLER_FOR_PROTOCOL\";\n codes[\"ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS\"] = \"ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS\";\n codes[\"ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS\"] = \"ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS\";\n codes[\"ERR_CONNECTION_DENIED\"] = \"ERR_CONNECTION_DENIED\";\n codes[\"ERR_TRANSFER_LIMIT_EXCEEDED\"] = \"ERR_TRANSFER_LIMIT_EXCEEDED\";\n})(codes || (codes = {}));\n//# sourceMappingURL=errors.js.map","import { CodeError, FaultTolerance } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport mergeOptions from 'merge-options';\nimport { codes, messages } from './errors.js';\nconst DefaultConfig = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: defaultAddressSort\n },\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n }\n};\nexport async function validateConfig(opts) {\n const resultingOptions = mergeOptions(DefaultConfig, opts);\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED);\n }\n if (!(await peerIdFromKeys(resultingOptions.privateKey.public.bytes, resultingOptions.privateKey.bytes)).equals(resultingOptions.peerId)) {\n throw new CodeError('Private key doesn\\'t match peer id', codes.ERR_INVALID_KEY);\n }\n return resultingOptions;\n}\n//# sourceMappingURL=config.js.map","import { CodeError, isPeerId } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { isMultiaddr } from '@multiformats/multiaddr';\nimport { codes } from './errors.js';\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nexport function getPeerAddress(peer) {\n if (isPeerId(peer)) {\n return { peerId: peer, multiaddrs: [] };\n }\n if (!Array.isArray(peer)) {\n peer = [peer];\n }\n let peerId;\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId();\n peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr);\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!isMultiaddr(ma)) {\n throw new CodeError('Invalid Multiaddr', codes.ERR_INVALID_MULTIADDR);\n }\n const maPeerIdStr = ma.getPeerId();\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS);\n }\n }\n else {\n const maPeerId = peerIdFromString(maPeerIdStr);\n if (peerId == null || !peerId.equals(maPeerId)) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS);\n }\n }\n });\n }\n return {\n peerId,\n multiaddrs: peer\n };\n}\n//# sourceMappingURL=get-peer.js.map","/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent(emitter, eventName, signal, opts) {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n if (signal?.aborted === true) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n function removeListeners() {\n signal?.removeEventListener('abort', abortListener);\n emitter.removeEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.removeEventListener(opts.errorEvent, errorEventListener);\n }\n }\n const eventListener = (evt) => {\n try {\n if (opts?.filter?.(evt) === false) {\n return;\n }\n }\n catch (err) {\n removeListeners();\n reject(err);\n return;\n }\n removeListeners();\n resolve(evt);\n };\n const errorEventListener = (evt) => {\n removeListeners();\n reject(evt.detail);\n };\n const abortListener = () => {\n removeListeners();\n reject(error);\n };\n signal?.addEventListener('abort', abortListener);\n emitter.addEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.addEventListener(opts.errorEvent, errorEventListener);\n }\n });\n}\n//# sourceMappingURL=index.js.map","import { AbortError } from '@libp2p/interface';\nimport pDefer from 'p-defer';\nexport class JobRecipient {\n deferred;\n signal;\n where;\n constructor(where, signal) {\n this.signal = signal;\n this.deferred = pDefer();\n this.where = where;\n this.onAbort = this.onAbort.bind(this);\n this.signal?.addEventListener('abort', this.onAbort);\n }\n onAbort() {\n this.deferred.reject(this.signal?.reason ?? new AbortError());\n }\n cleanup() {\n this.signal?.removeEventListener('abort', this.onAbort);\n }\n}\n//# sourceMappingURL=recipient.js.map","import { AbortError, setMaxListeners } from '@libp2p/interface';\nimport { raceSignal } from 'race-signal';\nimport { JobRecipient } from './recipient.js';\n/**\n * Returns a random string\n */\nfunction randomId() {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`;\n}\nexport class Job {\n id;\n fn;\n options;\n recipients;\n status;\n timeline;\n controller;\n constructor(fn, options) {\n this.id = randomId();\n this.status = 'queued';\n this.fn = fn;\n this.options = options;\n this.recipients = [];\n this.timeline = {\n created: Date.now()\n };\n this.controller = new AbortController();\n setMaxListeners(Infinity, this.controller.signal);\n this.onAbort = this.onAbort.bind(this);\n }\n abort(err) {\n this.controller.abort(err);\n }\n onAbort() {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true);\n }, true);\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError());\n this.cleanup();\n }\n }\n async join(options = {}) {\n const recipient = new JobRecipient((new Error('where')).stack, options.signal);\n this.recipients.push(recipient);\n options.signal?.addEventListener('abort', this.onAbort);\n return recipient.deferred.promise;\n }\n async run() {\n this.status = 'running';\n this.timeline.started = Date.now();\n try {\n this.controller.signal.throwIfAborted();\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal);\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result);\n });\n this.status = 'complete';\n }\n catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err);\n });\n this.status = 'errored';\n }\n finally {\n this.timeline.finished = Date.now();\n this.cleanup();\n }\n }\n cleanup() {\n this.recipients.forEach(recipient => {\n recipient.cleanup();\n recipient.signal?.removeEventListener('abort', this.onAbort);\n });\n }\n}\n//# sourceMappingURL=job.js.map","import { AbortError, CodeError, TypedEventEmitter } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport { raceEvent } from 'race-event';\nimport { Job } from './job.js';\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue extends TypedEventEmitter {\n concurrency;\n queue;\n pending;\n sort;\n constructor(init = {}) {\n super();\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY;\n this.pending = 0;\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n };\n }\n });\n }\n this.sort = init.sort;\n this.queue = [];\n }\n tryToStartAnother() {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty');\n });\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle');\n });\n }\n return false;\n }\n if (this.pending < this.concurrency) {\n let job;\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j;\n break;\n }\n }\n if (job == null) {\n return false;\n }\n this.safeDispatchEvent('active');\n this.pending++;\n job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n this.pending--;\n this.tryToStartAnother();\n this.safeDispatchEvent('next');\n });\n return true;\n }\n return false;\n }\n enqueue(job) {\n this.queue.push(job);\n if (this.sort != null) {\n this.queue.sort(this.sort);\n }\n }\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options) {\n options?.signal?.throwIfAborted();\n const job = new Job(fn, options);\n this.enqueue(job);\n this.safeDispatchEvent('add');\n this.tryToStartAnother();\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result });\n this.safeDispatchEvent('success', { detail: { job, result } });\n return result;\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n }\n this.safeDispatchEvent('error', { detail: err });\n this.safeDispatchEvent('failure', { detail: { job, error: err } });\n throw err;\n });\n }\n /**\n * Clear the queue\n */\n clear() {\n this.queue.splice(0, this.queue.length);\n }\n /**\n * Abort all jobs in the queue and clear it\n */\n abort() {\n this.queue.forEach(job => {\n job.abort(new AbortError());\n });\n this.clear();\n }\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty(options) {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return;\n }\n await raceEvent(this, 'empty', options?.signal);\n }\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan(limit, options) {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return;\n }\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n });\n }\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle(options) {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return;\n }\n await raceEvent(this, 'idle', options?.signal);\n }\n /**\n * Size of the queue including running items\n */\n get size() {\n return this.queue.length;\n }\n /**\n * The number of queued items waiting to run.\n */\n get queued() {\n return this.queue.length - this.pending;\n }\n /**\n * The number of items currently running.\n */\n get running() {\n return this.pending;\n }\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async *toGenerator(options) {\n options?.signal?.throwIfAborted();\n const stream = pushable({\n objectMode: true\n });\n const cleanup = (err) => {\n if (err != null) {\n this.abort();\n }\n else {\n this.clear();\n }\n stream.end(err);\n };\n const onQueueJobComplete = (evt) => {\n if (evt.detail != null) {\n stream.push(evt.detail);\n }\n };\n const onQueueError = (evt) => {\n cleanup(evt.detail);\n };\n const onQueueIdle = () => {\n cleanup();\n };\n // clear the queue and throw if the query is aborted\n const onSignalAbort = () => {\n cleanup(new CodeError('Queue aborted', 'ERR_QUEUE_ABORTED'));\n };\n // add listeners\n this.addEventListener('completed', onQueueJobComplete);\n this.addEventListener('error', onQueueError);\n this.addEventListener('idle', onQueueIdle);\n options?.signal?.addEventListener('abort', onSignalAbort);\n try {\n yield* stream;\n }\n finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete);\n this.removeEventListener('error', onQueueError);\n this.removeEventListener('idle', onQueueIdle);\n options?.signal?.removeEventListener('abort', onSignalAbort);\n // empty the queue for when the user has broken out of a loop early\n cleanup();\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { Queue } from './queue/index.js';\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue extends Queue {\n has(peerId) {\n return this.find(peerId) != null;\n }\n find(peerId) {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId);\n });\n }\n}\n//# sourceMappingURL=peer-queue.js.map","export * from './constants.defaults.js';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#minConnections\n */\nexport const MIN_CONNECTIONS = 5;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections\n */\nexport const MAX_CONNECTIONS = 100;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials\n */\nexport const MAX_PARALLEL_DIALS = 50;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialPeerRetryThreshold\n */\nexport const AUTO_DIAL_PEER_RETRY_THRESHOLD = 1000 * 60 * 7;\n//# sourceMappingURL=constants.browser.js.map","/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#dialTimeout\n */\nexport const DIAL_TIMEOUT = 5e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundUpgradeTimeout\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 2e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxPeerAddrsToDial\n */\nexport const MAX_PEER_ADDRS_TO_DIAL = 25;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialInterval\n */\nexport const AUTO_DIAL_INTERVAL = 5000;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialConcurrency\n */\nexport const AUTO_DIAL_CONCURRENCY = 25;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialPriority\n */\nexport const AUTO_DIAL_PRIORITY = 0;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialMaxQueueLength\n */\nexport const AUTO_DIAL_MAX_QUEUE_LENGTH = 100;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialDiscoveredPeersDebounce\n */\nexport const AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE = 10;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold\n */\nexport const INBOUND_CONNECTION_THRESHOLD = 5;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxIncomingPendingConnections\n */\nexport const MAX_INCOMING_PENDING_CONNECTIONS = 10;\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempted failed with the relevant\n * peer stored as a string.\n *\n * Used to insure we do not endlessly try to auto dial peers we have recently\n * failed to dial.\n */\nexport const LAST_DIAL_FAILURE_KEY = 'last-dial-failure';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength\n */\nexport const MAX_DIAL_QUEUE_LENGTH = 500;\n//# sourceMappingURL=constants.defaults.js.map","import { PeerMap, PeerSet } from '@libp2p/peer-collections';\nimport { PeerQueue } from '@libp2p/utils/peer-queue';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_INTERVAL, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, LAST_DIAL_FAILURE_KEY, MIN_CONNECTIONS } from './constants.js';\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialInterval: AUTO_DIAL_INTERVAL,\n autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\nexport class AutoDial {\n connectionManager;\n peerStore;\n queue;\n minConnections;\n autoDialPriority;\n autoDialIntervalMs;\n autoDialMaxQueueLength;\n autoDialPeerRetryThresholdMs;\n autoDialDiscoveredPeersDebounce;\n autoDialInterval;\n started;\n running;\n log;\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on whether we know their keys and protocols.\n */\n constructor(components, init) {\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.minConnections = init.minConnections ?? defaultOptions.minConnections;\n this.autoDialPriority = init.autoDialPriority ?? defaultOptions.autoDialPriority;\n this.autoDialIntervalMs = init.autoDialInterval ?? defaultOptions.autoDialInterval;\n this.autoDialMaxQueueLength = init.maxQueueLength ?? defaultOptions.maxQueueLength;\n this.autoDialPeerRetryThresholdMs = init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold;\n this.autoDialDiscoveredPeersDebounce = init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce;\n this.log = components.logger.forComponent('libp2p:connection-manager:auto-dial');\n this.started = false;\n this.running = false;\n this.queue = new PeerQueue({\n concurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n metricName: 'libp2p_autodial_queue',\n metrics: components.metrics\n });\n this.queue.addEventListener('error', (evt) => {\n this.log.error('error during auto-dial', evt.detail);\n });\n // check the min connection limit whenever a peer disconnects\n components.events.addEventListener('connection:close', () => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n });\n // sometimes peers are discovered in quick succession so add a small\n // debounce to ensure all eligible peers are autodialed\n let debounce;\n // when new peers are discovered, dial them if we don't have\n // enough connections\n components.events.addEventListener('peer:discovery', () => {\n clearTimeout(debounce);\n debounce = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n }, this.autoDialDiscoveredPeersDebounce);\n });\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n afterStart() {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }\n stop() {\n // clear the queue\n this.queue.clear();\n clearTimeout(this.autoDialInterval);\n this.started = false;\n this.running = false;\n }\n async autoDial() {\n if (!this.started || this.running) {\n return;\n }\n const connections = this.connectionManager.getConnectionsMap();\n const numConnections = connections.size;\n // already have enough connections\n if (numConnections >= this.minConnections) {\n if (this.minConnections > 0) {\n this.log.trace('have enough connections %d/%d', numConnections, this.minConnections);\n }\n // no need to schedule next autodial as it will be run when on\n // connection:close event\n return;\n }\n if (this.queue.size > this.autoDialMaxQueueLength) {\n this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections);\n this.sheduleNextAutodial();\n return;\n }\n this.running = true;\n this.log('not enough connections %d/%d - will dial peers to increase the number of connections', numConnections, this.minConnections);\n const dialQueue = new PeerSet(\n // @ts-expect-error boolean filter removes falsy peer IDs\n this.connectionManager.getDialQueue()\n .map(queue => queue.peerId)\n .filter(Boolean));\n // sort peers on whether we know protocols or public keys for them\n const peers = await this.peerStore.all({\n filters: [\n // remove some peers\n (peer) => {\n // remove peers without addresses\n if (peer.addresses.length === 0) {\n this.log.trace('not autodialing %p because they have no addresses', peer.id);\n return false;\n }\n // remove peers we are already connected to\n if (connections.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already connected', peer.id);\n return false;\n }\n // remove peers we are already dialling\n if (dialQueue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being dialed', peer.id);\n return false;\n }\n // remove peers already in the autodial queue\n if (this.queue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being autodialed', peer.id);\n return false;\n }\n return true;\n }\n ]\n });\n // shuffle the peers - this is so peers with the same tag values will be\n // dialled in a different order each time\n const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1);\n // sort shuffled peers by tag value\n const peerValues = new PeerMap();\n for (const peer of shuffledPeers) {\n if (peerValues.has(peer.id)) {\n continue;\n }\n // sum all tag values\n peerValues.set(peer.id, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n // sort by value, highest to lowest\n const sortedPeers = shuffledPeers.sort((a, b) => {\n const peerAValue = peerValues.get(a.id) ?? 0;\n const peerBValue = peerValues.get(b.id) ?? 0;\n if (peerAValue > peerBValue) {\n return -1;\n }\n if (peerAValue < peerBValue) {\n return 1;\n }\n return 0;\n });\n const peersThatHaveNotFailed = sortedPeers.filter(peer => {\n const lastDialFailure = peer.metadata.get(LAST_DIAL_FAILURE_KEY);\n if (lastDialFailure == null) {\n return true;\n }\n const lastDialFailureTimestamp = parseInt(uint8ArrayToString(lastDialFailure));\n if (isNaN(lastDialFailureTimestamp)) {\n return true;\n }\n // only dial if the time since the last failure is above the retry threshold\n return Date.now() - lastDialFailureTimestamp > this.autoDialPeerRetryThresholdMs;\n });\n this.log('selected %d/%d peers to dial', peersThatHaveNotFailed.length, peers.length);\n for (const peer of peersThatHaveNotFailed) {\n this.queue.add(async () => {\n const numConnections = this.connectionManager.getConnectionsMap().size;\n // Check to see if we still need to auto dial\n if (numConnections >= this.minConnections) {\n this.log('got enough connections now %d/%d', numConnections, this.minConnections);\n this.queue.clear();\n return;\n }\n this.log('connecting to a peerStore stored peer %p', peer.id);\n await this.connectionManager.openConnection(peer.id, {\n priority: this.autoDialPriority\n });\n }, {\n peerId: peer.id\n }).catch(err => {\n this.log.error('could not connect to peerStore stored peer', err);\n });\n }\n this.running = false;\n this.sheduleNextAutodial();\n }\n sheduleNextAutodial() {\n if (!this.started) {\n return;\n }\n this.autoDialInterval = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }, this.autoDialIntervalMs);\n }\n}\n//# sourceMappingURL=auto-dial.js.map","/**\n * Close the passed stream, falling back to aborting the stream if closing\n * cleanly fails.\n */\nexport async function safelyCloseStream(stream, options) {\n try {\n await stream?.close(options);\n }\n catch (err) {\n stream?.abort(err);\n }\n}\n/**\n * These are speculative protocols that are run automatically on connection open\n * so are usually not the reason the connection was opened.\n *\n * Consequently when requested it should be safe to close connections that only\n * have these protocol streams open.\n */\nconst DEFAULT_CLOSABLE_PROTOCOLS = [\n // identify\n '/ipfs/id/1.0.0',\n // identify-push\n '/ipfs/id/push/1.0.0',\n // autonat\n '/libp2p/autonat/1.0.0',\n // dcutr\n '/libp2p/dcutr'\n];\n/**\n * Close the passed connection if it has no streams, or only closable protocol\n * streams, falling back to aborting the connection if closing it cleanly fails.\n */\nexport async function safelyCloseConnectionIfUnused(connection, options) {\n const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? [];\n const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS;\n // if the connection has protocols not in the closable protocols list, do not\n // close the connection\n if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {\n return;\n }\n try {\n await connection?.close(options);\n }\n catch (err) {\n connection?.abort(err);\n }\n}\n//# sourceMappingURL=close.js.map","import { PeerMap } from '@libp2p/peer-collections';\nimport { safelyCloseConnectionIfUnused } from '@libp2p/utils/close';\nimport { MAX_CONNECTIONS } from './constants.js';\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n allow: []\n};\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nexport class ConnectionPruner {\n maxConnections;\n connectionManager;\n peerStore;\n allow;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n this.allow = init.allow ?? defaultOptions.allow;\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner');\n // check the max connection limit whenever a peer connects\n components.events.addEventListener('connection:open', () => {\n this.maybePruneConnections()\n .catch(err => {\n this.log.error(err);\n });\n });\n }\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async maybePruneConnections() {\n const connections = this.connectionManager.getConnections();\n const numConnections = connections.length;\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections);\n if (numConnections <= this.maxConnections) {\n return;\n }\n const peerValues = new PeerMap();\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer;\n if (peerValues.has(remotePeer)) {\n continue;\n }\n peerValues.set(remotePeer, 0);\n try {\n const peer = await this.peerStore.get(remotePeer);\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n this.log.error('error loading peer tags', err);\n }\n }\n }\n const sortedConnections = this.sortConnections(connections, peerValues);\n // close some connections\n const toPrune = Math.max(numConnections - this.maxConnections, 0);\n const toClose = [];\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer);\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString());\n });\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection);\n }\n if (toClose.length === toPrune) {\n break;\n }\n }\n // close connections\n await Promise.all(toClose.map(async (connection) => {\n await safelyCloseConnectionIfUnused(connection, {\n signal: AbortSignal.timeout(1000)\n });\n }));\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose });\n }\n sortConnections(connections, peerValues) {\n return connections\n // sort by connection age, newest to oldest\n .sort((a, b) => {\n const connectionALifespan = a.timeline.open;\n const connectionBLifespan = b.timeline.open;\n if (connectionALifespan < connectionBLifespan) {\n return 1;\n }\n if (connectionALifespan > connectionBLifespan) {\n return -1;\n }\n return 0;\n })\n // sort by direction, incoming first then outgoing\n .sort((a, b) => {\n if (a.direction === 'outbound' && b.direction === 'inbound') {\n return 1;\n }\n if (a.direction === 'inbound' && b.direction === 'outbound') {\n return -1;\n }\n return 0;\n })\n // sort by number of streams, lowest to highest\n .sort((a, b) => {\n if (a.streams.length > b.streams.length) {\n return 1;\n }\n if (a.streams.length < b.streams.length) {\n return -1;\n }\n return 0;\n })\n // sort by tag value, lowest to highest\n .sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0;\n const peerBValue = peerValues.get(b.remotePeer) ?? 0;\n if (peerAValue > peerBValue) {\n return 1;\n }\n if (peerAValue < peerBValue) {\n return -1;\n }\n return 0;\n });\n }\n}\n//# sourceMappingURL=connection-pruner.js.map","import { Queue } from './queue/index.js';\nexport class PriorityQueue extends Queue {\n constructor(init = {}) {\n super({\n ...init,\n sort: (a, b) => {\n if (a.options.priority > b.options.priority) {\n return -1;\n }\n if (a.options.priority < b.options.priority) {\n return 1;\n }\n return 0;\n }\n });\n }\n}\n//# sourceMappingURL=priority-queue.js.map","/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal(signals) {\n const controller = new globalThis.AbortController();\n function onAbort() {\n controller.abort();\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort();\n break;\n }\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort);\n }\n }\n function clear() {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n const signal = controller.signal;\n signal.clear = clear;\n return signal;\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable max-depth */\nimport { CodeError, AggregateCodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { PriorityQueue } from '@libp2p/utils/priority-queue';\nimport { resolvers, multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { Circuit } from '@multiformats/multiaddr-matcher';\nimport { anySignal } from 'any-signal';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { codes } from '../errors.js';\nimport { getPeerAddress } from '../get-peer.js';\nimport { DIAL_TIMEOUT, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, LAST_DIAL_FAILURE_KEY, MAX_DIAL_QUEUE_LENGTH } from './constants.js';\nimport { resolveMultiaddrs } from './utils.js';\nimport { DEFAULT_DIAL_PRIORITY } from './index.js';\nconst defaultOptions = {\n addressSorter: defaultAddressSort,\n maxParallelDials: MAX_PARALLEL_DIALS,\n maxDialQueueLength: MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n};\nexport class DialQueue {\n queue;\n components;\n addressSorter;\n maxPeerAddrsToDial;\n maxDialQueueLength;\n dialTimeout;\n shutDownController;\n connections;\n log;\n constructor(components, init = {}) {\n this.addressSorter = init.addressSorter ?? defaultOptions.addressSorter;\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial;\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength;\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout;\n this.connections = init.connections ?? new PeerMap();\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue');\n this.components = components;\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value);\n }\n // controls dial concurrency\n this.queue = new PriorityQueue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n });\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n this.log.error('error in dial queue', event.detail);\n });\n }\n start() {\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n }\n /**\n * Clears any pending dials\n */\n stop() {\n this.shutDownController.abort();\n this.queue.abort();\n }\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial(peerIdOrMultiaddr, options = {}) {\n const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr);\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false;\n }\n if (conn.remotePeer.equals(peerId)) {\n return true;\n }\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr);\n });\n });\n if (existingConnection != null) {\n this.log('already connected to %a', existingConnection.remoteAddr);\n return existingConnection;\n }\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true;\n }\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs;\n if (addresses == null) {\n return false;\n }\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true;\n }\n }\n return false;\n });\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId);\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString());\n }\n return existingDial.join(options);\n }\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL');\n }\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()));\n return this.queue.add(async (options) => {\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal);\n let addrsToDial;\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n });\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr);\n });\n }\n catch (err) {\n signal.clear();\n throw err;\n }\n try {\n let dialed = 0;\n const errors = [];\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId);\n throw new CodeError('Peer had more than maxPeerAddrsToDial', codes.ERR_TOO_MANY_ADDRESSES);\n }\n dialed++;\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n });\n this.log('dial to %a succeeded', address.multiaddr);\n return conn;\n }\n catch (err) {\n this.log.error('dial failed to %a', address.multiaddr, err);\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.patch(peerId, {\n metadata: {\n [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n }\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new CodeError(err.message, ERR_TIMEOUT);\n }\n errors.push(err);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateCodeError(errors, 'All multiaddr dials failed', codes.ERR_TRANSPORT_DIAL_FAILED);\n }\n finally {\n // clean up abort signals/controllers\n signal.clear();\n }\n }, {\n peerId,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal\n });\n }\n createDialAbortController(userSignal) {\n // let any signal abort the dial\n const signal = anySignal([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ]);\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, signal);\n return signal;\n }\n // eslint-disable-next-line complexity\n async calculateMultiaddrs(peerId, multiaddrs = new Set(), options = {}) {\n const addrs = [...multiaddrs].map(ma => ({\n multiaddr: multiaddr(ma),\n isCertified: false\n }));\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF);\n }\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED);\n }\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId);\n try {\n const peer = await this.components.peerStore.get(peerId);\n addrs.push(...peer.addresses);\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n }\n catch (err) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId);\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId);\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })));\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_ROUTERS_AVAILABLE) {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err);\n }\n }\n }\n }\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(addrs.map(async (addr) => {\n const result = await resolveMultiaddrs(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n });\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr;\n }\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }));\n })))\n .flat();\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`;\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop();\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr;\n }\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n };\n }\n return addr;\n });\n }\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.dialTransportForMultiaddr(addr.multiaddr) == null) {\n return false;\n }\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId();\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId);\n }\n return true;\n });\n // deduplicate addresses\n const dedupedAddrs = new Map();\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString();\n const existing = dedupedAddrs.get(maStr);\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false;\n continue;\n }\n dedupedAddrs.set(maStr, addr);\n }\n const dedupedMultiaddrs = [...dedupedAddrs.values()];\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES);\n }\n const gatedAdrs = [];\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue;\n }\n gatedAdrs.push(addr);\n }\n const sortedGatedAddrs = gatedAdrs.sort(this.addressSorter);\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new CodeError('The connection gater denied all addresses in the dial request', codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()));\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()));\n return sortedGatedAddrs;\n }\n async isDialable(multiaddr, options = {}) {\n if (!Array.isArray(multiaddr)) {\n multiaddr = [multiaddr];\n }\n try {\n const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options);\n if (options.runOnTransientConnection === false) {\n // return true if any resolved multiaddrs are not relay addresses\n return addresses.find(addr => {\n return !Circuit.matches(addr.multiaddr);\n }) != null;\n }\n return true;\n }\n catch (err) {\n this.log.trace('error calculating if multiaddr(s) were dialable', err);\n }\n return false;\n }\n}\n//# sourceMappingURL=dial-queue.js.map","import { resolvers } from '@multiformats/multiaddr';\n/**\n * Recursively resolve DNSADDR multiaddrs\n */\nexport async function resolveMultiaddrs(ma, options) {\n // check multiaddr resolvers\n let resolvable = false;\n for (const key of resolvers.keys()) {\n resolvable = ma.protoNames().includes(key);\n if (resolvable) {\n break;\n }\n }\n // return multiaddr if it is not resolvable\n if (!resolvable) {\n return [ma];\n }\n const output = await ma.resolve(options);\n options.log('resolved %s to', ma, output.map(ma => ma.toString()));\n return output;\n}\n//# sourceMappingURL=utils.js.map","import { CodeError, KEEP_ALIVE } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { codes } from '../errors.js';\nimport { getPeerAddress } from '../get-peer.js';\nimport { AutoDial } from './auto-dial.js';\nimport { ConnectionPruner } from './connection-pruner.js';\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, MIN_CONNECTIONS } from './constants.js';\nimport { DialQueue } from './dial-queue.js';\nexport const DEFAULT_DIAL_PRIORITY = 50;\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxConnections: MAX_CONNECTIONS,\n inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialMaxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager {\n started;\n connections;\n allow;\n deny;\n maxIncomingPendingConnections;\n incomingPendingConnections;\n maxConnections;\n dialQueue;\n autoDial;\n connectionPruner;\n inboundConnectionRateLimiter;\n peerStore;\n metrics;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n const minConnections = init.minConnections ?? defaultOptions.minConnections;\n if (this.maxConnections < minConnections) {\n throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS);\n }\n /**\n * Map of connections per peer\n */\n this.connections = new PeerMap();\n this.started = false;\n this.peerStore = components.peerStore;\n this.metrics = components.metrics;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager');\n this.onConnect = this.onConnect.bind(this);\n this.onDisconnect = this.onDisconnect.bind(this);\n this.events.addEventListener('connection:open', this.onConnect);\n this.events.addEventListener('connection:close', this.onDisconnect);\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma));\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma));\n this.incomingPendingConnections = 0;\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections;\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n });\n // controls what happens when we don't have enough connections\n this.autoDial = new AutoDial({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n minConnections,\n autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,\n autoDialPeerRetryThreshold: init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold,\n autoDialDiscoveredPeersDebounce: init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce,\n maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength\n });\n // controls what happens when we have too many connections\n this.connectionPruner = new ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n });\n this.dialQueue = new DialQueue(components, {\n addressSorter: init.addressSorter ?? defaultAddressSort,\n maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: dnsaddrResolver\n },\n connections: this.connections\n });\n }\n isStarted() {\n return this.started;\n }\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start() {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n };\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.direction === 'inbound') {\n metric.inbound++;\n }\n else {\n metric.outbound++;\n }\n }\n }\n return metric;\n }\n });\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n metric[key] = (metric[key] ?? 0) + 1;\n }\n }\n }\n return metric;\n }\n });\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams = {};\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n streams[key] = (streams[key] ?? 0) + 1;\n }\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? [];\n allStreams[protocol].push(count);\n }\n }\n }\n const metric = {};\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b);\n const index = Math.floor(counts.length * 0.9);\n metric[protocol] = counts[index];\n }\n return metric;\n }\n });\n this.dialQueue.start();\n this.autoDial.start();\n this.started = true;\n this.log('started');\n }\n async afterStart() {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(KEEP_ALIVE);\n }]\n });\n await Promise.all(keepAlivePeers.map(async (peer) => {\n await this.openConnection(peer.id)\n .catch(err => {\n this.log.error(err);\n });\n }));\n })\n .catch(err => {\n this.log.error(err);\n });\n this.autoDial.afterStart();\n }\n /**\n * Stops the Connection Manager\n */\n async stop() {\n this.dialQueue.stop();\n this.autoDial.stop();\n // Close all connections we're tracking\n const tasks = [];\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n })());\n }\n }\n this.log('closing %d connections', tasks.length);\n await Promise.all(tasks);\n this.connections.clear();\n this.log('stopped');\n }\n onConnect(evt) {\n void this._onConnect(evt).catch(err => {\n this.log.error(err);\n });\n }\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close();\n return;\n }\n const peerId = connection.remotePeer;\n const storedConns = this.connections.get(peerId);\n let isNewPeer = false;\n if (storedConns != null) {\n storedConns.push(connection);\n }\n else {\n isNewPeer = true;\n this.connections.set(peerId, [connection]);\n }\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n });\n }\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer });\n }\n }\n /**\n * Removes the connection from tracking\n */\n onDisconnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return;\n }\n const peerId = connection.remotePeer;\n let storedConn = this.connections.get(peerId);\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id);\n this.connections.set(peerId, storedConn);\n }\n else if (storedConn != null) {\n this.connections.delete(peerId);\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer });\n }\n }\n getConnections(peerId) {\n if (peerId != null) {\n return this.connections.get(peerId) ?? [];\n }\n let conns = [];\n for (const c of this.connections.values()) {\n conns = conns.concat(c);\n }\n return conns;\n }\n getConnectionsMap() {\n return this.connections;\n }\n async openConnection(peerIdOrMultiaddr, options = {}) {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED);\n }\n options.signal?.throwIfAborted();\n const { peerId } = getPeerAddress(peerIdOrMultiaddr);\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId);\n const existingConnection = this.getConnections(peerId)\n .find(conn => !conn.transient);\n if (existingConnection != null) {\n this.log('had an existing non-transient connection to %p', peerId);\n return existingConnection;\n }\n }\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n });\n let peerConnections = this.connections.get(connection.remotePeer);\n if (peerConnections == null) {\n peerConnections = [];\n this.connections.set(connection.remotePeer, peerConnections);\n }\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false;\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true;\n }\n }\n if (!trackedConnection) {\n peerConnections.push(connection);\n }\n return connection;\n }\n async closeConnections(peerId, options = {}) {\n const connections = this.connections.get(peerId) ?? [];\n await Promise.all(connections.map(async (connection) => {\n try {\n await connection.close(options);\n }\n catch (err) {\n connection.abort(err);\n }\n }));\n }\n async acceptIncomingConnection(maConn) {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr);\n return false;\n }\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (allowConnection) {\n this.incomingPendingConnections++;\n return true;\n }\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr);\n return false;\n }\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address;\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1);\n }\n catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host);\n return false;\n }\n }\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++;\n return true;\n }\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr);\n return false;\n }\n afterUpgradeInbound() {\n this.incomingPendingConnections--;\n }\n getDialQueue() {\n const statusMap = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n };\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => multiaddr(ma))\n };\n });\n }\n async isDialable(multiaddr, options = {}) {\n return this.dialQueue.isDialable(multiaddr, options);\n }\n}\n//# sourceMappingURL=index.js.map","export const KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map","import { CodeError } from '@libp2p/interface';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport merge from 'it-merge';\nimport { codes, messages } from './errors.js';\nexport class CompoundContentRouting {\n routers;\n started;\n components;\n constructor(components, init) {\n this.routers = init.routers ?? [];\n this.started = false;\n this.components = components;\n }\n isStarted() {\n return this.started;\n }\n async start() {\n this.started = true;\n }\n async stop() {\n this.started = false;\n }\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async *findProviders(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = new PeerSet();\n for await (const peer of merge(...self.routers.map(router => router.findProviders(key, options)))) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options);\n }));\n }\n /**\n * Store the given key/value pair in the available content routings\n */\n async put(key, value, options) {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options);\n }));\n }\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get(key, options) {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED);\n }\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options);\n }));\n }\n}\n//# sourceMappingURL=content-routing.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nexport const MAX_FINGERPRINT_SIZE = 64;\nexport class Fingerprint {\n fp;\n h;\n seed;\n constructor(buf, hash, seed, fingerprintSize = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size');\n }\n const fnv = hash.hashV(buf, seed);\n const fp = uint8ArrayAlloc(fingerprintSize);\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i];\n }\n if (fp.length === 0) {\n fp[0] = 7;\n }\n this.fp = fp;\n this.h = hash;\n this.seed = seed;\n }\n hash() {\n return this.h.hash(this.fp, this.seed);\n }\n equals(other) {\n if (!(other?.fp instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.fp, other.fp);\n }\n}\n//# sourceMappingURL=fingerprint.js.map","export function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n}\n//# sourceMappingURL=utils.js.map","import { Fingerprint } from './fingerprint.js';\nimport { getRandomInt } from './utils.js';\nexport class Bucket {\n contents;\n constructor(size) {\n this.contents = new Array(size).fill(null);\n }\n has(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n return this.contents.some((fp) => {\n return fingerprint.equals(fp);\n });\n }\n add(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint;\n return true;\n }\n }\n return true;\n }\n swap(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const i = getRandomInt(0, this.contents.length - 1);\n const current = this.contents[i];\n this.contents[i] = fingerprint;\n return current;\n }\n remove(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp);\n });\n if (found > -1) {\n this.contents[found] = null;\n return true;\n }\n else {\n return false;\n }\n }\n}\n//# sourceMappingURL=bucket.js.map","// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n","import fnv1aHash from '@sindresorhus/fnv1a';\nimport mur from 'murmurhash3js-revisited';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport const murmur3 = {\n hash: (input, seed) => {\n return mur.x86.hash32(input, seed);\n },\n hashV: (input, seed) => {\n return numberToBuffer(murmur3.hash(input, seed));\n }\n};\nexport const fnv1a = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }));\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed));\n }\n};\nexport function numberToBuffer(num) {\n let hex = num.toString(16);\n if (hex.length % 2 === 1) {\n hex = `0${hex}`;\n }\n return uint8ArrayFromString(hex, 'base16');\n}\n//# sourceMappingURL=hashes.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { Bucket } from './bucket.js';\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nconst maxCuckooCount = 500;\nexport class CuckooFilter {\n bucketSize;\n filterSize;\n fingerprintSize;\n buckets;\n count;\n hash;\n seed;\n constructor(init) {\n this.filterSize = init.filterSize;\n this.bucketSize = init.bucketSize ?? 4;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.count = 0;\n this.buckets = [];\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize);\n }\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize);\n }\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++;\n return true;\n }\n const rand = [j, k];\n let i = rand[getRandomInt(0, rand.length - 1)];\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint);\n if (swapped == null) {\n continue;\n }\n i = (i ^ swapped.hash()) % this.filterSize;\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n if (this.buckets[i].add(swapped)) {\n this.count++;\n return true;\n }\n else {\n continue;\n }\n }\n return false;\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.has(fingerprint) ?? false;\n if (inJ) {\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n return this.buckets[k]?.has(fingerprint) ?? false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false;\n if (inJ) {\n this.count--;\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n const inK = this.buckets[k]?.remove(fingerprint) ?? false;\n if (inK) {\n this.count--;\n }\n return inK;\n }\n get reliable() {\n return Math.floor(100 * (this.count / this.filterSize)) <= 95;\n }\n}\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n};\nfunction calculateBucketSize(errorRate = 0.001) {\n if (errorRate > 0.002) {\n return 2;\n }\n if (errorRate > 0.00001) {\n return 4;\n }\n return 8;\n}\nexport function optimize(maxItems, errorRate = 0.001) {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate);\n const load = MAX_LOAD[bucketSize];\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load);\n const fingerprintSize = Math.min(Math.ceil(Math.log(filterSize / bucketSize)) + 2, MAX_FINGERPRINT_SIZE);\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n };\n}\nexport function createCuckooFilter(maxItems, errorRate = 0.005) {\n const opts = optimize(maxItems, errorRate);\n return new CuckooFilter(opts);\n}\n//# sourceMappingURL=cuckoo-filter.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { CuckooFilter, optimize } from './cuckoo-filter.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nexport class ScalableCuckooFilter {\n filterSize;\n bucketSize;\n fingerprintSize;\n scale;\n filterSeries;\n hash;\n seed;\n constructor(init) {\n this.bucketSize = init.bucketSize ?? 4;\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.scale = init.scale ?? 2;\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ];\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n if (this.has(item)) {\n return true;\n }\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable;\n });\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length);\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n });\n this.filterSeries.push(current);\n }\n return current.add(item);\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true;\n }\n }\n return false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true;\n }\n }\n return false;\n }\n get count() {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count;\n }, 0);\n }\n}\nexport function createScalableCuckooFilter(maxItems, errorRate = 0.001, options) {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n });\n}\n//# sourceMappingURL=scalable-cuckoo-filter.js.map","/**\n * @packageDocumentation\n *\n * Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input\n *\n * @example\n *\n * ```javascript\n * import parallel from 'it-parallel'\n * import all from 'it-all'\n * import delay from 'delay'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const input = [\n * async () => {\n * console.info('start 1')\n * await delay(500)\n *\n * console.info('end 1')\n * return 1\n * },\n * async () => {\n * console.info('start 2')\n * await delay(200)\n *\n * console.info('end 2')\n * return 2\n * },\n * async () => {\n * console.info('start 3')\n * await delay(100)\n *\n * console.info('end 3')\n * return 3\n * }\n * ]\n *\n * const result = await all(parallel(input, {\n * concurrency: 2\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [2, 3, 1]\n * ```\n *\n * If order is important, pass `ordered: true` as an option:\n *\n * ```javascript\n * const result = await all(parallel(input, {\n * concurrency: 2,\n * ordered: true\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [1, 2, 3]\n * ```\n */\nimport defer from 'p-defer';\nconst CustomEvent = globalThis.CustomEvent ?? Event;\n/**\n * Takes an (async) iterator that emits promise-returning functions,\n * invokes them in parallel and emits the results as they become available but\n * in the same order as the input\n */\nexport default async function* parallel(source, options = {}) {\n let concurrency = options.concurrency ?? Infinity;\n if (concurrency < 1) {\n concurrency = Infinity;\n }\n const ordered = options.ordered == null ? false : options.ordered;\n const emitter = new EventTarget();\n const ops = [];\n let slotAvailable = defer();\n let resultAvailable = defer();\n let sourceFinished = false;\n let sourceErr;\n let opErred = false;\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve();\n });\n void Promise.resolve().then(async () => {\n try {\n for await (const task of source) {\n if (ops.length === concurrency) {\n slotAvailable = defer();\n await slotAvailable.promise;\n }\n if (opErred) {\n break;\n }\n const op = {\n done: false\n };\n ops.push(op);\n task()\n .then(result => {\n op.done = true;\n op.ok = true;\n op.value = result;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }, err => {\n op.done = true;\n op.err = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n });\n }\n sourceFinished = true;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n catch (err) {\n sourceErr = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n });\n function valuesAvailable() {\n if (ordered) {\n return ops[0]?.done;\n }\n return Boolean(ops.find(op => op.done));\n }\n function* yieldOrderedValues() {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0];\n ops.shift();\n if (op.ok) {\n yield op.value;\n }\n else {\n // allow the source to exit\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n function* yieldUnOrderedValues() {\n // more values can become available while we wait for `yield`\n // to return control to this function\n while (valuesAvailable()) {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].done) {\n const op = ops[i];\n ops.splice(i, 1);\n i--;\n if (op.ok) {\n yield op.value;\n }\n else {\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n }\n }\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer();\n await resultAvailable.promise;\n }\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr;\n }\n if (ordered) {\n yield* yieldOrderedValues();\n }\n else {\n yield* yieldUnOrderedValues();\n }\n if (sourceFinished && ops.length === 0) {\n // not waiting for any results and no more tasks so we are done\n break;\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { CodeError } from '@libp2p/interface';\nimport { createScalableCuckooFilter } from '@libp2p/utils/filters';\nimport merge from 'it-merge';\nimport parallel from 'it-parallel';\nimport { codes, messages } from './errors.js';\nexport class DefaultPeerRouting {\n log;\n peerId;\n peerStore;\n routers;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing');\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.routers = init.routers ?? [];\n }\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer(id, options) {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n if (id.toString() === this.peerId.toString()) {\n throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF);\n }\n const self = this;\n const source = merge(...this.routers.map(router => (async function* () {\n try {\n yield await router.findPeer(id, options);\n }\n catch (err) {\n self.log.error(err);\n }\n })()));\n for await (const peer of source) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n return peer;\n }\n throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND);\n }\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async *getClosestPeers(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = createScalableCuckooFilter(1024);\n for await (const peer of parallel(async function* () {\n const source = merge(...self.routers.map(router => router.getClosestPeers(key, options)));\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n });\n }\n catch (err) {\n self.log.error('could not find peer multiaddrs', err);\n return;\n }\n }\n return peer;\n };\n }\n }())) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id.toBytes())) {\n continue;\n }\n seen.add(peer.id.toBytes());\n yield peer;\n }\n }\n}\n//# sourceMappingURL=peer-routing.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { TypedEventEmitter, setMaxListeners } from '@libp2p/interface';\nimport { anySignal } from 'any-signal';\nimport pDefer, {} from 'p-defer';\nimport { raceEvent } from 'race-event';\nimport { raceSignal } from 'race-signal';\nexport class RandomWalk extends TypedEventEmitter {\n peerRouting;\n log;\n walking;\n walkers;\n shutdownController;\n walkController;\n needNext;\n constructor(components) {\n super();\n this.log = components.logger.forComponent('libp2p:random-walk');\n this.peerRouting = components.peerRouting;\n this.walkers = 0;\n this.walking = false;\n // stops any in-progress walks when the node is shut down\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n start() {\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n stop() {\n this.shutdownController.abort();\n }\n async *walk(options) {\n if (!this.walking) {\n // start the query that causes walk:peer events to be emitted\n this.startWalk();\n }\n this.walkers++;\n const signal = anySignal([this.shutdownController.signal, options?.signal]);\n setMaxListeners(Infinity, signal);\n try {\n while (true) {\n // if another consumer has paused the query, start it again\n this.needNext?.resolve();\n this.needNext = pDefer();\n // wait for a walk:peer or walk:error event\n const event = await raceEvent(this, 'walk:peer', signal, {\n errorEvent: 'walk:error'\n });\n yield event.detail;\n }\n }\n finally {\n signal.clear();\n this.walkers--;\n // stop the walk if no more consumers are interested\n if (this.walkers === 0) {\n this.walkController?.abort();\n this.walkController = undefined;\n }\n }\n }\n startWalk() {\n this.walking = true;\n // the signal for this controller will be aborted if no more random peers\n // are required\n this.walkController = new AbortController();\n setMaxListeners(Infinity, this.walkController.signal);\n const signal = anySignal([this.walkController.signal, this.shutdownController.signal]);\n setMaxListeners(Infinity, signal);\n const start = Date.now();\n let found = 0;\n Promise.resolve().then(async () => {\n this.log('start walk');\n // find peers until no more consumers are interested\n while (this.walkers > 0) {\n try {\n const data = randomBytes(32);\n let s = Date.now();\n for await (const peer of this.peerRouting.getClosestPeers(data, { signal })) {\n if (signal.aborted) {\n this.log('aborting walk');\n }\n signal.throwIfAborted();\n this.log('found peer %p after %dms for %d walkers', peer.id, Date.now() - s, this.walkers);\n found++;\n this.safeDispatchEvent('walk:peer', {\n detail: peer\n });\n // if we only have one consumer, pause the query until they request\n // another random peer or they signal they are no longer interested\n if (this.walkers === 1 && this.needNext != null) {\n this.log('wait for need next');\n await raceSignal(this.needNext.promise, signal);\n }\n s = Date.now();\n }\n this.log('walk iteration for %b and %d walkers finished, found %d peers', data, this.walkers, found);\n }\n catch (err) {\n this.log.error('randomwalk errored', err);\n this.safeDispatchEvent('walk:error', {\n detail: err\n });\n }\n }\n this.log('no walkers left, ended walk');\n })\n .catch(err => {\n this.log.error('randomwalk errored', err);\n })\n .finally(() => {\n this.log('finished walk, found %d peers after %dms', found, Date.now() - start);\n this.walking = false;\n });\n }\n}\n//# sourceMappingURL=random-walk.js.map","import { CodeError } from '@libp2p/interface';\nimport merge from 'merge-options';\nimport { codes } from './errors.js';\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32;\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64;\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar {\n log;\n topologies;\n handlers;\n components;\n constructor(components) {\n this.log = components.logger.forComponent('libp2p:registrar');\n this.topologies = new Map();\n this.handlers = new Map();\n this.components = components;\n this._onDisconnect = this._onDisconnect.bind(this);\n this._onPeerUpdate = this._onPeerUpdate.bind(this);\n this._onPeerIdentify = this._onPeerIdentify.bind(this);\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect);\n this.components.events.addEventListener('peer:update', this._onPeerUpdate);\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify);\n }\n getProtocols() {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort();\n }\n getHandler(protocol) {\n const handler = this.handlers.get(protocol);\n if (handler == null) {\n throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL);\n }\n return handler;\n }\n getTopologies(protocol) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n return [];\n }\n return [\n ...topologies.values()\n ];\n }\n /**\n * Registers the `handler` for each protocol\n */\n async handle(protocol, handler, opts) {\n if (this.handlers.has(protocol)) {\n throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);\n }\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts);\n this.handlers.set(protocol, {\n handler,\n options\n });\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n });\n }\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle(protocols) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols];\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol);\n });\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n });\n }\n /**\n * Register handlers for a set of multicodecs given\n */\n async register(protocol, topology) {\n if (topology == null) {\n throw new CodeError('invalid topology', codes.ERR_INVALID_PARAMETERS);\n }\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`;\n let topologies = this.topologies.get(protocol);\n if (topologies == null) {\n topologies = new Map();\n this.topologies.set(protocol, topologies);\n }\n topologies.set(id, topology);\n return id;\n }\n /**\n * Unregister topology\n */\n unregister(id) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id);\n if (topologies.size === 0) {\n this.topologies.delete(protocol);\n }\n }\n }\n }\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect(evt) {\n const remotePeer = evt.detail;\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(remotePeer) === false) {\n continue;\n }\n topology.filter?.remove(remotePeer);\n topology.onDisconnect?.(remotePeer);\n }\n }\n })\n .catch(err => {\n if (err.code === codes.ERR_NOT_FOUND) {\n // peer has not completed identify so they are not in the peer store\n return;\n }\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err);\n });\n }\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate(evt) {\n const { peer, previous } = evt.detail;\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol));\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(peer.id) === false) {\n continue;\n }\n topology.filter?.remove(peer.id);\n topology.onDisconnect?.(peer.id);\n }\n }\n }\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify(evt) {\n const protocols = evt.detail.protocols;\n const connection = evt.detail.connection;\n const peerId = evt.detail.peerId;\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (connection.transient && topology.notifyOnTransient !== true) {\n continue;\n }\n if (topology.filter?.has(peerId) === true) {\n continue;\n }\n topology.filter?.add(peerId);\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n}\n//# sourceMappingURL=registrar.js.map","class TrackedMap extends Map {\n metric;\n constructor(init) {\n super();\n const { name, metrics } = init;\n this.metric = metrics.registerMetric(name);\n this.updateComponentMetric();\n }\n set(key, value) {\n super.set(key, value);\n this.updateComponentMetric();\n return this;\n }\n delete(key) {\n const deleted = super.delete(key);\n this.updateComponentMetric();\n return deleted;\n }\n clear() {\n super.clear();\n this.updateComponentMetric();\n }\n updateComponentMetric() {\n this.metric.update(this.size);\n }\n}\nexport function trackedMap(config) {\n const { name, metrics } = config;\n let map;\n if (metrics != null) {\n map = new TrackedMap({ name, metrics });\n }\n else {\n map = new Map();\n }\n return map;\n}\n//# sourceMappingURL=tracked-map.js.map","import { CodeError, FaultTolerance } from '@libp2p/interface';\nimport { trackedMap } from '@libp2p/utils/tracked-map';\nimport { codes } from './errors.js';\nexport class DefaultTransportManager {\n log;\n components;\n transports;\n listeners;\n faultTolerance;\n started;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:transports');\n this.components = components;\n this.started = false;\n this.transports = new Map();\n this.listeners = trackedMap({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n });\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL;\n }\n /**\n * Adds a `Transport` to the manager\n */\n add(transport) {\n const tag = transport[Symbol.toStringTag];\n if (tag == null) {\n throw new CodeError('Transport must have a valid tag', codes.ERR_INVALID_KEY);\n }\n if (this.transports.has(tag)) {\n throw new CodeError(`There is already a transport with the tag ${tag}`, codes.ERR_DUPLICATE_TRANSPORT);\n }\n this.log('adding transport %s', tag);\n this.transports.set(tag, transport);\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, []);\n }\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs();\n await this.listen(addrs);\n }\n /**\n * Stops all listeners\n */\n async stop() {\n const tasks = [];\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n }\n await Promise.all(tasks);\n this.log('all listeners closed');\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, []);\n }\n this.started = false;\n }\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial(ma, options) {\n const transport = this.dialTransportForMultiaddr(ma);\n if (transport == null) {\n throw new CodeError(`No transport available for address ${String(ma)}`, codes.ERR_TRANSPORT_UNAVAILABLE);\n }\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n });\n }\n catch (err) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED;\n }\n throw err;\n }\n }\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs() {\n let addrs = [];\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()];\n }\n }\n return addrs;\n }\n /**\n * Returns all the transports instances\n */\n getTransports() {\n return Array.of(...this.transports.values());\n }\n /**\n * Returns all the listener instances\n */\n getListeners() {\n return Array.of(...this.listeners.values()).flat();\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n dialTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.dialFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n listenTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.listenFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen(addrs) {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED);\n }\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only');\n return;\n }\n const couldNotListen = [];\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.listenFilter(addrs);\n const tasks = [];\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr);\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n });\n let listeners = this.listeners.get(key) ?? [];\n if (listeners == null) {\n listeners = [];\n this.listeners.set(key, listeners);\n }\n listeners.push(listener);\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n });\n });\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener);\n // remove the listener\n listeners.splice(index, 1);\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n });\n });\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr));\n }\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key);\n continue;\n }\n const results = await Promise.allSettled(tasks);\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled');\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw new CodeError(`Transport (${key}) could not listen on any available address`, codes.ERR_NO_VALID_ADDRESSES);\n }\n }\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`;\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw new CodeError(message, codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log(`libp2p in dial mode only: ${message}`);\n }\n }\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove(key) {\n const listeners = this.listeners.get(key) ?? [];\n this.log.trace('removing transport %s', key);\n // Close any running listeners\n const tasks = [];\n this.log.trace('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n await Promise.all(tasks);\n this.transports.delete(key);\n this.listeners.delete(key);\n }\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll() {\n const tasks = [];\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key));\n }\n await Promise.all(tasks);\n }\n}\n//# sourceMappingURL=transport-manager.js.map","export const PROTOCOL_ID = '/multistream/1.0.0';\n// Conforming to go-libp2p\n// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297\nexport const MAX_PROTOCOL_LENGTH = 1024;\n//# sourceMappingURL=constants.js.map","import { CodeError } from '@libp2p/interface';\nimport {} from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst NewLine = uint8ArrayFromString('\\n');\n/**\n * `write` encodes and writes a single buffer\n */\nexport async function write(writer, buffer, options) {\n await writer.write(buffer, options);\n}\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport async function writeAll(writer, buffers, options) {\n await writer.writeV(buffers, options);\n}\n/**\n * Read a length-prefixed buffer from the passed stream, stripping the final newline character\n */\nexport async function read(reader, options) {\n const buf = await reader.read(options);\n if (buf.byteLength === 0 || buf.get(buf.byteLength - 1) !== NewLine[0]) {\n options.log.error('Invalid mss message - missing newline', buf);\n throw new CodeError('missing newline', 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE');\n }\n return buf.sublist(0, -1); // Remove newline\n}\n/**\n * Read a length-prefixed string from the passed stream, stripping the final newline character\n */\nexport async function readString(reader, options) {\n const buf = await read(reader, options);\n return uint8ArrayToString(buf.subarray());\n}\n//# sourceMappingURL=multistream.js.map","import { encode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH, PROTOCOL_ID } from './constants.js';\nimport * as multistream from './multistream.js';\n/**\n * Handle multistream protocol selections for the given list of protocols.\n *\n * Note that after a protocol is handled `listener` can no longer be used.\n *\n * @param stream - A duplex iterable stream to listen on\n * @param protocols - A list of protocols (or single protocol) that this listener is able to speak.\n * @param options - an options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex({\n * async onStream (muxedStream) {\n * // mss.handle(handledProtocols)\n * // Returns selected stream and protocol\n * const { stream, protocol } = await mss.handle(muxedStream, [\n * '/ipfs-dht/1.0.0',\n * '/ipfs-bitswap/1.0.0'\n * ])\n *\n * // Typically here we'd call the handler function that was registered in\n * // libp2p for the given protocol:\n * // e.g. handlers[protocol].handler(stream)\n * //\n * // If protocol was /ipfs-dht/1.0.0 it might do something like this:\n * // try {\n * // await pipe(\n * // dhtStream,\n * // source => (async function * () {\n * // for await (const chunk of source)\n * // // Incoming DHT data -> process and yield to respond\n * // })(),\n * // dhtStream\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * }\n * })\n * ```\n */\nexport async function handle(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n options.log.trace('handle: available protocols %s', protocols);\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH,\n maxLengthLength: 2 // 2 bytes is enough to length-prefix MAX_PROTOCOL_LENGTH\n });\n while (true) {\n options.log.trace('handle: reading incoming string');\n const protocol = await multistream.readString(lp, options);\n options.log.trace('handle: read \"%s\"', protocol);\n if (protocol === PROTOCOL_ID) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${PROTOCOL_ID}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n continue;\n }\n if (protocols.includes(protocol)) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', protocol, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', protocol, protocol);\n return { stream: lp.unwrap(), protocol };\n }\n if (protocol === 'ls') {\n // \\n\\n\\n\n const protos = new Uint8ArrayList(...protocols.map(p => encode.single(uint8ArrayFromString(`${p}\\n`))), uint8ArrayFromString('\\n'));\n options.log.trace('handle: respond with \"%s\" for %s', protocols, protocol);\n await multistream.write(lp, protos, options);\n options.log.trace('handle: responded with \"%s\" for %s', protocols, protocol);\n continue;\n }\n options.log('handle: respond with \"na\" for \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString('na\\n'), options);\n options.log('handle: responded with \"na\" for \"%s\"', protocol);\n }\n}\n//# sourceMappingURL=handle.js.map","import { CodeError } from '@libp2p/interface';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH } from './constants.js';\nimport * as multistream from './multistream.js';\nimport { PROTOCOL_ID } from './index.js';\n/**\n * Negotiate a protocol to use from a list of protocols.\n *\n * @param stream - A duplex iterable stream to dial on\n * @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.\n * @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex()\n * const muxedStream = muxer.newStream()\n *\n * // mss.select(protocol(s))\n * // Select from one of the passed protocols (in priority order)\n * // Returns selected stream and protocol\n * const { stream: dhtStream, protocol } = await mss.select(muxedStream, [\n * // This might just be different versions of DHT, but could be different impls\n * '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.\n * '/ipfs-dht/1.0.0'\n * ])\n *\n * // Typically this stream will be passed back to the caller of libp2p.dialProtocol\n * //\n * // ...it might then do something like this:\n * // try {\n * // await pipe(\n * // [uint8ArrayFromString('Some DHT data')]\n * // dhtStream,\n * // async source => {\n * // for await (const chunk of source)\n * // // DHT response data\n * // }\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * ```\n */\nexport async function select(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols];\n if (protocols.length === 1 && options.negotiateFully === false) {\n return optimisticSelect(stream, protocols[0], options);\n }\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n const protocol = protocols.shift();\n if (protocol == null) {\n throw new Error('At least one protocol must be specified');\n }\n options.log.trace('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol);\n const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\\n`);\n const p2 = uint8ArrayFromString(`${protocol}\\n`);\n await multistream.writeAll(lp, [p1, p2], options);\n options.log.trace('select: reading multistream-select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n options.log.trace('select: reading protocol response');\n response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n }\n // We're done\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n options.log.trace('select: write \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('select: reading protocol response');\n const response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\" for \"%s\"', response, protocol);\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n }\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL');\n}\n/**\n * Optimistically negotiates a protocol.\n *\n * It *does not* block writes waiting for the other end to respond. Instead, it\n * simply assumes the negotiation went successfully and starts writing data.\n *\n * Use when it is known that the receiver supports the desired protocol.\n */\nfunction optimisticSelect(stream, protocol, options) {\n const originalSink = stream.sink.bind(stream);\n const originalSource = stream.source;\n let negotiated = false;\n let negotiating = false;\n const doneNegotiating = pDefer();\n let sentProtocol = false;\n let sendingProtocol = false;\n const doneSendingProtocol = pDefer();\n let readProtocol = false;\n let readingProtocol = false;\n const doneReadingProtocol = pDefer();\n const lp = lpStream({\n sink: originalSink,\n source: originalSource\n }, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n stream.sink = async (source) => {\n const { sink } = lp.unwrap();\n await sink(async function* () {\n let sentData = false;\n for await (const buf of source) {\n // started reading before the source yielded, wait for protocol send\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n }\n // writing before reading, send the protocol and the first chunk of data\n if (!sentProtocol) {\n sendingProtocol = true;\n options.log.trace('optimistic: write [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n const protocolString = `${protocol}\\n`;\n // send protocols in first chunk of data written to transport\n yield new Uint8ArrayList(Uint8Array.from([19]), // length of PROTOCOL_ID plus newline\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`), varint.encode(protocolString.length), uint8ArrayFromString(protocolString), buf).subarray();\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n // read the negotiation response but don't block more sending\n negotiate()\n .catch(err => {\n options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err);\n });\n }\n else {\n yield buf;\n }\n sentData = true;\n }\n // special case - the source passed to the sink has ended but we didn't\n // negotiated the protocol yet so do it now\n if (!sentData) {\n await negotiate();\n }\n }());\n };\n async function negotiate() {\n if (negotiating) {\n options.log.trace('optimistic: already negotiating %s stream', protocol);\n await doneNegotiating.promise;\n return;\n }\n negotiating = true;\n try {\n // we haven't sent the protocol yet, send it now\n if (!sentProtocol) {\n options.log.trace('optimistic: doing send protocol for %s stream', protocol);\n await doSendProtocol();\n }\n // if we haven't read the protocol response yet, do it now\n if (!readProtocol) {\n options.log.trace('optimistic: doing read protocol for %s stream', protocol);\n await doReadProtocol();\n }\n }\n finally {\n negotiating = false;\n negotiated = true;\n doneNegotiating.resolve();\n }\n }\n async function doSendProtocol() {\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n return;\n }\n sendingProtocol = true;\n try {\n options.log.trace('optimistic: write [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n await lp.writeV([\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n uint8ArrayFromString(`${protocol}\\n`)\n ]);\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n }\n finally {\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n }\n }\n async function doReadProtocol() {\n if (readingProtocol) {\n await doneReadingProtocol.promise;\n return;\n }\n readingProtocol = true;\n try {\n options.log.trace('optimistic: reading multistream select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('optimistic: read multistream select header \"%s\"', response);\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(lp, options);\n }\n options.log.trace('optimistic: read protocol \"%s\", expecting \"%s\"', response, protocol);\n if (response !== protocol) {\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL');\n }\n }\n finally {\n readProtocol = true;\n readingProtocol = false;\n doneReadingProtocol.resolve();\n }\n }\n stream.source = (async function* () {\n // make sure we've done protocol negotiation before we read stream data\n await negotiate();\n options.log.trace('optimistic: reading data from \"%s\" stream', protocol);\n yield* lp.unwrap().source;\n })();\n if (stream.closeRead != null) {\n const originalCloseRead = stream.closeRead.bind(stream);\n stream.closeRead = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the readable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close read', err);\n });\n }\n // protocol has been negotiated, ok to close the readable end\n await originalCloseRead(opts);\n };\n }\n if (stream.closeWrite != null) {\n const originalCloseWrite = stream.closeWrite.bind(stream);\n stream.closeWrite = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the writable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close write', err);\n });\n }\n // protocol has been negotiated, ok to close the writable end\n await originalCloseWrite(opts);\n };\n }\n if (stream.close != null) {\n const originalClose = stream.close.bind(stream);\n stream.close = async (opts) => {\n // if we are in the process of negotiation, let it finish before closing\n // because we may have unsent early data\n const tasks = [];\n if (sendingProtocol) {\n tasks.push(doneSendingProtocol.promise);\n }\n if (readingProtocol) {\n tasks.push(doneReadingProtocol.promise);\n }\n if (tasks.length > 0) {\n // let the in-flight protocol negotiation finish gracefully\n await raceSignal(Promise.all(tasks), opts?.signal);\n }\n else {\n // no protocol negotiation attempt has occurred so don't start one\n negotiated = true;\n negotiating = false;\n doneNegotiating.resolve();\n }\n // protocol has been negotiated, ok to close the writable end\n await originalClose(opts);\n };\n }\n return {\n stream,\n protocol\n };\n}\n//# sourceMappingURL=select.js.map","export const connectionSymbol = Symbol.for('@libp2p/connection');\nexport function isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map","import { connectionSymbol, CodeError, setMaxListeners } from '@libp2p/interface';\nconst CLOSE_TIMEOUT = 500;\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl {\n /**\n * Connection identifier.\n */\n id;\n /**\n * Observed multiaddr of the remote peer\n */\n remoteAddr;\n /**\n * Remote peer id\n */\n remotePeer;\n direction;\n timeline;\n multiplexer;\n encryption;\n status;\n transient;\n log;\n /**\n * User provided tags\n *\n */\n tags;\n /**\n * Reference to the new stream function of the multiplexer\n */\n _newStream;\n /**\n * Reference to the close function of the raw connection\n */\n _close;\n _abort;\n /**\n * Reference to the getStreams function of the muxer\n */\n _getStreams;\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor(init) {\n const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init;\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`;\n this.remoteAddr = remoteAddr;\n this.remotePeer = remotePeer;\n this.direction = init.direction;\n this.status = 'open';\n this.timeline = init.timeline;\n this.multiplexer = init.multiplexer;\n this.encryption = init.encryption;\n this.transient = init.transient ?? false;\n this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`);\n if (this.remoteAddr.getPeerId() == null) {\n this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`);\n }\n this._newStream = newStream;\n this._close = close;\n this._abort = abort;\n this._getStreams = getStreams;\n this.tags = [];\n }\n [Symbol.toStringTag] = 'Connection';\n [connectionSymbol] = true;\n /**\n * Get all the streams of the muxer\n */\n get streams() {\n return this._getStreams();\n }\n /**\n * Create a new stream from this connection\n */\n async newStream(protocols, options) {\n if (this.status === 'closing') {\n throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED');\n }\n if (this.status === 'closed') {\n throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED');\n }\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n if (this.transient && options?.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n const stream = await this._newStream(protocols, options);\n stream.direction = 'outbound';\n return stream;\n }\n /**\n * Close the connection\n */\n async close(options = {}) {\n if (this.status === 'closed' || this.status === 'closing') {\n return;\n }\n this.log('closing connection to %a', this.remoteAddr);\n this.status = 'closing';\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n this.log.trace('closing all streams');\n // close all streams gracefully - this can throw if we're not multiplexed\n await Promise.all(this.streams.map(async (s) => s.close(options)));\n this.log.trace('closing underlying transport');\n // close raw connection\n await this._close(options);\n this.log.trace('updating timeline with close time');\n this.status = 'closed';\n this.timeline.close = Date.now();\n }\n catch (err) {\n this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err);\n this.abort(err);\n }\n }\n abort(err) {\n this.log.error('aborting connection to %a due to error', this.remoteAddr, err);\n this.status = 'closing';\n this.streams.forEach(s => { s.abort(err); });\n this.log.error('all streams aborted', this.streams.length);\n // Abort raw connection\n this._abort(err);\n this.timeline.close = Date.now();\n this.status = 'closed';\n }\n}\nexport function createConnection(init) {\n return new ConnectionImpl(init);\n}\n//# sourceMappingURL=index.js.map","import { CodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface';\nimport * as mss from '@libp2p/multistream-select';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { createConnection } from './connection/index.js';\nimport { INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js';\nimport { codes } from './errors.js';\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js';\nconst DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000;\nfunction findIncomingStreamLimit(protocol, registrar) {\n try {\n const { options } = registrar.getHandler(protocol);\n return options.maxInboundStreams;\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return DEFAULT_MAX_INBOUND_STREAMS;\n}\nfunction findOutgoingStreamLimit(protocol, registrar, options = {}) {\n try {\n const { options } = registrar.getHandler(protocol);\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams;\n }\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS;\n}\nfunction countStreams(protocol, direction, connection) {\n let streamCount = 0;\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++;\n }\n });\n return streamCount;\n}\nexport class DefaultUpgrader {\n components;\n connectionEncryption;\n muxers;\n inboundUpgradeTimeout;\n events;\n constructor(components, init) {\n this.components = components;\n this.connectionEncryption = new Map();\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter);\n });\n this.muxers = new Map();\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer);\n });\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT;\n this.events = components.events;\n }\n async shouldBlockConnection(remotePeer, maConn, connectionType) {\n const connectionGater = this.components.connectionGater[connectionType];\n if (connectionGater !== undefined) {\n if (await connectionGater(remotePeer, maConn)) {\n throw new CodeError(`The multiaddr connection is blocked by gater.${connectionType}`, codes.ERR_CONNECTION_INTERCEPTED);\n }\n }\n }\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound(maConn, opts) {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn);\n if (!accept) {\n throw new CodeError('connection denied', codes.ERR_CONNECTION_DENIED);\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let muxerFactory;\n let cryptoProtocol;\n const signal = AbortSignal.timeout(this.inboundUpgradeTimeout);\n const onAbort = () => {\n maConn.abort(new CodeError('inbound upgrade timeout', ERR_TIMEOUT));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n setMaxListeners(Infinity, signal);\n try {\n if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {\n throw new CodeError('The multiaddr connection is blocked by gater.acceptConnection', codes.ERR_CONNECTION_INTERCEPTED);\n }\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the inbound connection upgrade');\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n maConn.log('protecting the inbound connection');\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection');\n }\n else {\n const idStr = maConn.remoteAddr.getPeerId();\n if (idStr == null) {\n throw new CodeError('inbound connection that skipped encryption must have a peer id', codes.ERR_INVALID_MULTIADDR);\n }\n const remotePeerId = peerIdFromString(idStr);\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade inbound connection', err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection');\n maConn.log('successfully upgraded inbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n finally {\n signal.removeEventListener('abort', onAbort);\n this.components.connectionManager.afterUpgradeInbound();\n }\n }\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound(maConn, opts) {\n const idStr = maConn.remoteAddr.getPeerId();\n let remotePeerId;\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr);\n await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection');\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let cryptoProtocol;\n let muxerFactory;\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the outbound connection upgrade');\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection');\n }\n else {\n if (remotePeerId == null) {\n throw new CodeError('Encryption was skipped but no peer id was passed', codes.ERR_INVALID_PEER);\n }\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade outbound connection', err);\n await maConn.close(err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection');\n maConn.log('successfully upgraded outbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection(opts) {\n const { cryptoProtocol, direction, maConn, upgradedConn, remotePeer, muxerFactory, transient } = opts;\n let muxer;\n let newStream;\n let connection; // eslint-disable-line prefer-const\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return;\n }\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols();\n const { stream, protocol } = await mss.handle(muxedStream, protocols, {\n log: muxedStream.log,\n yieldBytes: false\n });\n if (connection == null) {\n return;\n }\n connection.log('incoming stream opened on %s', protocol);\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar);\n const streamCount = countStreams(protocol, 'inbound', connection);\n if (streamCount === incomingLimit) {\n const err = new CodeError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`, codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n this._onStream({ connection, stream: muxedStream, protocol });\n })\n .catch(async (err) => {\n connection.log.error('error handling incoming stream id %s', muxedStream.id, err.message, err.code, err.stack);\n if (muxedStream.timeline.close == null) {\n await muxedStream.close();\n }\n });\n }\n });\n newStream = async (protocols, options = {}) => {\n if (muxer == null) {\n throw new CodeError('Stream is not multiplexed', codes.ERR_MUXER_UNAVAILABLE);\n }\n connection.log('starting new stream for protocols %s', protocols);\n const muxedStream = await muxer.newStream();\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols);\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols);\n const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n muxedStream.log.trace('selecting protocol from protocols %s', protocols);\n const { stream, protocol } = await mss.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n });\n muxedStream.log('selected protocol %s', protocol);\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);\n const streamCount = countStreams(protocol, 'outbound', connection);\n if (streamCount >= outgoingLimit) {\n const err = new CodeError(`Too many outbound protocol streams for protocol \"${protocol}\" - ${streamCount}/${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n return muxedStream;\n }\n catch (err) {\n connection.log.error('could not create new stream for protocols %s', protocols, err);\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err);\n }\n if (err.code != null) {\n throw err;\n }\n throw new CodeError(String(err), codes.ERR_UNSUPPORTED_PROTOCOL);\n }\n };\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer', err);\n });\n }\n const _timeline = maConn.timeline;\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close();\n }\n }\n catch (err) {\n connection.log.error('error closing connection after timeline close', err);\n }\n finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n });\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event', err);\n });\n }\n return Reflect.set(...args);\n }\n });\n maConn.timeline.upgraded = Date.now();\n const errConnectionNotMultiplexed = () => {\n throw new CodeError('connection is not multiplexed', codes.ERR_CONNECTION_NOT_MULTIPLEXED);\n };\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n transient,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => { if (muxer != null) {\n return muxer.streams;\n }\n else {\n return [];\n } },\n close: async (options) => {\n // Ensure remaining streams are closed gracefully\n if (muxer != null) {\n connection.log.trace('close muxer');\n await muxer.close(options);\n }\n connection.log.trace('close maconn');\n // close the underlying transport\n await maConn.close(options);\n connection.log.trace('closed maconn');\n },\n abort: (err) => {\n maConn.abort(err);\n // Ensure remaining streams are aborted\n if (muxer != null) {\n muxer.abort(err);\n }\n }\n });\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n });\n return connection;\n }\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream(opts) {\n const { connection, stream, protocol } = opts;\n const { handler, options } = this.components.registrar.getHandler(protocol);\n if (connection.transient && options.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n handler({ connection, stream });\n }\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound(connection) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('handling inbound crypto protocol selection', protocols);\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting inbound connection using', protocol);\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting inbound connection failed', err);\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound(connection, remotePeerId) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('selecting outbound crypto protocol', protocols);\n try {\n connection.log.trace('selecting encrypter from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting outbound connection to %p using %s', remotePeerId, encrypter);\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting outbound connection to %p failed', remotePeerId, err);\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('outbound selecting muxer %s', protocols);\n try {\n connection.log.trace('selecting stream muxer from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n connection.log('selected %s as muxer protocol', protocol);\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing outbound connection', err);\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('inbound handling muxers %s', protocols);\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n });\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing inbound connection', err);\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n}\n//# sourceMappingURL=upgrader.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { contentRoutingSymbol, CodeError, TypedEventEmitter, CustomEvent, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory';\nimport { PersistentPeerStore } from '@libp2p/peer-store';\nimport { isMultiaddr } from '@multiformats/multiaddr';\nimport { MemoryDatastore } from 'datastore-core/memory';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { DefaultAddressManager } from './address-manager/index.js';\nimport { defaultComponents } from './components.js';\nimport { connectionGater } from './config/connection-gater.js';\nimport { validateConfig } from './config.js';\nimport { DefaultConnectionManager } from './connection-manager/index.js';\nimport { CompoundContentRouting } from './content-routing.js';\nimport { codes } from './errors.js';\nimport { DefaultPeerRouting } from './peer-routing.js';\nimport { RandomWalk } from './random-walk.js';\nimport { DefaultRegistrar } from './registrar.js';\nimport { DefaultTransportManager } from './transport-manager.js';\nimport { DefaultUpgrader } from './upgrader.js';\nimport * as pkg from './version.js';\nexport class Libp2pNode extends TypedEventEmitter {\n peerId;\n peerStore;\n contentRouting;\n peerRouting;\n metrics;\n services;\n logger;\n status;\n components;\n log;\n constructor(init) {\n super();\n this.status = 'stopped';\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new TypedEventEmitter();\n const originalDispatch = events.dispatchEvent.bind(events);\n events.dispatchEvent = (evt) => {\n const internalResult = originalDispatch(evt);\n const externalResult = this.dispatchEvent(new CustomEvent(evt.type, { detail: evt.detail }));\n return internalResult || externalResult;\n };\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, events);\n this.peerId = init.peerId;\n this.logger = init.logger ?? defaultLogger();\n this.log = this.logger.forComponent('libp2p');\n // @ts-expect-error {} may not be of type T\n this.services = {};\n const components = this.components = defaultComponents({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: pkg.name,\n version: pkg.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: connectionGater(init.connectionGater),\n dns: init.dns\n });\n this.peerStore = this.configureComponent('peerStore', new PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }));\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components));\n }\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n };\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo });\n }\n });\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components));\n }\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n muxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n });\n // Setup the transport manager\n this.configureComponent('transportManager', new DefaultTransportManager(this.components, init.transportManager));\n // Create the Connection Manager\n this.configureComponent('connectionManager', new DefaultConnectionManager(this.components, init.connectionManager));\n // Create the Registrar\n this.configureComponent('registrar', new DefaultRegistrar(this.components));\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new DefaultAddressManager(this.components, init.addresses));\n // Peer routers\n const peerRouters = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)));\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new DefaultPeerRouting(this.components, {\n routers: peerRouters\n }));\n // Content routers\n const contentRouters = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)));\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new CompoundContentRouting(this.components, {\n routers: contentRouters\n }));\n // Random walk\n this.configureComponent('randomWalk', new RandomWalk(this.components));\n (init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components));\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n });\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)));\n });\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name];\n const service = createService(this.components);\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name);\n continue;\n }\n this.services[name] = service;\n this.configureComponent(name, service);\n if (service[contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name);\n contentRouters.push(service[contentRoutingSymbol]);\n }\n if (service[peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name);\n peerRouters.push(service[peerRoutingSymbol]);\n }\n if (service[peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name);\n service[peerDiscoverySymbol].addEventListener?.('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n }\n }\n }\n }\n configureComponent(name, component) {\n if (component == null) {\n this.log.error('component %s was null or undefined', name);\n }\n this.components[name] = component;\n return component;\n }\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start() {\n if (this.status !== 'stopped') {\n return;\n }\n this.status = 'starting';\n this.log('libp2p is starting');\n try {\n await this.components.beforeStart?.();\n await this.components.start();\n await this.components.afterStart?.();\n this.status = 'started';\n this.safeDispatchEvent('start', { detail: this });\n this.log('libp2p has started');\n }\n catch (err) {\n this.log.error('An error occurred starting libp2p', err);\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started';\n await this.stop();\n throw err;\n }\n }\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop() {\n if (this.status !== 'started') {\n return;\n }\n this.log('libp2p is stopping');\n this.status = 'stopping';\n await this.components.beforeStop?.();\n await this.components.stop();\n await this.components.afterStop?.();\n this.status = 'stopped';\n this.safeDispatchEvent('stop', { detail: this });\n this.log('libp2p has stopped');\n }\n getConnections(peerId) {\n return this.components.connectionManager.getConnections(peerId);\n }\n getDialQueue() {\n return this.components.connectionManager.getDialQueue();\n }\n getPeers() {\n const peerSet = new PeerSet();\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer);\n }\n return Array.from(peerSet);\n }\n async dial(peer, options = {}) {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n });\n }\n async dialProtocol(peer, protocols, options = {}) {\n if (protocols == null) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n if (protocols.length === 0) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n const connection = await this.dial(peer, options);\n return connection.newStream(protocols, options);\n }\n getMultiaddrs() {\n return this.components.addressManager.getAddresses();\n }\n getProtocols() {\n return this.components.registrar.getProtocols();\n }\n async hangUp(peer, options = {}) {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '');\n }\n await this.components.connectionManager.closeConnections(peer, options);\n }\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey(peer, options = {}) {\n this.log('getPublicKey %p', peer);\n if (peer.publicKey != null) {\n return peer.publicKey;\n }\n try {\n const peerInfo = await this.peerStore.get(peer);\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey;\n }\n }\n catch (err) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ]);\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options);\n // ensure the returned key is valid\n unmarshalPublicKey(bytes);\n await this.peerStore.patch(peer, {\n publicKey: bytes\n });\n return bytes;\n }\n async handle(protocols, handler, options) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.handle(protocol, handler, options);\n }));\n }\n async unhandle(protocols) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.unhandle(protocol);\n }));\n }\n async register(protocol, topology) {\n return this.components.registrar.register(protocol, topology);\n }\n unregister(id) {\n this.components.registrar.unregister(id);\n }\n async isDialable(multiaddr, options = {}) {\n return this.components.connectionManager.isDialable(multiaddr, options);\n }\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer(evt) {\n const { detail: peer } = evt;\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error(new Error(codes.ERR_DISCOVERED_SELF));\n return;\n }\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err); });\n }\n}\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode(options = {}) {\n const peerId = options.peerId ??= await createEd25519PeerId();\n if (peerId.privateKey == null) {\n throw new CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY');\n }\n options.privateKey ??= await unmarshalPrivateKey(peerId.privateKey);\n return new Libp2pNode(await validateConfig(options));\n}\n//# sourceMappingURL=libp2p.js.map","export const version = '1.6.1';\nexport const name = 'libp2p';\n//# sourceMappingURL=version.js.map","const DEFAULT_NUM_PEERS_TO_USE = 3;\nexport class BaseProtocolSDK {\n numPeers;\n constructor(options) {\n this.numPeers = options?.numPeersToUse ?? DEFAULT_NUM_PEERS_TO_USE;\n }\n}\n//# sourceMappingURL=base_protocol.js.map","import { FilterCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { messageHashStr } from \"@waku/message-hash\";\nimport { ensurePubsubTopicIsConfigured, groupByContentTopic, Logger, shardInfoToPubsubTopics, toAsyncIterator } from \"@waku/utils\";\nimport { BaseProtocolSDK } from \"./base_protocol.js\";\nconst log = new Logger(\"sdk:filter\");\nconst MINUTE = 60 * 1000;\nconst DEFAULT_SUBSCRIBE_OPTIONS = {\n keepAlive: MINUTE\n};\nexport class SubscriptionManager {\n protocol;\n pubsubTopic;\n peers;\n receivedMessagesHashStr = [];\n keepAliveTimer = null;\n subscriptionCallbacks;\n constructor(pubsubTopic, remotePeers, protocol) {\n this.protocol = protocol;\n this.peers = remotePeers;\n this.pubsubTopic = pubsubTopic;\n this.subscriptionCallbacks = new Map();\n }\n async subscribe(decoders, callback, options = DEFAULT_SUBSCRIBE_OPTIONS) {\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n // check that all decoders are configured for the same pubsub topic as this subscription\n for (const decoder of decodersArray) {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n return {\n failures: [\n {\n error: ProtocolError.TOPIC_DECODER_MISMATCH\n }\n ],\n successes: []\n };\n }\n }\n const decodersGroupedByCT = groupByContentTopic(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n const promises = this.peers.map(async (peer) => this.protocol.subscribe(this.pubsubTopic, peer, contentTopics));\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"subscribe\");\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n };\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n if (options?.keepAlive) {\n this.startKeepAlivePings(options.keepAlive);\n }\n return finalResult;\n }\n async unsubscribe(contentTopics) {\n const promises = this.peers.map(async (peer) => {\n const response = await this.protocol.unsubscribe(this.pubsubTopic, peer, contentTopics);\n contentTopics.forEach((contentTopic) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n return response;\n });\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"unsubscribe\");\n if (this.subscriptionCallbacks.size === 0 && this.keepAliveTimer) {\n this.stopKeepAlivePings();\n }\n return finalResult;\n }\n async ping() {\n const promises = this.peers.map(async (peer) => this.protocol.ping(peer));\n const results = await Promise.allSettled(promises);\n return this.handleResult(results, \"ping\");\n }\n async unsubscribeAll() {\n const promises = this.peers.map(async (peer) => this.protocol.unsubscribeAll(this.pubsubTopic, peer));\n const results = await Promise.allSettled(promises);\n this.subscriptionCallbacks.clear();\n const finalResult = this.handleResult(results, \"unsubscribeAll\");\n if (this.keepAliveTimer) {\n this.stopKeepAlivePings();\n }\n return finalResult;\n }\n async processIncomingMessage(message) {\n const hashedMessageStr = messageHashStr(this.pubsubTopic, message);\n if (this.receivedMessagesHashStr.includes(hashedMessageStr)) {\n log.info(\"Message already received, skipping\");\n return;\n }\n this.receivedMessagesHashStr.push(hashedMessageStr);\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\"Processing message with content topic \", contentTopic, \" on pubsub topic \", this.pubsubTopic);\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n handleResult(results, type) {\n const result = { failures: [], successes: [] };\n for (const promiseResult of results) {\n if (promiseResult.status === \"rejected\") {\n log.error(`Failed to resolve ${type} promise successfully: `, promiseResult.reason);\n result.failures.push({ error: ProtocolError.GENERIC_FAIL });\n }\n else {\n const coreResult = promiseResult.value;\n if (coreResult.failure) {\n result.failures.push(coreResult.failure);\n }\n else {\n result.successes.push(coreResult.success);\n }\n }\n }\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n return result;\n }\n startKeepAlivePings(interval) {\n if (this.keepAliveTimer) {\n log.info(\"Recurring pings already set up.\");\n return;\n }\n this.keepAliveTimer = setInterval(() => {\n const run = async () => {\n try {\n log.info(\"Recurring ping to peers.\");\n await this.ping();\n }\n catch (error) {\n log.error(\"Stopping recurring pings due to failure\", error);\n this.stopKeepAlivePings();\n }\n };\n void run();\n }, interval);\n }\n stopKeepAlivePings() {\n if (!this.keepAliveTimer) {\n log.info(\"Already stopped recurring pings.\");\n return;\n }\n log.info(\"Stopping recurring pings.\");\n clearInterval(this.keepAliveTimer);\n this.keepAliveTimer = null;\n }\n}\nclass FilterSDK extends BaseProtocolSDK {\n protocol;\n activeSubscriptions = new Map();\n async handleIncomingMessage(pubsubTopic, wakuMessage) {\n const subscription = this.getActiveSubscription(pubsubTopic);\n if (!subscription) {\n log.error(`No subscription locally registered for topic ${pubsubTopic}`);\n return;\n }\n await subscription.processIncomingMessage(wakuMessage);\n }\n constructor(libp2p, options) {\n super({ numPeersToUse: options?.numPeersToUse });\n this.protocol = new FilterCore(this.handleIncomingMessage.bind(this), libp2p, options);\n this.activeSubscriptions = new Map();\n }\n //TODO: move to SubscriptionManager\n getActiveSubscription(pubsubTopic) {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n setActiveSubscription(pubsubTopic, subscription) {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(pubsubTopicShardInfo) {\n const pubsubTopic = typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : shardInfoToPubsubTopics(pubsubTopicShardInfo)?.[0];\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n let peers = [];\n try {\n peers = await this.protocol.getPeers();\n }\n catch (error) {\n log.error(\"Error getting peers to initiate subscription: \", error);\n return {\n error: ProtocolError.GENERIC_FAIL,\n subscription: null\n };\n }\n if (peers.length === 0) {\n return {\n error: ProtocolError.NO_PEER_AVAILABLE,\n subscription: null\n };\n }\n log.info(`Creating filter subscription with ${peers.length} peers: `, peers.map((peer) => peer.id.toString()));\n const subscription = this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(pubsubTopic, new SubscriptionManager(pubsubTopic, peers, this.protocol));\n return {\n error: null,\n subscription\n };\n }\n //TODO: remove this dependency on IReceiver\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribe(decoders, callback, options = DEFAULT_SUBSCRIBE_OPTIONS) {\n const uniquePubsubTopics = this.getUniquePubsubTopics(decoders);\n if (uniquePubsubTopics.length === 0) {\n throw Error(\"Failed to subscribe: no pubsubTopic found on decoders provided.\");\n }\n if (uniquePubsubTopics.length > 1) {\n throw Error(\"Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.\");\n }\n const { subscription, error } = await this.createSubscription(uniquePubsubTopics[0]);\n if (error) {\n throw Error(`Failed to create subscription: ${error}`);\n }\n await subscription.subscribe(decoders, callback, options);\n const contentTopics = Array.from(groupByContentTopic(Array.isArray(decoders) ? decoders : [decoders]).keys());\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n toSubscriptionIterator(decoders) {\n return toAsyncIterator(this, decoders);\n }\n getUniquePubsubTopics(decoders) {\n if (!Array.isArray(decoders)) {\n return [decoders.pubsubTopic];\n }\n if (decoders.length === 0) {\n return [];\n }\n const pubsubTopics = new Set(decoders.map((d) => d.pubsubTopic));\n return [...pubsubTopics];\n }\n}\nexport function wakuFilter(init) {\n return (libp2p) => new FilterSDK(libp2p, init);\n}\nasync function pushMessage(subscriptionCallback, pubsubTopic, message) {\n const { decoders, callback } = subscriptionCallback;\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n try {\n const decodePromises = decoders.map((dec) => dec\n .fromProtoObj(pubsubTopic, message)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\")));\n const decodedMessage = await Promise.any(decodePromises);\n await callback(decodedMessage);\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n//# sourceMappingURL=filter.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { isDefined } from \"@waku/utils\";\nimport { bytesToUtf8, concat, numberToBytes, utf8ToBytes } from \"@waku/utils/bytes\";\n/**\n * Deterministic Message Hashing as defined in\n * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)\n */\nexport function messageHash(pubsubTopic, message) {\n const pubsubTopicBytes = utf8ToBytes(pubsubTopic);\n const contentTopicBytes = utf8ToBytes(message.contentTopic);\n const timestampBytes = tryConvertTimestampToBytes(message.timestamp);\n const bytes = concat([\n pubsubTopicBytes,\n message.payload,\n contentTopicBytes,\n message.meta,\n timestampBytes\n ].filter(isDefined));\n return sha256(bytes);\n}\nfunction tryConvertTimestampToBytes(timestamp) {\n if (!timestamp) {\n return;\n }\n return numberToBytes(timestamp.valueOf());\n}\nexport function messageHashStr(pubsubTopic, message) {\n const hash = messageHash(pubsubTopic, message);\n const hashStr = bytesToUtf8(hash);\n return hashStr;\n}\n//# sourceMappingURL=index.js.map","import { LightPushCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, Logger } from \"@waku/utils\";\nimport { BaseProtocolSDK } from \"./base_protocol.js\";\nconst log = new Logger(\"sdk:light-push\");\nclass LightPushSDK extends BaseProtocolSDK {\n protocol;\n constructor(libp2p, options) {\n super({ numPeersToUse: options?.numPeersToUse });\n this.protocol = new LightPushCore(libp2p, options);\n }\n async send(encoder, message) {\n const successes = [];\n const failures = [];\n const { pubsubTopic } = encoder;\n try {\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n }\n catch (error) {\n log.error(\"Failed to send waku light push: pubsub topic not configured\");\n return {\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ],\n successes: []\n };\n }\n const peers = await this.protocol.getPeers();\n if (!peers.length) {\n return {\n successes,\n failures: [{ error: ProtocolError.NO_PEER_AVAILABLE }]\n };\n }\n const sendPromises = peers.map((peer) => this.protocol.send(encoder, message, peer));\n const results = await Promise.allSettled(sendPromises);\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n const { failure, success } = result.value;\n if (success) {\n successes.push(success);\n }\n if (failure) {\n failures.push(failure);\n }\n }\n else {\n log.error(\"Failed to send message to peer\", result.reason);\n failures.push({ error: ProtocolError.GENERIC_FAIL });\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n }\n }\n return {\n successes,\n failures\n };\n }\n}\nexport function wakuLightPush(init = {}) {\n return (libp2p) => new LightPushSDK(libp2p, init);\n}\n//# sourceMappingURL=light_push.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { StoreCore } from \"@waku/core\";\nimport { PageDirection } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, isDefined, Logger } from \"@waku/utils\";\nimport { concat } from \"@waku/utils/bytes\";\nimport { utf8ToBytes } from \"../index.js\";\nimport { BaseProtocolSDK } from \"./base_protocol.js\";\nexport const DefaultPageSize = 10;\nconst DEFAULT_NUM_PEERS = 1;\nconst log = new Logger(\"waku:store:protocol\");\nexport class StoreSDK extends BaseProtocolSDK {\n protocol;\n constructor(libp2p, options) {\n // TODO: options.numPeersToUse is disregarded: https://github.com/waku-org/js-waku/issues/1685\n super({ numPeersToUse: DEFAULT_NUM_PEERS });\n this.protocol = new StoreCore(libp2p, options);\n }\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * This is a generator, useful if you want most control on how messages\n * are processed.\n *\n * The order of the messages returned by the remote Waku node SHOULD BE\n * as follows:\n * - within a page, messages SHOULD be ordered from oldest to most recent\n * - pages direction depends on { @link QueryOptions.pageDirection }\n * @throws If not able to reach a Waku Store peer to query,\n * or if an error is encountered when processing the reply,\n * or if two decoders with the same content topic are passed.\n *\n * This API only supports querying a single pubsub topic at a time.\n * If multiple decoders are provided, they must all have the same pubsub topic.\n * @throws If multiple decoders with different pubsub topics are provided.\n * @throws If no decoders are provided.\n * @throws If no decoders are found for the provided pubsub topic.\n */\n async *queryGenerator(decoders, options) {\n const { pubsubTopic, contentTopics, decodersAsMap } = this.validateDecodersAndPubsubTopic(decoders, options);\n const queryOpts = this.constructOptions(pubsubTopic, contentTopics, options);\n const peer = (await this.protocol.getPeers({\n numPeers: this.numPeers,\n maxBootstrapPeers: 1\n }))[0];\n if (!peer)\n throw new Error(\"No peers available to query\");\n const responseGenerator = this.protocol.queryPerPage(queryOpts, decodersAsMap, peer);\n for await (const messages of responseGenerator) {\n yield messages;\n }\n }\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * The callback function takes a `WakuMessage` in input,\n * messages are processed in order:\n * - oldest to latest if `options.pageDirection` == { @link PageDirection.FORWARD }\n * - latest to oldest if `options.pageDirection` == { @link PageDirection.BACKWARD }\n *\n * The ordering may affect performance.\n * The ordering depends on the behavior of the remote store node.\n * If strong ordering is needed, you may need to handle this at application level\n * and set your own timestamps too (the WakuMessage timestamps are not certified).\n *\n * @throws If not able to reach a Waku Store peer to query,\n * or if an error is encountered when processing the reply,\n * or if two decoders with the same content topic are passed.\n */\n async queryWithOrderedCallback(decoders, callback, options) {\n for await (const promises of this.queryGenerator(decoders, options)) {\n if (await this.processMessages(promises, callback, options))\n break;\n }\n }\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n * The callback function takes a `Promise` in input,\n * useful if messages need to be decrypted and performance matters.\n *\n * The order of the messages passed to the callback is as follows:\n * - within a page, messages are expected to be ordered from oldest to most recent\n * - pages direction depends on { @link QueryOptions.pageDirection }\n *\n * Do note that the resolution of the `Promise {\n if (abort)\n return;\n abort = Boolean(await callback(msgPromise));\n });\n await Promise.all(_promises);\n if (abort)\n break;\n }\n }\n createCursor(message) {\n if (!message ||\n !message.timestamp ||\n !message.payload ||\n !message.contentTopic) {\n throw new Error(\"Message is missing required fields\");\n }\n const contentTopicBytes = utf8ToBytes(message.contentTopic);\n const digest = sha256(concat([contentTopicBytes, message.payload]));\n const messageTime = BigInt(message.timestamp.getTime()) * BigInt(1000000);\n return {\n digest,\n pubsubTopic: message.pubsubTopic,\n senderTime: messageTime,\n receiverTime: messageTime\n };\n }\n validateDecodersAndPubsubTopic(decoders, options) {\n if (decoders.length === 0) {\n throw new Error(\"No decoders provided\");\n }\n // convert array to set to remove duplicates\n const uniquePubsubTopicsInQuery = Array.from(new Set(decoders.map((decoder) => decoder.pubsubTopic)));\n // If multiple pubsub topics are provided, throw an error\n if (uniquePubsubTopicsInQuery.length > 1) {\n throw new Error(\"API does not support querying multiple pubsub topics at once\");\n }\n // we can be certain that there is only one pubsub topic in the query\n const pubsubTopicForQuery = uniquePubsubTopicsInQuery[0];\n ensurePubsubTopicIsConfigured(pubsubTopicForQuery, this.protocol.pubsubTopics);\n // check that the pubsubTopic from the Cursor and Decoder match\n if (options?.cursor?.pubsubTopic &&\n options.cursor.pubsubTopic !== pubsubTopicForQuery) {\n throw new Error(`Cursor pubsub topic (${options?.cursor?.pubsubTopic}) does not match decoder pubsub topic (${pubsubTopicForQuery})`);\n }\n const decodersAsMap = new Map();\n decoders.forEach((dec) => {\n if (decodersAsMap.has(dec.contentTopic)) {\n throw new Error(\"API does not support different decoder per content topic\");\n }\n decodersAsMap.set(dec.contentTopic, dec);\n });\n const contentTopics = decoders\n .filter((decoder) => decoder.pubsubTopic === pubsubTopicForQuery)\n .map((dec) => dec.contentTopic);\n if (contentTopics.length === 0) {\n throw new Error(\"No decoders found for topic \" + pubsubTopicForQuery);\n }\n return {\n pubsubTopic: pubsubTopicForQuery,\n contentTopics,\n decodersAsMap\n };\n }\n constructOptions(pubsubTopic, contentTopics, options = {}) {\n let startTime, endTime;\n if (options?.timeFilter) {\n startTime = options.timeFilter.startTime;\n endTime = options.timeFilter.endTime;\n }\n if (!startTime) {\n log.warn(\"No start time provided\");\n }\n if (!endTime) {\n log.warn(\"No end time provided\");\n }\n const queryOpts = Object.assign({\n pubsubTopic: pubsubTopic,\n pageDirection: PageDirection.BACKWARD,\n pageSize: DefaultPageSize\n }, options, { contentTopics, startTime, endTime });\n return queryOpts;\n }\n /**\n * Processes messages based on the provided callback and options.\n * @private\n */\n async processMessages(messages, callback, options) {\n let abort = false;\n const messagesOrUndef = await Promise.all(messages);\n let processedMessages = messagesOrUndef.filter(isDefined);\n if (this.shouldReverseOrder(options)) {\n processedMessages = processedMessages.reverse();\n }\n await Promise.all(processedMessages.map(async (msg) => {\n if (msg && !abort) {\n abort = Boolean(await callback(msg));\n }\n }));\n return abort;\n }\n /**\n * Determines whether to reverse the order of messages based on the provided options.\n *\n * Messages in pages are ordered from oldest (first) to most recent (last).\n * https://github.com/vacp2p/rfc/issues/533\n *\n * @private\n */\n shouldReverseOrder(options) {\n return (typeof options?.pageDirection === \"undefined\" ||\n options?.pageDirection === PageDirection.BACKWARD);\n }\n}\nexport function wakuStore(init = {}) {\n return (libp2p) => new StoreSDK(libp2p, init);\n}\n//# sourceMappingURL=store.js.map","import { wakuFilter } from \"../protocols/filter.js\";\nimport { wakuLightPush } from \"../protocols/light_push.js\";\nimport { wakuStore } from \"../protocols/store.js\";\nimport { createLibp2pAndUpdateOptions } from \"../utils/libp2p.js\";\nimport { WakuNode } from \"../waku.js\";\n/**\n * Create a Waku node that uses Waku Light Push, Filter and Store to send and\n * receive messages, enabling low resource consumption.\n * Uses Waku Filter V2 by default.\n */\nexport async function createLightNode(options = {}) {\n const libp2p = await createLibp2pAndUpdateOptions(options);\n const store = wakuStore(options);\n const lightPush = wakuLightPush(options);\n const filter = wakuFilter(options);\n return new WakuNode(options, libp2p, store, lightPush, filter);\n}\n//# sourceMappingURL=index.js.map","import { noise } from \"@chainsafe/libp2p-noise\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { mplex } from \"@libp2p/mplex\";\nimport { ping } from \"@libp2p/ping\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { all as filterAll, wss } from \"@libp2p/websockets/filters\";\nimport { wakuMetadata } from \"@waku/core\";\nimport { DefaultPubsubTopic } from \"@waku/interfaces\";\nimport { wakuGossipSub } from \"@waku/relay\";\nimport { ensureShardingConfigured, Logger } from \"@waku/utils\";\nimport { createLibp2p } from \"libp2p\";\nimport { DefaultPingMaxInboundStreams, DefaultUserAgent } from \"../waku.js\";\nimport { defaultPeerDiscoveries } from \"./discovery.js\";\nconst logger = new Logger(\"sdk:create\");\nexport async function defaultLibp2p(shardInfo, wakuGossipSub, options, userAgent) {\n if (!options?.hideWebSocketInfo && process?.env?.NODE_ENV !== \"test\") {\n /* eslint-disable no-console */\n console.info(\"%cIgnore WebSocket connection failures\", \"background: gray; color: white; font-size: x-large\");\n console.info(\"%cWaku tries to discover peers and some of them are expected to fail\", \"background: gray; color: white; font-size: x-large\");\n /* eslint-enable no-console */\n }\n const pubsubService = wakuGossipSub\n ? { pubsub: wakuGossipSub }\n : {};\n const metadataService = shardInfo\n ? { metadata: wakuMetadata(shardInfo) }\n : {};\n const filter = process?.env?.NODE_ENV === \"test\" ? filterAll : wss;\n return createLibp2p({\n connectionManager: {\n minConnections: 1\n },\n transports: [webSockets({ filter })],\n streamMuxers: [mplex()],\n connectionEncryption: [noise()],\n ...options,\n services: {\n identify: identify({\n agentVersion: userAgent ?? DefaultUserAgent\n }),\n ping: ping({\n maxInboundStreams: options?.pingMaxInboundStreams ?? DefaultPingMaxInboundStreams\n }),\n ...metadataService,\n ...pubsubService,\n ...options?.services\n }\n }); // TODO: make libp2p include it;\n}\nexport async function createLibp2pAndUpdateOptions(options) {\n logWhichShardInfoIsUsed(options);\n if (options.contentTopics) {\n options.shardInfo = { contentTopics: options.contentTopics };\n }\n const shardInfo = options.shardInfo\n ? ensureShardingConfigured(options.shardInfo)\n : undefined;\n options.pubsubTopics = shardInfo?.pubsubTopics ??\n options.pubsubTopics ?? [DefaultPubsubTopic];\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(...defaultPeerDiscoveries(options.pubsubTopics));\n }\n if (options?.bootstrapPeers) {\n peerDiscovery.push(bootstrap({ list: options.bootstrapPeers }));\n }\n libp2pOptions.peerDiscovery = peerDiscovery;\n const libp2p = await defaultLibp2p(shardInfo?.shardInfo, wakuGossipSub(options), libp2pOptions, options?.userAgent);\n return libp2p;\n}\nfunction logWhichShardInfoIsUsed(options) {\n if (options.pubsubTopics) {\n logger.info(\"Using pubsubTopics array to bootstrap the node.\");\n return;\n }\n if (options.contentTopics) {\n logger.info(\"Using contentTopics and default cluster ID (1) to bootstrap the node.\");\n return;\n }\n if (options.shardInfo) {\n logger.info(\"Using shardInfo parameters to bootstrap the node.\");\n return;\n }\n}\n//# sourceMappingURL=libp2p.js.map","import { enrTree, wakuDnsDiscovery, wakuLocalPeerCacheDiscovery, wakuPeerExchangeDiscovery } from \"@waku/discovery\";\nimport { DefaultPubsubTopic } from \"@waku/interfaces\";\nconst DEFAULT_NODE_REQUIREMENTS = {\n lightPush: 1,\n filter: 1,\n store: 1\n};\nexport function defaultPeerDiscoveries(pubsubTopics) {\n const isDefaultPubsubTopic = pubsubTopics.includes(DefaultPubsubTopic);\n const dnsEnrTrees = isDefaultPubsubTopic\n ? [enrTree[\"DEPRECATED_DEFAULT_PUBSUB\"]]\n : [enrTree[\"SANDBOX\"], enrTree[\"TEST\"]];\n const discoveries = [\n wakuDnsDiscovery(dnsEnrTrees, DEFAULT_NODE_REQUIREMENTS),\n wakuLocalPeerCacheDiscovery(),\n wakuPeerExchangeDiscovery(pubsubTopics)\n ];\n return discoveries;\n}\n//# sourceMappingURL=discovery.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { CustomEvent } from \"@libp2p/interface\";\nimport { createFromJSON } from \"@libp2p/peer-id-factory\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { Tags } from \"@waku/interfaces\";\nimport { getWsMultiaddrFromMultiaddrs, Logger } from \"@waku/utils\";\nconst log = new Logger(\"peer-exchange-discovery\");\nexport const DEFAULT_LOCAL_TAG_NAME = Tags.LOCAL;\nconst DEFAULT_LOCAL_TAG_VALUE = 50;\nconst DEFAULT_LOCAL_TAG_TTL = 100_000_000;\nexport class LocalPeerCacheDiscovery extends TypedEventEmitter {\n components;\n options;\n isStarted;\n peers = [];\n constructor(components, options) {\n super();\n this.components = components;\n this.options = options;\n this.isStarted = false;\n this.peers = this.getPeersFromLocalStorage();\n }\n get [Symbol.toStringTag]() {\n return \"@waku/local-peer-cache-discovery\";\n }\n async start() {\n if (this.isStarted)\n return;\n log.info(\"Starting Local Storage Discovery\");\n this.components.events.addEventListener(\"peer:identify\", this.handleNewPeers);\n for (const { id: idStr, address } of this.peers) {\n const peerId = await createFromJSON({ id: idStr });\n if (await this.components.peerStore.has(peerId))\n continue;\n await this.components.peerStore.save(peerId, {\n multiaddrs: [multiaddr(address)],\n tags: {\n [this.options?.tagName ?? DEFAULT_LOCAL_TAG_NAME]: {\n value: this.options?.tagValue ?? DEFAULT_LOCAL_TAG_VALUE,\n ttl: this.options?.tagTTL ?? DEFAULT_LOCAL_TAG_TTL\n }\n }\n });\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: [multiaddr(address)]\n }\n }));\n }\n log.info(`Discovered ${this.peers.length} peers`);\n this.isStarted = true;\n }\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping Local Storage Discovery\");\n this.components.events.removeEventListener(\"peer:identify\", this.handleNewPeers);\n this.isStarted = false;\n this.savePeersToLocalStorage();\n }\n handleNewPeers = (event) => {\n const { peerId, listenAddrs } = event.detail;\n const websocketMultiaddr = getWsMultiaddrFromMultiaddrs(listenAddrs);\n const localStoragePeers = this.getPeersFromLocalStorage();\n const existingPeerIndex = localStoragePeers.findIndex((_peer) => _peer.id === peerId.toString());\n if (existingPeerIndex >= 0) {\n localStoragePeers[existingPeerIndex].address =\n websocketMultiaddr.toString();\n }\n else {\n localStoragePeers.push({\n id: peerId.toString(),\n address: websocketMultiaddr.toString()\n });\n }\n this.peers = localStoragePeers;\n this.savePeersToLocalStorage();\n };\n getPeersFromLocalStorage() {\n try {\n const storedPeersData = localStorage.getItem(\"waku:peers\");\n if (!storedPeersData)\n return [];\n const peers = JSON.parse(storedPeersData);\n return peers.filter(isValidStoredPeer);\n }\n catch (error) {\n log.error(\"Error parsing peers from local storage:\", error);\n return [];\n }\n }\n savePeersToLocalStorage() {\n try {\n localStorage.setItem(\"waku:peers\", JSON.stringify(this.peers));\n }\n catch (error) {\n log.error(\"Error saving peers to local storage:\", error);\n }\n }\n}\nfunction isValidStoredPeer(peer) {\n return (peer &&\n typeof peer === \"object\" &&\n typeof peer.id === \"string\" &&\n typeof peer.address === \"string\");\n}\nexport function wakuLocalPeerCacheDiscovery() {\n return (components, options) => new LocalPeerCacheDiscovery(components, options);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Use the `createLibp2p` function to create a libp2p node.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n *\n * const node = await createLibp2p({\n * // ...other options\n * })\n * ```\n */\nimport { createLibp2pNode } from './libp2p.js';\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n *\n * The node will be started unless `start: false` is passed as an option.\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { tcp } from '@libp2p/tcp'\n * import { mplex } from '@libp2p/mplex'\n * import { noise } from '@chainsafe/libp2p-noise'\n * import { yamux } from '@chainsafe/libp2p-yamux'\n *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [yamux(), mplex()],\n * connectionEncryption: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p(options = {}) {\n const node = await createLibp2pNode(options);\n if (options.start !== false) {\n await node.start();\n }\n return node;\n}\n//# sourceMappingURL=index.js.map","import { isPeerId } from \"@libp2p/interface\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { ConnectionManager } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { subscribeToContentTopic } from \"./utils/content_topic.js\";\nexport const DefaultPingKeepAliveValueSecs = 5 * 60;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\nexport const DefaultUserAgent = \"js-waku\";\nexport const DefaultPingMaxInboundStreams = 10;\nconst log = new Logger(\"waku\");\nexport class WakuNode {\n libp2p;\n relay;\n store;\n filter;\n lightPush;\n connectionManager;\n pubsubTopics;\n constructor(options, libp2p, store, lightPush, filter, relay) {\n if (options.pubsubTopics.length == 0) {\n throw new Error(\"At least one pubsub topic must be provided\");\n }\n this.pubsubTopics = options.pubsubTopics;\n this.libp2p = libp2p;\n if (store) {\n this.store = store(libp2p);\n }\n if (filter) {\n this.filter = filter(libp2p);\n }\n if (lightPush) {\n this.lightPush = lightPush(libp2p);\n }\n if (relay) {\n this.relay = relay(libp2p);\n }\n const pingKeepAlive = options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive = this.relay\n ? options.relayKeepAlive || DefaultRelayKeepAliveValueSecs\n : 0;\n const peerId = this.libp2p.peerId.toString();\n this.connectionManager = ConnectionManager.create(peerId, libp2p, { pingKeepAlive, relayKeepAlive }, this.pubsubTopics, this.relay);\n log.info(\"Waku node created\", peerId, `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this\n .lightPush}, filter: ${!!this.filter}`);\n }\n /**\n * Dials to the provided peer.\n *\n * @param peer The peer to dial\n * @param protocols Waku protocols we expect from the peer; Defaults to mounted protocols\n */\n async dial(peer, protocols) {\n const _protocols = protocols ?? [];\n const peerId = mapToPeerIdOrMultiaddr(peer);\n if (typeof protocols === \"undefined\") {\n this.relay && _protocols.push(Protocols.Relay);\n this.store && _protocols.push(Protocols.Store);\n this.filter && _protocols.push(Protocols.Filter);\n this.lightPush && _protocols.push(Protocols.LightPush);\n }\n const codecs = [];\n if (_protocols.includes(Protocols.Relay)) {\n if (this.relay) {\n this.relay.gossipSub.multicodecs.forEach((codec) => codecs.push(codec));\n }\n else {\n log.error(\"Relay codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Store)) {\n if (this.store) {\n codecs.push(this.store.protocol.multicodec);\n }\n else {\n log.error(\"Store codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n if (this.lightPush) {\n codecs.push(this.lightPush.protocol.multicodec);\n }\n else {\n log.error(\"Light Push codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Filter)) {\n if (this.filter) {\n codecs.push(this.filter.protocol.multicodec);\n }\n else {\n log.error(\"Filter codec not included in dial codec: protocol not mounted locally\");\n }\n }\n log.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);\n return this.libp2p.dialProtocol(peerId, codecs);\n }\n async start() {\n await this.libp2p.start();\n }\n async stop() {\n this.connectionManager.stop();\n await this.libp2p.stop();\n }\n async subscribeToContentTopic(contentTopic, peer, callback) {\n return (await subscribeToContentTopic(contentTopic, callback, {\n waku: this,\n peer\n })).subscription;\n }\n isStarted() {\n return this.libp2p.status == \"started\";\n }\n isConnected() {\n return this.connectionManager.isConnected();\n }\n /**\n * Return the local multiaddr with peer id on which libp2p is listening.\n *\n * @throws if libp2p is not listening on localhost.\n */\n getLocalMultiaddrWithID() {\n const localMultiaddr = this.libp2p\n .getMultiaddrs()\n .find((addr) => addr.toString().match(/127\\.0\\.0\\.1/));\n if (!localMultiaddr || localMultiaddr.toString() === \"\") {\n throw \"Not listening on localhost\";\n }\n return localMultiaddr + \"/p2p/\" + this.libp2p.peerId.toString();\n }\n}\nfunction mapToPeerIdOrMultiaddr(peerId) {\n return isPeerId(peerId) ? peerId : multiaddr(peerId);\n}\n//# sourceMappingURL=waku.js.map","import { createDecoder, waitForRemotePeer } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { contentTopicToPubsubTopic, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport { createLightNode } from \"../light-node/index.js\";\n// Given a Waku node, peer Multiaddr, and content topic, creates a decoder and\n// subscription for that content topic.\nasync function prepareSubscription(waku, contentTopic, peer) {\n // Validate that the Waku node matches assumptions\n if (!waku.filter) {\n throw new Error(\"Filter protocol missing from Waku node\");\n }\n const { shardInfo } = waku.libp2p.components.metadata;\n if (!shardInfo) {\n throw new Error(\"Shard info missing from Waku node.\");\n }\n // Validate content topic and ensure node is configured for its corresponding pubsub topic\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic);\n if (!pubsubTopics.includes(pubsubTopic))\n throw new Error(\"Content topic does not match any pubsub topic in shard info.\");\n await waku.dial(peer);\n await waitForRemotePeer(waku, [Protocols.Filter]);\n // Create decoder and subscription\n let decoder = createDecoder(contentTopic, pubsubTopic);\n if (decoder)\n decoder = decoder ?? decoder;\n const { subscription, error } = await waku.filter.createSubscription(pubsubTopic);\n if (error)\n throw new Error(\"Failed to create subscription for content topic.\");\n return { decoder, subscription };\n}\n/**\n * Creates a subscription and streams all new messages for a content topic.\n * Will create a light node configured for the content topic with default settings if a node is not provided in `opts`.\n * Assumes node is using autosharding.\n * @param contentTopic\n * @param opts\n */\nexport async function streamContentTopic(contentTopic, opts) {\n opts.waku =\n opts.waku ??\n (await createLightNode({\n shardInfo: { contentTopics: [contentTopic] }\n }));\n const { decoder, subscription } = await prepareSubscription(opts.waku, contentTopic, opts.peer);\n // Create a ReadableStream that receives any messages for the content topic\n const messageStream = new ReadableStream({\n async start(controller) {\n await subscription.subscribe(decoder, (message) => {\n controller.enqueue(message);\n });\n },\n async cancel() {\n await subscription.unsubscribe([contentTopic]);\n }\n });\n return [messageStream, opts.waku];\n}\n/**\n * Subscribes to new messages for a content topic via callback function.\n * Will create a light node configured for the content topic with default settings if a node is not provided in `opts`.\n * Assumes node is using autosharding.\n * @param contentTopic\n * @param callback Called every time a new message is received on the content topic\n * @param opts\n */\nexport async function subscribeToContentTopic(contentTopic, callback, opts) {\n opts.waku =\n opts.waku ??\n (await createLightNode({\n shardInfo: { contentTopics: [contentTopic] }\n }));\n const { decoder, subscription } = await prepareSubscription(opts.waku, contentTopic, opts.peer);\n await subscription.subscribe(decoder, callback);\n return { subscription, waku: opts.waku };\n}\n//# sourceMappingURL=content_topic.js.map","/**\n * The ENR tree for the different fleets.\n * SANDBOX and TEST fleets are for The Waku Network.\n * DEPRECATED_DEFAULT_PUBSUB is the fleet of nodes supporting the now deprecated DefaultPubsubTopic.\n */\nexport const enrTree = {\n SANDBOX: \"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im\",\n TEST: \"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im\",\n DEPRECATED_DEFAULT_PUBSUB: \"enrtree://ANEDLO25QVUGJOUTQFRYKWX6P4Z4GKVESBMHML7DZ6YK4LGS5FC5O@prod.wakuv2.nodes.status.im\"\n};\nexport const DEFAULT_BOOTSTRAP_TAG_NAME = \"bootstrap\";\nexport const DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nexport const DEFAULT_BOOTSTRAP_TAG_TTL = 100_000_000;\nexport const DEFAULT_NODE_REQUIREMENTS = {\n store: 2,\n filter: 1,\n lightPush: 1\n};\n//# sourceMappingURL=constants.js.map","/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nimport * as nodeCrypto from 'crypto';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _8n = BigInt(8);\nconst CURVE = Object.freeze({\n a: _0n,\n b: BigInt(7),\n P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: _1n,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n});\nconst divNearest = (a, b) => (a + b / _2n) / b;\nconst endo = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar(k) {\n const { n } = CURVE;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000');\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n};\nconst fieldLen = 32;\nconst groupLen = 32;\nconst hashLen = 32;\nconst compressedLen = fieldLen + 1;\nconst uncompressedLen = 2 * fieldLen + 1;\nexport { CURVE };\nfunction weierstrass(x) {\n const { a, b } = CURVE;\n const x2 = mod(x * x);\n const x3 = mod(x2 * x);\n return mod(x3 + a * x + b);\n}\nconst USE_ENDOMORPHISM = CURVE.a === _0n;\nclass ShaError extends Error {\n constructor(message) {\n super(message);\n }\n}\nfunction assertJacPoint(other) {\n if (!(other instanceof JacobianPoint))\n throw new TypeError('JacobianPoint expected');\n}\nclass JacobianPoint {\n constructor(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('JacobianPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return JacobianPoint.ZERO;\n return new JacobianPoint(p.x, p.y, _1n);\n }\n static toAffineBatch(points) {\n const toInv = invertBatch(points.map((p) => p.z));\n return points.map((p, i) => p.toAffine(toInv[i]));\n }\n static normalizeZ(points) {\n return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);\n }\n equals(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n return U1 === U2 && S1 === S2;\n }\n negate() {\n return new JacobianPoint(this.x, mod(-this.y), this.z);\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(B * B);\n const x1b = X1 + B;\n const D = mod(_2n * (mod(x1b * x1b) - A - C));\n const E = mod(_3n * A);\n const F = mod(E * E);\n const X3 = mod(F - _2n * D);\n const Y3 = mod(E * (D - X3) - _8n * C);\n const Z3 = mod(_2n * Y1 * Z1);\n return new JacobianPoint(X3, Y3, Z3);\n }\n add(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n if (X2 === _0n || Y2 === _0n)\n return this;\n if (X1 === _0n || Y1 === _0n)\n return other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n const H = mod(U2 - U1);\n const r = mod(S2 - S1);\n if (H === _0n) {\n if (r === _0n) {\n return this.double();\n }\n else {\n return JacobianPoint.ZERO;\n }\n }\n const HH = mod(H * H);\n const HHH = mod(H * HH);\n const V = mod(U1 * HH);\n const X3 = mod(r * r - HHH - _2n * V);\n const Y3 = mod(r * (V - X3) - S1 * HHH);\n const Z3 = mod(Z1 * Z2 * H);\n return new JacobianPoint(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiplyUnsafe(scalar) {\n const P0 = JacobianPoint.ZERO;\n if (typeof scalar === 'bigint' && scalar === _0n)\n return P0;\n let n = normalizeScalar(scalar);\n if (n === _1n)\n return this;\n if (!USE_ENDOMORPHISM) {\n let p = P0;\n let d = this;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = P0;\n let k2p = P0;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n return k1p.add(k2p);\n }\n precomputeWindow(W) {\n const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;\n const points = [];\n let p = this;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n for (let i = 1; i < 2 ** (W - 1); i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n wNAF(n, affinePoint) {\n if (!affinePoint && this.equals(JacobianPoint.BASE))\n affinePoint = Point.BASE;\n const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;\n if (256 % W) {\n throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');\n }\n let precomputes = affinePoint && pointPrecomputes.get(affinePoint);\n if (!precomputes) {\n precomputes = this.precomputeWindow(W);\n if (affinePoint && W !== 1) {\n precomputes = JacobianPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = JacobianPoint.ZERO;\n let f = JacobianPoint.BASE;\n const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);\n const windowSize = 2 ** (W - 1);\n const mask = BigInt(2 ** W - 1);\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n let wbits = Number(n & mask);\n n >>= shiftBy;\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1;\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n return { p, f };\n }\n multiply(scalar, affinePoint) {\n let n = normalizeScalar(scalar);\n let point;\n let fake;\n if (USE_ENDOMORPHISM) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);\n let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);\n k1p = constTimeNegate(k1neg, k1p);\n k2p = constTimeNegate(k2neg, k2p);\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n, affinePoint);\n point = p;\n fake = f;\n }\n return JacobianPoint.normalizeZ([point, fake])[0];\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(JacobianPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const iz1 = invZ;\n const iz2 = mod(iz1 * iz1);\n const iz3 = mod(iz2 * iz1);\n const ax = mod(x * iz2);\n const ay = mod(y * iz3);\n const zz = mod(z * iz1);\n if (is0)\n return Point.ZERO;\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return new Point(ax, ay);\n }\n}\nJacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);\nJacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nconst pointPrecomputes = new WeakMap();\nexport class Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n hasEvenY() {\n return this.y % _2n === _0n;\n }\n static fromCompressedHex(bytes) {\n const isShort = bytes.length === 32;\n const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrass(x);\n let y = sqrtMod(y2);\n const isYOdd = (y & _1n) === _1n;\n if (isShort) {\n if (isYOdd)\n y = mod(-y);\n }\n else {\n const isFirstByteOdd = (bytes[0] & 1) === 1;\n if (isFirstByteOdd !== isYOdd)\n y = mod(-y);\n }\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromUncompressedHex(bytes) {\n const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));\n const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n const len = bytes.length;\n const header = bytes[0];\n if (len === fieldLen)\n return this.fromCompressedHex(bytes);\n if (len === compressedLen && (header === 0x02 || header === 0x03)) {\n return this.fromCompressedHex(bytes);\n }\n if (len === uncompressedLen && header === 0x04)\n return this.fromUncompressedHex(bytes);\n throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normalizePrivateKey(privateKey));\n }\n static fromSignature(msgHash, signature, recovery) {\n const { r, s } = normalizeSignature(signature);\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('Cannot recover: invalid recovery bit');\n const h = truncateHash(ensureBytes(msgHash));\n const { n } = CURVE;\n const radj = recovery === 2 || recovery === 3 ? r + n : r;\n const rinv = invert(radj, n);\n const u1 = mod(-h * rinv, n);\n const u2 = mod(s * rinv, n);\n const prefix = recovery & 1 ? '03' : '02';\n const R = Point.fromHex(prefix + numTo32bStr(radj));\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);\n if (!Q)\n throw new Error('Cannot recover signature: point at infinify');\n Q.assertValidity();\n return Q;\n }\n toRawBytes(isCompressed = false) {\n return hexToBytes(this.toHex(isCompressed));\n }\n toHex(isCompressed = false) {\n const x = numTo32bStr(this.x);\n if (isCompressed) {\n const prefix = this.hasEvenY() ? '02' : '03';\n return `${prefix}${x}`;\n }\n else {\n return `04${x}${numTo32bStr(this.y)}`;\n }\n }\n toHexX() {\n return this.toHex(true).slice(2);\n }\n toRawX() {\n return this.toRawBytes(true).slice(1);\n }\n assertValidity() {\n const msg = 'Point is not on elliptic curve';\n const { x, y } = this;\n if (!isValidFieldElement(x) || !isValidFieldElement(y))\n throw new Error(msg);\n const left = mod(y * y);\n const right = weierstrass(x);\n if (mod(left - right) !== _0n)\n throw new Error(msg);\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(this.x, mod(-this.y));\n }\n double() {\n return JacobianPoint.fromAffine(this).double().toAffine();\n }\n add(other) {\n return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const P = JacobianPoint.fromAffine(this);\n const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);\n const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);\n const sum = aP.add(bQ);\n return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _0n);\nfunction sliceDER(s) {\n return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;\n}\nfunction parseDERInt(data) {\n if (data.length < 2 || data[0] !== 0x02) {\n throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);\n }\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) {\n throw new Error(`Invalid signature integer: wrong length`);\n }\n if (res[0] === 0x00 && res[1] <= 0x7f) {\n throw new Error('Invalid signature integer: trailing length');\n }\n return { data: bytesToNumber(res), left: data.subarray(len + 2) };\n}\nfunction parseDERSignature(data) {\n if (data.length < 2 || data[0] != 0x30) {\n throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);\n }\n if (data[1] !== data.length - 2) {\n throw new Error('Invalid signature: incorrect length');\n }\n const { data: r, left: sBytes } = parseDERInt(data.subarray(2));\n const { data: s, left: rBytesLeft } = parseDERInt(sBytes);\n if (rBytesLeft.length) {\n throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);\n }\n return { r, s };\n}\nexport class Signature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromCompact(hex) {\n const arr = hex instanceof Uint8Array;\n const name = 'Signature.fromCompact';\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`${name}: Expected string or Uint8Array`);\n const str = arr ? bytesToHex(hex) : hex;\n if (str.length !== 128)\n throw new Error(`${name}: Expected 64-byte hex`);\n return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));\n }\n static fromDER(hex) {\n const arr = hex instanceof Uint8Array;\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);\n const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));\n return new Signature(r, s);\n }\n static fromHex(hex) {\n return this.fromDER(hex);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isWithinCurveOrder(r))\n throw new Error('Invalid Signature: r must be 0 < r < n');\n if (!isWithinCurveOrder(s))\n throw new Error('Invalid Signature: s must be 0 < s < n');\n }\n hasHighS() {\n const HALF = CURVE.n >> _1n;\n return this.s > HALF;\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;\n }\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n const sHex = sliceDER(numberToHexUnpadded(this.s));\n const rHex = sliceDER(numberToHexUnpadded(this.r));\n const sHexL = sHex.length / 2;\n const rHexL = rHex.length / 2;\n const sLen = numberToHexUnpadded(sHexL);\n const rLen = numberToHexUnpadded(rHexL);\n const length = numberToHexUnpadded(rHexL + sHexL + 4);\n return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;\n }\n toRawBytes() {\n return this.toDERRawBytes();\n }\n toHex() {\n return this.toDERHex();\n }\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n}\nfunction concatBytes(...arrays) {\n if (!arrays.every((b) => b instanceof Uint8Array))\n throw new Error('Uint8Array list expected');\n if (arrays.length === 1)\n return arrays[0];\n const length = arrays.reduce((a, arr) => a + arr.length, 0);\n const result = new Uint8Array(length);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n result.set(arr, pad);\n pad += arr.length;\n }\n return result;\n}\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\nfunction bytesToHex(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return hex;\n}\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nfunction numTo32bStr(num) {\n if (typeof num !== 'bigint')\n throw new Error('Expected bigint');\n if (!(_0n <= num && num < POW_2_256))\n throw new Error('Expected number 0 <= n < 2^256');\n return num.toString(16).padStart(64, '0');\n}\nfunction numTo32b(num) {\n const b = hexToBytes(numTo32bStr(num));\n if (b.length !== 32)\n throw new Error('Error: expected 32 bytes');\n return b;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToNumber: expected string, got ' + typeof hex);\n }\n return BigInt(`0x${hex}`);\n}\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToBytes: expected string, got ' + typeof hex);\n }\n if (hex.length % 2)\n throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\nfunction bytesToNumber(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction ensureBytes(hex) {\n return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n}\nfunction normalizeScalar(num) {\n if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)\n return BigInt(num);\n if (typeof num === 'bigint' && isWithinCurveOrder(num))\n return num;\n throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');\n}\nfunction mod(a, b = CURVE.P) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\nfunction pow2(x, power) {\n const { P } = CURVE;\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= P;\n }\n return res;\n}\nfunction sqrtMod(x) {\n const { P } = CURVE;\n const _6n = BigInt(6);\n const _11n = BigInt(11);\n const _22n = BigInt(22);\n const _23n = BigInt(23);\n const _44n = BigInt(44);\n const _88n = BigInt(88);\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n) * b3) % P;\n const b9 = (pow2(b6, _3n) * b3) % P;\n const b11 = (pow2(b9, _2n) * b2) % P;\n const b22 = (pow2(b11, _11n) * b11) % P;\n const b44 = (pow2(b22, _22n) * b22) % P;\n const b88 = (pow2(b44, _44n) * b44) % P;\n const b176 = (pow2(b88, _88n) * b88) % P;\n const b220 = (pow2(b176, _44n) * b44) % P;\n const b223 = (pow2(b220, _3n) * b3) % P;\n const t1 = (pow2(b223, _23n) * b22) % P;\n const t2 = (pow2(t1, _6n) * b2) % P;\n const rt = pow2(t2, _2n);\n const xc = (rt * rt) % P;\n if (xc !== x)\n throw new Error('Cannot find square root');\n return rt;\n}\nfunction invert(number, modulo = CURVE.P) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n let a = mod(number, modulo);\n let b = modulo;\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction invertBatch(nums, p = CURVE.P) {\n const scratch = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = acc;\n return mod(acc * num, p);\n }, _1n);\n const inverted = invert(lastMultiplied, p);\n nums.reduceRight((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = mod(acc * scratch[i], p);\n return mod(acc * num, p);\n }, inverted);\n return scratch;\n}\nfunction bits2int_2(bytes) {\n const delta = bytes.length * 8 - groupLen * 8;\n const num = bytesToNumber(bytes);\n return delta > 0 ? num >> BigInt(delta) : num;\n}\nfunction truncateHash(hash, truncateOnly = false) {\n const h = bits2int_2(hash);\n if (truncateOnly)\n return h;\n const { n } = CURVE;\n return h >= n ? h - n : h;\n}\nlet _sha256Sync;\nlet _hmacSha256Sync;\nclass HmacDrbg {\n constructor(hashLen, qByteLen) {\n this.hashLen = hashLen;\n this.qByteLen = qByteLen;\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n this.v = new Uint8Array(hashLen).fill(1);\n this.k = new Uint8Array(hashLen).fill(0);\n this.counter = 0;\n }\n hmac(...values) {\n return utils.hmacSha256(this.k, ...values);\n }\n hmacSync(...values) {\n return _hmacSha256Sync(this.k, ...values);\n }\n checkSync() {\n if (typeof _hmacSha256Sync !== 'function')\n throw new ShaError('hmacSha256Sync needs to be set');\n }\n incr() {\n if (this.counter >= 1000)\n throw new Error('Tried 1,000 k values for sign(), all were invalid');\n this.counter += 1;\n }\n async reseed(seed = new Uint8Array()) {\n this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed);\n this.v = await this.hmac(this.v);\n if (seed.length === 0)\n return;\n this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed);\n this.v = await this.hmac(this.v);\n }\n reseedSync(seed = new Uint8Array()) {\n this.checkSync();\n this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);\n this.v = this.hmacSync(this.v);\n if (seed.length === 0)\n return;\n this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed);\n this.v = this.hmacSync(this.v);\n }\n async generate() {\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = await this.hmac(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n generateSync() {\n this.checkSync();\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = this.hmacSync(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n}\nfunction isWithinCurveOrder(num) {\n return _0n < num && num < CURVE.n;\n}\nfunction isValidFieldElement(num) {\n return _0n < num && num < CURVE.P;\n}\nfunction kmdToSig(kBytes, m, d, lowS = true) {\n const { n } = CURVE;\n const k = truncateHash(kBytes, true);\n if (!isWithinCurveOrder(k))\n return;\n const kinv = invert(k, n);\n const q = Point.BASE.multiply(k);\n const r = mod(q.x, n);\n if (r === _0n)\n return;\n const s = mod(kinv * mod(m + d * r, n), n);\n if (s === _0n)\n return;\n let sig = new Signature(r, s);\n let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);\n if (lowS && sig.hasHighS()) {\n sig = sig.normalizeS();\n recovery ^= 1;\n }\n return { sig, recovery };\n}\nfunction normalizePrivateKey(key) {\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {\n num = BigInt(key);\n }\n else if (typeof key === 'string') {\n if (key.length !== 2 * groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = hexToNumber(key);\n }\n else if (key instanceof Uint8Array) {\n if (key.length !== groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = bytesToNumber(key);\n }\n else {\n throw new TypeError('Expected valid private key');\n }\n if (!isWithinCurveOrder(num))\n throw new Error('Expected private key: 0 < key < n');\n return num;\n}\nfunction normalizePublicKey(publicKey) {\n if (publicKey instanceof Point) {\n publicKey.assertValidity();\n return publicKey;\n }\n else {\n return Point.fromHex(publicKey);\n }\n}\nfunction normalizeSignature(signature) {\n if (signature instanceof Signature) {\n signature.assertValidity();\n return signature;\n }\n try {\n return Signature.fromDER(signature);\n }\n catch (error) {\n return Signature.fromCompact(signature);\n }\n}\nexport function getPublicKey(privateKey, isCompressed = false) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n}\nexport function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {\n return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);\n}\nfunction isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === compressedLen * 2 || len === uncompressedLen * 2;\n if (item instanceof Point)\n return true;\n return false;\n}\nexport function getSharedSecret(privateA, publicB, isCompressed = false) {\n if (isProbPub(privateA))\n throw new TypeError('getSharedSecret: first arg must be private key');\n if (!isProbPub(publicB))\n throw new TypeError('getSharedSecret: second arg must be public key');\n const b = normalizePublicKey(publicB);\n b.assertValidity();\n return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);\n}\nfunction bits2int(bytes) {\n const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;\n return bytesToNumber(slice);\n}\nfunction bits2octets(bytes) {\n const z1 = bits2int(bytes);\n const z2 = mod(z1, CURVE.n);\n return int2octets(z2 < _0n ? z1 : z2);\n}\nfunction int2octets(num) {\n return numTo32b(num);\n}\nfunction initSigArgs(msgHash, privateKey, extraEntropy) {\n if (msgHash == null)\n throw new Error(`sign: expected valid message hash, not \"${msgHash}\"`);\n const h1 = ensureBytes(msgHash);\n const d = normalizePrivateKey(privateKey);\n const seedArgs = [int2octets(d), bits2octets(h1)];\n if (extraEntropy != null) {\n if (extraEntropy === true)\n extraEntropy = utils.randomBytes(fieldLen);\n const e = ensureBytes(extraEntropy);\n if (e.length !== fieldLen)\n throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);\n seedArgs.push(e);\n }\n const seed = concatBytes(...seedArgs);\n const m = bits2int(h1);\n return { seed, m, d };\n}\nfunction finalizeSig(recSig, opts) {\n const { sig, recovery } = recSig;\n const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);\n const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();\n return recovered ? [hashed, recovery] : hashed;\n}\nasync function sign(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n await drbg.reseed(seed);\n let sig;\n while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))\n await drbg.reseed();\n return finalizeSig(sig, opts);\n}\nfunction signSync(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n drbg.reseedSync(seed);\n let sig;\n while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical)))\n drbg.reseedSync();\n return finalizeSig(sig, opts);\n}\nexport { sign, signSync };\nconst vopts = { strict: true };\nexport function verify(signature, msgHash, publicKey, opts = vopts) {\n let sig;\n try {\n sig = normalizeSignature(signature);\n msgHash = ensureBytes(msgHash);\n }\n catch (error) {\n return false;\n }\n const { r, s } = sig;\n if (opts.strict && sig.hasHighS())\n return false;\n const h = truncateHash(msgHash);\n let P;\n try {\n P = normalizePublicKey(publicKey);\n }\n catch (error) {\n return false;\n }\n const { n } = CURVE;\n const sinv = invert(s, n);\n const u1 = mod(h * sinv, n);\n const u2 = mod(r * sinv, n);\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2);\n if (!R)\n return false;\n const v = mod(R.x, n);\n return v === r;\n}\nfunction schnorrChallengeFinalize(ch) {\n return mod(bytesToNumber(ch), CURVE.n);\n}\nclass SchnorrSignature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n if (bytes.length !== 64)\n throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);\n const r = bytesToNumber(bytes.subarray(0, 32));\n const s = bytesToNumber(bytes.subarray(32, 64));\n return new SchnorrSignature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isValidFieldElement(r) || !isWithinCurveOrder(s))\n throw new Error('Invalid signature');\n }\n toHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n toRawBytes() {\n return hexToBytes(this.toHex());\n }\n}\nfunction schnorrGetPublicKey(privateKey) {\n return Point.fromPrivateKey(privateKey).toRawX();\n}\nclass InternalSchnorrSignature {\n constructor(message, privateKey, auxRand = utils.randomBytes()) {\n if (message == null)\n throw new TypeError(`sign: Expected valid message, not \"${message}\"`);\n this.m = ensureBytes(message);\n const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey));\n this.px = x;\n this.d = scalar;\n this.rand = ensureBytes(auxRand);\n if (this.rand.length !== 32)\n throw new TypeError('sign: Expected 32 bytes of aux randomness');\n }\n getScalar(priv) {\n const point = Point.fromPrivateKey(priv);\n const scalar = point.hasEvenY() ? priv : CURVE.n - priv;\n return { point, scalar, x: point.toRawX() };\n }\n initNonce(d, t0h) {\n return numTo32b(d ^ bytesToNumber(t0h));\n }\n finalizeNonce(k0h) {\n const k0 = mod(bytesToNumber(k0h), CURVE.n);\n if (k0 === _0n)\n throw new Error('sign: Creation of signature failed. k is zero');\n const { point: R, x: rx, scalar: k } = this.getScalar(k0);\n return { R, rx, k };\n }\n finalizeSig(R, k, e, d) {\n return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();\n }\n error() {\n throw new Error('sign: Invalid signature produced');\n }\n async calc() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHash;\n const t = this.initNonce(d, await tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!(await schnorrVerify(sig, m, px)))\n this.error();\n return sig;\n }\n calcSync() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHashSync;\n const t = this.initNonce(d, tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!schnorrVerifySync(sig, m, px))\n this.error();\n return sig;\n }\n}\nasync function schnorrSign(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calc();\n}\nfunction schnorrSignSync(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync();\n}\nfunction initSchnorrVerify(signature, message, publicKey) {\n const raw = signature instanceof SchnorrSignature;\n const sig = raw ? signature : SchnorrSignature.fromHex(signature);\n if (raw)\n sig.assertValidity();\n return {\n ...sig,\n m: ensureBytes(message),\n P: normalizePublicKey(publicKey),\n };\n}\nfunction finalizeSchnorrVerify(r, P, s, e) {\n const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));\n if (!R || !R.hasEvenY() || R.x !== r)\n return false;\n return true;\n}\nasync function schnorrVerify(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n return false;\n }\n}\nfunction schnorrVerifySync(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n if (error instanceof ShaError)\n throw error;\n return false;\n }\n}\nexport const schnorr = {\n Signature: SchnorrSignature,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n signSync: schnorrSignSync,\n verifySync: schnorrVerifySync,\n};\nPoint.BASE._setWindowSize(8);\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n aux: 'BIP0340/aux',\n nonce: 'BIP0340/nonce',\n};\nconst TAGGED_HASH_PREFIXES = {};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n isValidPrivateKey(privateKey) {\n try {\n normalizePrivateKey(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n _bigintTo32Bytes: numTo32b,\n _normalizePrivateKey: normalizePrivateKey,\n hashToPrivateKey: (hash) => {\n hash = ensureBytes(hash);\n const minLen = groupLen + 8;\n if (hash.length < minLen || hash.length > 1024) {\n throw new Error(`Expected valid bytes of private key as per FIPS 186`);\n }\n const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;\n return numTo32b(num);\n },\n randomBytes: (bytesLength = 32) => {\n if (crypto.web) {\n return crypto.web.getRandomValues(new Uint8Array(bytesLength));\n }\n else if (crypto.node) {\n const { randomBytes } = crypto.node;\n return Uint8Array.from(randomBytes(bytesLength));\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point === Point.BASE ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_3n);\n return cached;\n },\n sha256: async (...messages) => {\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages));\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHash } = crypto.node;\n const hash = createHash('sha256');\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha256 function\");\n }\n },\n hmacSha256: async (key, ...messages) => {\n if (crypto.web) {\n const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n const message = concatBytes(...messages);\n const buffer = await crypto.web.subtle.sign('HMAC', ckey, message);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHmac } = crypto.node;\n const hash = createHmac('sha256', key);\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have hmac-sha256 function\");\n }\n },\n sha256Sync: undefined,\n hmacSha256Sync: undefined,\n taggedHash: async (tag, ...messages) => {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return utils.sha256(tagP, ...messages);\n },\n taggedHashSync: (tag, ...messages) => {\n if (typeof _sha256Sync !== 'function')\n throw new ShaError('sha256Sync is undefined, you need to set it');\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return _sha256Sync(tagP, ...messages);\n },\n _JacobianPoint: JacobianPoint,\n};\nObject.defineProperties(utils, {\n sha256Sync: {\n configurable: false,\n get() {\n return _sha256Sync;\n },\n set(val) {\n if (!_sha256Sync)\n _sha256Sync = val;\n },\n },\n hmacSha256Sync: {\n configurable: false,\n get() {\n return _hmacSha256Sync;\n },\n set(val) {\n if (!_hmacSha256Sync)\n _hmacSha256Sync = val;\n },\n },\n});\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"@waku/utils/bytes\";\nimport sha3 from \"js-sha3\";\n/**\n * ECDSA Sign a message with the given private key.\n *\n * @param message The message to sign, usually a hash.\n * @param privateKey The ECDSA private key to use to sign the message.\n *\n * @returns The signature and the recovery id concatenated.\n */\nexport async function sign(message, privateKey) {\n const [signature, recoveryId] = await secp.sign(message, privateKey, {\n recovered: true,\n der: false\n });\n return concat([signature, new Uint8Array([recoveryId])], signature.length + 1);\n}\nexport function keccak256(input) {\n return new Uint8Array(sha3.keccak256.arrayBuffer(input));\n}\nexport function compressPublicKey(publicKey) {\n if (publicKey.length === 64) {\n publicKey = concat([new Uint8Array([4]), publicKey], 65);\n }\n const point = secp.Point.fromHex(publicKey);\n return point.toRawBytes(true);\n}\n/**\n * Verify an ECDSA signature.\n */\nexport function verifySignature(signature, message, publicKey) {\n try {\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n return secp.verify(_signature, message, publicKey);\n }\n catch {\n return false;\n }\n}\n//# sourceMappingURL=crypto.js.map","// Maximum encoded size of an ENR\nexport const MAX_RECORD_SIZE = 300;\nexport const ERR_INVALID_ID = \"Invalid record id\";\nexport const ERR_NO_SIGNATURE = \"No valid signature found\";\n// The maximum length of byte size of a multiaddr to encode in the `multiaddr` field\n// The size is a big endian 16-bit unsigned integer\nexport const MULTIADDR_LENGTH_SIZE = 2;\n//# sourceMappingURL=constants.js.map","import { multiaddrFromFields } from \"./multiaddr_from_fields.js\";\nexport function locationMultiaddrFromEnrFields(enr, protocol) {\n switch (protocol) {\n case \"udp\":\n return (locationMultiaddrFromEnrFields(enr, \"udp4\") ||\n locationMultiaddrFromEnrFields(enr, \"udp6\"));\n case \"tcp\":\n return (locationMultiaddrFromEnrFields(enr, \"tcp4\") ||\n locationMultiaddrFromEnrFields(enr, \"tcp6\"));\n }\n const isIpv6 = protocol.endsWith(\"6\");\n const ipVal = enr.get(isIpv6 ? \"ip6\" : \"ip\");\n if (!ipVal)\n return;\n const protoName = protocol.slice(0, 3);\n let protoVal;\n switch (protoName) {\n case \"udp\":\n protoVal = isIpv6 ? enr.get(\"udp6\") : enr.get(\"udp\");\n break;\n case \"tcp\":\n protoVal = isIpv6 ? enr.get(\"tcp6\") : enr.get(\"tcp\");\n break;\n default:\n return;\n }\n if (!protoVal)\n return;\n return multiaddrFromFields(isIpv6 ? \"ip6\" : \"ip4\", protoName, ipVal, protoVal);\n}\n//# sourceMappingURL=get_multiaddr.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { convertToString } from \"@multiformats/multiaddr/convert\";\nexport function multiaddrFromFields(ipFamily, protocol, ipBytes, protocolBytes) {\n let ma = multiaddr(\"/\" + ipFamily + \"/\" + convertToString(ipFamily, ipBytes));\n ma = ma.encapsulate(multiaddr(\"/\" + protocol + \"/\" + convertToString(protocol, protocolBytes)));\n return ma;\n}\n//# sourceMappingURL=multiaddr_from_fields.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { MULTIADDR_LENGTH_SIZE } from \"./constants.js\";\nexport function decodeMultiaddrs(bytes) {\n const multiaddrs = [];\n let index = 0;\n while (index < bytes.length) {\n const sizeDataView = new DataView(bytes.buffer, index, MULTIADDR_LENGTH_SIZE);\n const size = sizeDataView.getUint16(0);\n index += MULTIADDR_LENGTH_SIZE;\n const multiaddrBytes = bytes.slice(index, index + size);\n index += size;\n multiaddrs.push(multiaddr(multiaddrBytes));\n }\n return multiaddrs;\n}\nexport function encodeMultiaddrs(multiaddrs) {\n const totalLength = multiaddrs.reduce((acc, ma) => acc + MULTIADDR_LENGTH_SIZE + ma.bytes.length, 0);\n const bytes = new Uint8Array(totalLength);\n const dataView = new DataView(bytes.buffer);\n let index = 0;\n multiaddrs.forEach((multiaddr) => {\n if (multiaddr.getPeerId())\n throw new Error(\"`multiaddr` field MUST not contain peer id\");\n // Prepend the size of the next entry\n dataView.setUint16(index, multiaddr.bytes.length);\n index += MULTIADDR_LENGTH_SIZE;\n bytes.set(multiaddr.bytes, index);\n index += multiaddr.bytes.length;\n });\n return bytes;\n}\n//# sourceMappingURL=multiaddrs_codec.js.map","export function encodeWaku2(protocols) {\n let byte = 0;\n if (protocols.lightPush)\n byte += 1;\n byte = byte << 1;\n if (protocols.filter)\n byte += 1;\n byte = byte << 1;\n if (protocols.store)\n byte += 1;\n byte = byte << 1;\n if (protocols.relay)\n byte += 1;\n return byte;\n}\nexport function decodeWaku2(byte) {\n const waku2 = {\n relay: false,\n store: false,\n filter: false,\n lightPush: false\n };\n if (byte % 2)\n waku2.relay = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.store = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.filter = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.lightPush = true;\n return waku2;\n}\n//# sourceMappingURL=waku2_codec.js.map","import { convertToBytes, convertToString } from \"@multiformats/multiaddr/convert\";\nimport { decodeRelayShard } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { decodeMultiaddrs, encodeMultiaddrs } from \"./multiaddrs_codec.js\";\nimport { decodeWaku2, encodeWaku2 } from \"./waku2_codec.js\";\nexport class RawEnr extends Map {\n seq;\n signature;\n constructor(kvs = {}, seq = BigInt(1), signature) {\n super(Object.entries(kvs));\n this.seq = seq;\n this.signature = signature;\n }\n set(k, v) {\n this.signature = undefined;\n this.seq++;\n return super.set(k, v);\n }\n get id() {\n const id = this.get(\"id\");\n if (!id)\n throw new Error(\"id not found.\");\n return bytesToUtf8(id);\n }\n get publicKey() {\n switch (this.id) {\n case \"v4\":\n return this.get(\"secp256k1\");\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n get rs() {\n const rs = this.get(\"rs\");\n if (!rs)\n return undefined;\n return decodeRelayShard(rs);\n }\n get rsv() {\n const rsv = this.get(\"rsv\");\n if (!rsv)\n return undefined;\n return decodeRelayShard(rsv);\n }\n get ip() {\n return getStringValue(this, \"ip\", \"ip4\");\n }\n set ip(ip) {\n setStringValue(this, \"ip\", \"ip4\", ip);\n }\n get tcp() {\n return getNumberAsStringValue(this, \"tcp\", \"tcp\");\n }\n set tcp(port) {\n setNumberAsStringValue(this, \"tcp\", \"tcp\", port);\n }\n get udp() {\n return getNumberAsStringValue(this, \"udp\", \"udp\");\n }\n set udp(port) {\n setNumberAsStringValue(this, \"udp\", \"udp\", port);\n }\n get ip6() {\n return getStringValue(this, \"ip6\", \"ip6\");\n }\n set ip6(ip) {\n setStringValue(this, \"ip6\", \"ip6\", ip);\n }\n get tcp6() {\n return getNumberAsStringValue(this, \"tcp6\", \"tcp\");\n }\n set tcp6(port) {\n setNumberAsStringValue(this, \"tcp6\", \"tcp\", port);\n }\n get udp6() {\n return getNumberAsStringValue(this, \"udp6\", \"udp\");\n }\n set udp6(port) {\n setNumberAsStringValue(this, \"udp6\", \"udp\", port);\n }\n /**\n * Get the `multiaddrs` field from ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.getLocationMultiaddr } should be preferred.\n *\n * The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.\n */\n get multiaddrs() {\n const raw = this.get(\"multiaddrs\");\n if (raw)\n return decodeMultiaddrs(raw);\n return;\n }\n /**\n * Set the `multiaddrs` field on the ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.setLocationMultiaddr } should be preferred.\n * The multiaddresses stored in this field must be location multiaddresses,\n * ie, without a peer id.\n */\n set multiaddrs(multiaddrs) {\n deleteUndefined(this, \"multiaddrs\", multiaddrs, encodeMultiaddrs);\n }\n /**\n * Get the `waku2` field from ENR.\n */\n get waku2() {\n const raw = this.get(\"waku2\");\n if (raw)\n return decodeWaku2(raw[0]);\n return;\n }\n /**\n * Set the `waku2` field on the ENR.\n */\n set waku2(waku2) {\n deleteUndefined(this, \"waku2\", waku2, (w) => new Uint8Array([encodeWaku2(w)]));\n }\n}\nfunction getStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return convertToString(proto, raw);\n}\nfunction getNumberAsStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return Number(convertToString(proto, raw));\n}\nfunction setStringValue(map, key, proto, value) {\n deleteUndefined(map, key, value, convertToBytes.bind({}, proto));\n}\nfunction setNumberAsStringValue(map, key, proto, value) {\n setStringValue(map, key, proto, value?.toString(10));\n}\nfunction deleteUndefined(map, key, value, transform) {\n if (value !== undefined) {\n map.set(key, transform(value));\n }\n else {\n map.delete(key);\n }\n}\n//# sourceMappingURL=raw_enr.js.map","import * as secp from \"@noble/secp256k1\";\nimport { bytesToHex } from \"@waku/utils/bytes\";\nimport { keccak256 } from \"./crypto.js\";\nexport async function sign(privKey, msg) {\n return secp.sign(keccak256(msg), privKey, {\n der: false\n });\n}\nexport function nodeId(pubKey) {\n const publicKey = secp.Point.fromHex(pubKey);\n const uncompressedPubkey = publicKey.toRawBytes(false);\n return bytesToHex(keccak256(uncompressedPubkey.slice(1)));\n}\n//# sourceMappingURL=v4.js.map","import { Logger } from \"@waku/utils\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { keccak256, verifySignature } from \"./crypto.js\";\nimport { locationMultiaddrFromEnrFields } from \"./get_multiaddr.js\";\nimport { createPeerIdFromPublicKey } from \"./peer_id.js\";\nimport { RawEnr } from \"./raw_enr.js\";\nimport * as v4 from \"./v4.js\";\nconst log = new Logger(\"enr\");\nexport var TransportProtocol;\n(function (TransportProtocol) {\n TransportProtocol[\"TCP\"] = \"tcp\";\n TransportProtocol[\"UDP\"] = \"udp\";\n})(TransportProtocol || (TransportProtocol = {}));\nexport var TransportProtocolPerIpVersion;\n(function (TransportProtocolPerIpVersion) {\n TransportProtocolPerIpVersion[\"TCP4\"] = \"tcp4\";\n TransportProtocolPerIpVersion[\"UDP4\"] = \"udp4\";\n TransportProtocolPerIpVersion[\"TCP6\"] = \"tcp6\";\n TransportProtocolPerIpVersion[\"UDP6\"] = \"udp6\";\n})(TransportProtocolPerIpVersion || (TransportProtocolPerIpVersion = {}));\nexport class ENR extends RawEnr {\n static RECORD_PREFIX = \"enr:\";\n peerId;\n static async create(kvs = {}, seq = BigInt(1), signature) {\n const enr = new ENR(kvs, seq, signature);\n try {\n const publicKey = enr.publicKey;\n if (publicKey) {\n enr.peerId = await createPeerIdFromPublicKey(publicKey);\n }\n }\n catch (e) {\n log.error(\"Could not calculate peer id for ENR\", e);\n }\n return enr;\n }\n get nodeId() {\n switch (this.id) {\n case \"v4\":\n return this.publicKey ? v4.nodeId(this.publicKey) : undefined;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n getLocationMultiaddr = locationMultiaddrFromEnrFields.bind({}, this);\n get shardInfo() {\n if (this.rs && this.rsv) {\n log.warn(\"ENR contains both `rs` and `rsv` fields.\");\n }\n return this.rs || this.rsv;\n }\n setLocationMultiaddr(multiaddr) {\n const protoNames = multiaddr.protoNames();\n if (protoNames.length !== 2 &&\n protoNames[1] !== \"udp\" &&\n protoNames[1] !== \"tcp\") {\n throw new Error(\"Invalid multiaddr\");\n }\n const tuples = multiaddr.tuples();\n if (!tuples[0][1] || !tuples[1][1]) {\n throw new Error(\"Invalid multiaddr\");\n }\n // IPv4\n if (tuples[0][0] === 4) {\n this.set(\"ip\", tuples[0][1]);\n this.set(protoNames[1], tuples[1][1]);\n }\n else {\n this.set(\"ip6\", tuples[0][1]);\n this.set(protoNames[1] + \"6\", tuples[1][1]);\n }\n }\n getAllLocationMultiaddrs() {\n const multiaddrs = [];\n for (const protocol of Object.values(TransportProtocolPerIpVersion)) {\n const ma = this.getLocationMultiaddr(protocol);\n if (ma)\n multiaddrs.push(ma);\n }\n const _multiaddrs = this.multiaddrs ?? [];\n return multiaddrs.concat(_multiaddrs).map((ma) => {\n if (this.peerId) {\n return ma.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n return ma;\n });\n }\n get peerInfo() {\n const id = this.peerId;\n if (!id)\n return;\n return {\n id,\n multiaddrs: this.getAllLocationMultiaddrs()\n };\n }\n /**\n * Returns the full multiaddr from the ENR fields matching the provided\n * `protocol` parameter.\n * To return full multiaddrs from the `multiaddrs` ENR field,\n * use { @link ENR.getFullMultiaddrs }.\n *\n * @param protocol\n */\n getFullMultiaddr(protocol) {\n if (this.peerId) {\n const locationMultiaddr = this.getLocationMultiaddr(protocol);\n if (locationMultiaddr) {\n return locationMultiaddr.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n }\n return;\n }\n /**\n * Returns the full multiaddrs from the `multiaddrs` ENR field.\n */\n getFullMultiaddrs() {\n if (this.peerId && this.multiaddrs) {\n const peerId = this.peerId;\n return this.multiaddrs.map((ma) => {\n return ma.encapsulate(`/p2p/${peerId.toString()}`);\n });\n }\n return [];\n }\n verify(data, signature) {\n if (!this.get(\"id\") || this.id !== \"v4\") {\n throw new Error(ERR_INVALID_ID);\n }\n if (!this.publicKey) {\n throw new Error(\"Failed to verify ENR: No public key\");\n }\n return verifySignature(signature, keccak256(data), this.publicKey);\n }\n async sign(data, privateKey) {\n switch (this.id) {\n case \"v4\":\n this.signature = await v4.sign(privateKey, data);\n break;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n return this.signature;\n }\n}\n//# sourceMappingURL=enr.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from \"@libp2p/crypto/keys\";\nimport { supportedKeys } from \"@libp2p/crypto/keys\";\nimport { peerIdFromKeys } from \"@libp2p/peer-id\";\nexport function createPeerIdFromPublicKey(publicKey) {\n const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);\n return peerIdFromKeys(_publicKey.bytes, undefined);\n}\nexport function getPublicKeyFromPeerId(peerId) {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n return unmarshalPublicKey(peerId.publicKey).marshal();\n}\n// Only used in tests\nexport async function getPrivateKeyFromPeerId(peerId) {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n if (!peerId.privateKey) {\n throw new Error(\"Private key not present on peer id\");\n }\n const privateKey = await unmarshalPrivateKey(peerId.privateKey);\n return privateKey.marshal();\n}\n//# sourceMappingURL=peer_id.js.map","\"use strict\";\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\nconst LogLevels = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\nimport { version } from \"./_version\";\nlet _globalLogger = null;\nfunction _checkNormalize() {\n try {\n const missing = [];\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n }\n ;\n }\n catch (error) {\n missing.push(form);\n }\n });\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\");\n }\n }\n catch (error) {\n return error.message;\n }\n return null;\n}\nconst _normalizeError = _checkNormalize();\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[\"DEBUG\"] = \"DEBUG\";\n LogLevel[\"INFO\"] = \"INFO\";\n LogLevel[\"WARNING\"] = \"WARNING\";\n LogLevel[\"ERROR\"] = \"ERROR\";\n LogLevel[\"OFF\"] = \"OFF\";\n})(LogLevel || (LogLevel = {}));\nexport var ErrorCode;\n(function (ErrorCode) {\n ///////////////////\n // Generic Errors\n // Unknown Error\n ErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n // Not Implemented\n ErrorCode[\"NOT_IMPLEMENTED\"] = \"NOT_IMPLEMENTED\";\n // Unsupported Operation\n // - operation\n ErrorCode[\"UNSUPPORTED_OPERATION\"] = \"UNSUPPORTED_OPERATION\";\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n ErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n // Some sort of bad response from the server\n ErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n // Timeout\n ErrorCode[\"TIMEOUT\"] = \"TIMEOUT\";\n ///////////////////\n // Operational Errors\n // Buffer Overrun\n ErrorCode[\"BUFFER_OVERRUN\"] = \"BUFFER_OVERRUN\";\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n ErrorCode[\"NUMERIC_FAULT\"] = \"NUMERIC_FAULT\";\n ///////////////////\n // Argument Errors\n // Missing new operator to an object\n // - name: The name of the class\n ErrorCode[\"MISSING_NEW\"] = \"MISSING_NEW\";\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n ErrorCode[\"INVALID_ARGUMENT\"] = \"INVALID_ARGUMENT\";\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"MISSING_ARGUMENT\"] = \"MISSING_ARGUMENT\";\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"UNEXPECTED_ARGUMENT\"] = \"UNEXPECTED_ARGUMENT\";\n ///////////////////\n // Blockchain Errors\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n ErrorCode[\"CALL_EXCEPTION\"] = \"CALL_EXCEPTION\";\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n ErrorCode[\"INSUFFICIENT_FUNDS\"] = \"INSUFFICIENT_FUNDS\";\n // Nonce has already been used\n // - transaction: the transaction attempted\n ErrorCode[\"NONCE_EXPIRED\"] = \"NONCE_EXPIRED\";\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n ErrorCode[\"REPLACEMENT_UNDERPRICED\"] = \"REPLACEMENT_UNDERPRICED\";\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n ErrorCode[\"UNPREDICTABLE_GAS_LIMIT\"] = \"UNPREDICTABLE_GAS_LIMIT\";\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n ErrorCode[\"TRANSACTION_REPLACED\"] = \"TRANSACTION_REPLACED\";\n ///////////////////\n // Interaction Errors\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ErrorCode[\"ACTION_REJECTED\"] = \"ACTION_REJECTED\";\n})(ErrorCode || (ErrorCode = {}));\n;\nconst HEX = \"0123456789abcdef\";\nexport class Logger {\n constructor(version) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n _log(logLevel, args) {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) {\n return;\n }\n console.log.apply(console, args);\n }\n debug(...args) {\n this._log(Logger.levels.DEBUG, args);\n }\n info(...args) {\n this._log(Logger.levels.INFO, args);\n }\n warn(...args) {\n this._log(Logger.levels.WARNING, args);\n }\n makeError(message, code, params) {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, {});\n }\n if (!code) {\n code = Logger.errors.UNKNOWN_ERROR;\n }\n if (!params) {\n params = {};\n }\n const messageDetails = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n }\n else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n }\n catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${code}`);\n messageDetails.push(`version=${this.version}`);\n const reason = message;\n let url = \"\";\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n switch (fault) {\n case \"overflow\":\n case \"underflow\":\n case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\":\n case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n // @TODO: Any??\n const error = new Error(message);\n error.reason = reason;\n error.code = code;\n Object.keys(params).forEach(function (key) {\n error[key] = params[key];\n });\n return error;\n }\n throwError(message, code, params) {\n throw this.makeError(message, code, params);\n }\n throwArgumentError(message, name, value) {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n assert(condition, message, code, params) {\n if (!!condition) {\n return;\n }\n this.throwError(message, code, params);\n }\n assertArgument(condition, message, name, value) {\n if (!!condition) {\n return;\n }\n this.throwArgumentError(message, name, value);\n }\n checkNormalize(message) {\n if (message == null) {\n message = \"platform missing String.prototype.normalize\";\n }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n checkSafeUint53(value, message) {\n if (typeof (value) !== \"number\") {\n return;\n }\n if (message == null) {\n message = \"value not safe\";\n }\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n checkArgumentCount(count, expectedCount, message) {\n if (message) {\n message = \": \" + message;\n }\n else {\n message = \"\";\n }\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n checkNew(target, kind) {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n checkAbstract(target, kind) {\n if (target === kind) {\n this.throwError(\"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: \"new\" });\n }\n else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n static globalLogger() {\n if (!_globalLogger) {\n _globalLogger = new Logger(version);\n }\n return _globalLogger;\n }\n static setCensorship(censorship, permanent) {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n if (_permanentCensorErrors) {\n if (!censorship) {\n return;\n }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n static setLogLevel(logLevel) {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n static from(version) {\n return new Logger(version);\n }\n}\nLogger.errors = ErrorCode;\nLogger.levels = LogLevel;\n//# sourceMappingURL=index.js.map","export const version = \"logger/5.7.0\";\n//# sourceMappingURL=_version.js.map","export const version = \"bytes/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n///////////////////////////////\nfunction isHexable(value) {\n return !!(value.toHexString);\n}\nfunction addSlice(array) {\n if (array.slice) {\n return array;\n }\n array.slice = function () {\n const args = Array.prototype.slice.call(arguments);\n return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));\n };\n return array;\n}\nexport function isBytesLike(value) {\n return ((isHexString(value) && !(value.length % 2)) || isBytes(value));\n}\nfunction isInteger(value) {\n return (typeof (value) === \"number\" && value == value && (value % 1) === 0);\n}\nexport function isBytes(value) {\n if (value == null) {\n return false;\n }\n if (value.constructor === Uint8Array) {\n return true;\n }\n if (typeof (value) === \"string\") {\n return false;\n }\n if (!isInteger(value.length) || value.length < 0) {\n return false;\n }\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (!isInteger(v) || v < 0 || v >= 256) {\n return false;\n }\n }\n return true;\n}\nexport function arrayify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid arrayify value\");\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value = parseInt(String(value / 256));\n }\n if (result.length === 0) {\n result.push(0);\n }\n return addSlice(new Uint8Array(result));\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n value = value.toHexString();\n }\n if (isHexString(value)) {\n let hex = value.substring(2);\n if (hex.length % 2) {\n if (options.hexPad === \"left\") {\n hex = \"0\" + hex;\n }\n else if (options.hexPad === \"right\") {\n hex += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n const result = [];\n for (let i = 0; i < hex.length; i += 2) {\n result.push(parseInt(hex.substring(i, i + 2), 16));\n }\n return addSlice(new Uint8Array(result));\n }\n if (isBytes(value)) {\n return addSlice(new Uint8Array(value));\n }\n return logger.throwArgumentError(\"invalid arrayify value\", \"value\", value);\n}\nexport function concat(items) {\n const objects = items.map(item => arrayify(item));\n const length = objects.reduce((accum, item) => (accum + item.length), 0);\n const result = new Uint8Array(length);\n objects.reduce((offset, object) => {\n result.set(object, offset);\n return offset + object.length;\n }, 0);\n return addSlice(result);\n}\nexport function stripZeros(value) {\n let result = arrayify(value);\n if (result.length === 0) {\n return result;\n }\n // Find the first non-zero entry\n let start = 0;\n while (start < result.length && result[start] === 0) {\n start++;\n }\n // If we started with zeros, strip them\n if (start) {\n result = result.slice(start);\n }\n return result;\n}\nexport function zeroPad(value, length) {\n value = arrayify(value);\n if (value.length > length) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[0]);\n }\n const result = new Uint8Array(length);\n result.set(value, length - value.length);\n return addSlice(result);\n}\nexport function isHexString(value, length) {\n if (typeof (value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false;\n }\n if (length && value.length !== 2 + 2 * length) {\n return false;\n }\n return true;\n}\nconst HexCharacters = \"0123456789abcdef\";\nexport function hexlify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid hexlify value\");\n let hex = \"\";\n while (value) {\n hex = HexCharacters[value & 0xf] + hex;\n value = Math.floor(value / 16);\n }\n if (hex.length) {\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n return \"0x\" + hex;\n }\n return \"0x00\";\n }\n if (typeof (value) === \"bigint\") {\n value = value.toString(16);\n if (value.length % 2) {\n return (\"0x0\" + value);\n }\n return \"0x\" + value;\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n return value.toHexString();\n }\n if (isHexString(value)) {\n if (value.length % 2) {\n if (options.hexPad === \"left\") {\n value = \"0x0\" + value.substring(2);\n }\n else if (options.hexPad === \"right\") {\n value += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n return value.toLowerCase();\n }\n if (isBytes(value)) {\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n let v = value[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n }\n return logger.throwArgumentError(\"invalid hexlify value\", \"value\", value);\n}\n/*\nfunction unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {\n if (typeof(value) === \"string\" && value.length % 2 && value.substring(0, 2) === \"0x\") {\n return \"0x0\" + value.substring(2);\n }\n return value;\n}\n*/\nexport function hexDataLength(data) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n return null;\n }\n return (data.length - 2) / 2;\n}\nexport function hexDataSlice(data, offset, endOffset) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n logger.throwArgumentError(\"invalid hexData\", \"value\", data);\n }\n offset = 2 + 2 * offset;\n if (endOffset != null) {\n return \"0x\" + data.substring(offset, 2 + 2 * endOffset);\n }\n return \"0x\" + data.substring(offset);\n}\nexport function hexConcat(items) {\n let result = \"0x\";\n items.forEach((item) => {\n result += hexlify(item).substring(2);\n });\n return result;\n}\nexport function hexValue(value) {\n const trimmed = hexStripZeros(hexlify(value, { hexPad: \"left\" }));\n if (trimmed === \"0x\") {\n return \"0x0\";\n }\n return trimmed;\n}\nexport function hexStripZeros(value) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n value = value.substring(2);\n let offset = 0;\n while (offset < value.length && value[offset] === \"0\") {\n offset++;\n }\n return \"0x\" + value.substring(offset);\n}\nexport function hexZeroPad(value, length) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n else if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n if (value.length > 2 * length + 2) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[1]);\n }\n while (value.length < 2 * length + 2) {\n value = \"0x0\" + value.substring(2);\n }\n return value;\n}\nexport function splitSignature(signature) {\n const result = {\n r: \"0x\",\n s: \"0x\",\n _vs: \"0x\",\n recoveryParam: 0,\n v: 0,\n yParityAndS: \"0x\",\n compact: \"0x\"\n };\n if (isBytesLike(signature)) {\n let bytes = arrayify(signature);\n // Get the r, s and v\n if (bytes.length === 64) {\n // EIP-2098; pull the v from the top bit of s and clear it\n result.v = 27 + (bytes[32] >> 7);\n bytes[32] &= 0x7f;\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n }\n else if (bytes.length === 65) {\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n result.v = bytes[64];\n }\n else {\n logger.throwArgumentError(\"invalid signature string\", \"signature\", signature);\n }\n // Allow a recid to be used as the v\n if (result.v < 27) {\n if (result.v === 0 || result.v === 1) {\n result.v += 27;\n }\n else {\n logger.throwArgumentError(\"signature invalid v byte\", \"signature\", signature);\n }\n }\n // Compute recoveryParam from v\n result.recoveryParam = 1 - (result.v % 2);\n // Compute _vs from recoveryParam and s\n if (result.recoveryParam) {\n bytes[32] |= 0x80;\n }\n result._vs = hexlify(bytes.slice(32, 64));\n }\n else {\n result.r = signature.r;\n result.s = signature.s;\n result.v = signature.v;\n result.recoveryParam = signature.recoveryParam;\n result._vs = signature._vs;\n // If the _vs is available, use it to populate missing s, v and recoveryParam\n // and verify non-missing s, v and recoveryParam\n if (result._vs != null) {\n const vs = zeroPad(arrayify(result._vs), 32);\n result._vs = hexlify(vs);\n // Set or check the recid\n const recoveryParam = ((vs[0] >= 128) ? 1 : 0);\n if (result.recoveryParam == null) {\n result.recoveryParam = recoveryParam;\n }\n else if (result.recoveryParam !== recoveryParam) {\n logger.throwArgumentError(\"signature recoveryParam mismatch _vs\", \"signature\", signature);\n }\n // Set or check the s\n vs[0] &= 0x7f;\n const s = hexlify(vs);\n if (result.s == null) {\n result.s = s;\n }\n else if (result.s !== s) {\n logger.throwArgumentError(\"signature v mismatch _vs\", \"signature\", signature);\n }\n }\n // Use recid and v to populate each other\n if (result.recoveryParam == null) {\n if (result.v == null) {\n logger.throwArgumentError(\"signature missing v and recoveryParam\", \"signature\", signature);\n }\n else if (result.v === 0 || result.v === 1) {\n result.recoveryParam = result.v;\n }\n else {\n result.recoveryParam = 1 - (result.v % 2);\n }\n }\n else {\n if (result.v == null) {\n result.v = 27 + result.recoveryParam;\n }\n else {\n const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));\n if (result.recoveryParam !== recId) {\n logger.throwArgumentError(\"signature recoveryParam mismatch v\", \"signature\", signature);\n }\n }\n }\n if (result.r == null || !isHexString(result.r)) {\n logger.throwArgumentError(\"signature missing or invalid r\", \"signature\", signature);\n }\n else {\n result.r = hexZeroPad(result.r, 32);\n }\n if (result.s == null || !isHexString(result.s)) {\n logger.throwArgumentError(\"signature missing or invalid s\", \"signature\", signature);\n }\n else {\n result.s = hexZeroPad(result.s, 32);\n }\n const vs = arrayify(result.s);\n if (vs[0] >= 128) {\n logger.throwArgumentError(\"signature s out of range\", \"signature\", signature);\n }\n if (result.recoveryParam) {\n vs[0] |= 0x80;\n }\n const _vs = hexlify(vs);\n if (result._vs) {\n if (!isHexString(result._vs)) {\n logger.throwArgumentError(\"signature invalid _vs\", \"signature\", signature);\n }\n result._vs = hexZeroPad(result._vs, 32);\n }\n // Set or check the _vs\n if (result._vs == null) {\n result._vs = _vs;\n }\n else if (result._vs !== _vs) {\n logger.throwArgumentError(\"signature _vs mismatch v and s\", \"signature\", signature);\n }\n }\n result.yParityAndS = result._vs;\n result.compact = result.r + result.yParityAndS.substring(2);\n return result;\n}\nexport function joinSignature(signature) {\n signature = splitSignature(signature);\n return hexlify(concat([\n signature.r,\n signature.s,\n (signature.recoveryParam ? \"0x1c\" : \"0x1b\")\n ]));\n}\n//# sourceMappingURL=index.js.map","export const version = \"rlp/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\n//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { arrayify, hexlify, isBytesLike } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nfunction arrayifyInteger(value) {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\nfunction unarrayifyInteger(data, offset, length) {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\nfunction _encode(object) {\n if (Array.isArray(object)) {\n let payload = [];\n object.forEach(function (child) {\n payload = payload.concat(_encode(child));\n });\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length);\n return payload;\n }\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n return length.concat(payload);\n }\n if (!isBytesLike(object)) {\n logger.throwArgumentError(\"RLP object must be BytesLike\", \"object\", object);\n }\n const data = Array.prototype.slice.call(arrayify(object));\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n }\n else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n return length.concat(data);\n}\nexport function encode(object) {\n return hexlify(_encode(object));\n}\nfunction _decodeChildren(data, offset, childOffset, length) {\n const result = [];\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n result.push(decoded.result);\n childOffset += decoded.consumed;\n if (childOffset > offset + 1 + length) {\n logger.throwError(\"child data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n }\n return { consumed: (1 + length), result: result };\n}\n// returns { consumed: number, result: Object }\nfunction _decode(data, offset) {\n if (data.length === 0) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data short segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data long segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n }\n else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1, length);\n }\n else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result };\n }\n else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result };\n }\n return { consumed: 1, result: hexlify(data[offset]) };\n}\nexport function decode(data) {\n const bytes = arrayify(data);\n const decoded = _decode(bytes, 0);\n if (decoded.consumed !== bytes.length) {\n logger.throwArgumentError(\"invalid rlp data\", \"data\", data);\n }\n return decoded.result;\n}\n//# sourceMappingURL=index.js.map","import * as RLP from \"@ethersproject/rlp\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToHex, bytesToUtf8, hexToBytes } from \"@waku/utils/bytes\";\nimport { fromString } from \"uint8arrays/from-string\";\nimport { ENR } from \"./enr.js\";\nconst log = new Logger(\"enr:decoder\");\nexport class EnrDecoder {\n static fromString(encoded) {\n if (!encoded.startsWith(ENR.RECORD_PREFIX)) {\n throw new Error(`\"string encoded ENR must start with '${ENR.RECORD_PREFIX}'`);\n }\n return EnrDecoder.fromRLP(fromString(encoded.slice(4), \"base64url\"));\n }\n static fromRLP(encoded) {\n const decoded = RLP.decode(encoded).map(hexToBytes);\n return fromValues(decoded);\n }\n}\nasync function fromValues(values) {\n const { signature, seq, kvs } = checkValues(values);\n const obj = {};\n for (let i = 0; i < kvs.length; i += 2) {\n try {\n obj[bytesToUtf8(kvs[i])] = kvs[i + 1];\n }\n catch (e) {\n log.error(\"Failed to decode ENR key to UTF-8, skipping it\", kvs[i], e);\n }\n }\n const _seq = decodeSeq(seq);\n const enr = await ENR.create(obj, _seq, signature);\n checkSignature(seq, kvs, enr, signature);\n return enr;\n}\nfunction decodeSeq(seq) {\n // If seq is an empty array, translate as value 0\n if (!seq.length)\n return BigInt(0);\n return BigInt(\"0x\" + bytesToHex(seq));\n}\nfunction checkValues(values) {\n if (!Array.isArray(values)) {\n throw new Error(\"Decoded ENR must be an array\");\n }\n if (values.length % 2 !== 0) {\n throw new Error(\"Decoded ENR must have an even number of elements\");\n }\n const [signature, seq, ...kvs] = values;\n if (!signature || Array.isArray(signature)) {\n throw new Error(\"Decoded ENR invalid signature: must be a byte array\");\n }\n if (!seq || Array.isArray(seq)) {\n throw new Error(\"Decoded ENR invalid sequence number: must be a byte array\");\n }\n return { signature, seq, kvs };\n}\nfunction checkSignature(seq, kvs, enr, signature) {\n const rlpEncodedBytes = hexToBytes(RLP.encode([seq, ...kvs]));\n if (!enr.verify(rlpEncodedBytes, signature)) {\n throw new Error(\"Unable to verify ENR signature\");\n }\n}\n//# sourceMappingURL=decoder.js.map","const v4Regex = /^(\\d{1,3}\\.){3,3}\\d{1,3}$/\nconst v4Size = 4\nconst v6Regex = /^(::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i\nconst v6Size = 16\n\nexport const v4 = {\n name: 'v4',\n size: v4Size,\n isFormat: ip => v4Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n buff = buff || new Uint8Array(offset + v4Size)\n const max = ip.length\n let n = 0\n for (let i = 0; i < max;) {\n const c = ip.charCodeAt(i++)\n if (c === 46) { // \".\"\n buff[offset++] = n\n n = 0\n } else {\n n = n * 10 + (c - 48)\n }\n }\n buff[offset] = n\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`\n }\n}\n\nexport const v6 = {\n name: 'v6',\n size: v6Size,\n isFormat: ip => ip.length > 0 && v6Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n let end = offset + v6Size\n let fill = -1\n let hexN = 0\n let decN = 0\n let prevColon = true\n let useDec = false\n buff = buff || new Uint8Array(offset + v6Size)\n // Note: This algorithm needs to check if the offset\n // could exceed the buffer boundaries as it supports\n // non-standard compliant encodings that may go beyond\n // the boundary limits. if (offset < end) checks should\n // not be necessary...\n for (let i = 0; i < ip.length; i++) {\n let c = ip.charCodeAt(i)\n if (c === 58) { // :\n if (prevColon) {\n if (fill !== -1) {\n // Not Standard! (standard doesn't allow multiple ::)\n // We need to treat\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (offset < end) {\n // :: in the middle\n fill = offset\n }\n } else {\n // : ends the previous number\n if (useDec === true) {\n // Non-standard! (ipv4 should be at end only)\n // A ipv4 address should not be found anywhere else but at\n // the end. This codec also support putting characters\n // after the ipv4 address..\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n hexN = 0\n decN = 0\n }\n prevColon = true\n useDec = false\n } else if (c === 46) { // . indicates IPV4 notation\n if (offset < end) buff[offset] = decN\n offset++\n decN = 0\n hexN = 0\n prevColon = false\n useDec = true\n } else {\n prevColon = false\n if (c >= 97) {\n c -= 87 // a-f ... 97~102 -87 => 10~15\n } else if (c >= 65) {\n c -= 55 // A-F ... 65~70 -55 => 10~15\n } else {\n c -= 48 // 0-9 ... starting from charCode 48\n decN = decN * 10 + c\n }\n // We don't know yet if its a dec or hex number\n hexN = (hexN << 4) + c\n }\n }\n if (prevColon === false) {\n // Commiting last number\n if (useDec === true) {\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n } else if (fill === 0) {\n // Not Standard! (standard doesn't allow multiple ::)\n // This means that a : was found at the start AND end which means the\n // end needs to be treated as 0 entry...\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (fill !== -1) {\n // Non-standard! (standard doens't allow multiple ::)\n // Here we find that there has been a :: somewhere in the middle\n // and the end. To treat the end with priority we need to move all\n // written data two bytes to the right.\n offset += 2\n for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) {\n buff[i] = buff[i - 2]\n }\n buff[fill] = 0\n buff[fill + 1] = 0\n fill = offset\n }\n if (fill !== offset && fill !== -1) {\n // Move the written numbers to the end while filling the everything\n // \"fill\" to the bytes with zeros.\n if (offset > end - 2) {\n // Non Standard support, when the cursor exceeds bounds.\n offset = end - 2\n }\n while (end > fill) {\n buff[--end] = offset < end && offset > fill ? buff[--offset] : 0\n }\n } else {\n // Fill the rest with zeros\n while (offset < end) {\n buff[offset++] = 0\n }\n }\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n let result = ''\n for (let i = 0; i < v6Size; i += 2) {\n if (i !== 0) {\n result += ':'\n }\n result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16)\n }\n return result\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n}\n\nexport const name = 'ip'\nexport function sizeOf (ip) {\n if (v4.isFormat(ip)) return v4.size\n if (v6.isFormat(ip)) return v6.size\n throw Error(`Invalid ip address: ${ip}`)\n}\n\nexport function familyOf (string) {\n return sizeOf(string) === v4.size ? 1 : 2\n}\n\nexport function encode (ip, buff, offset) {\n offset = ~~offset\n const size = sizeOf(ip)\n if (typeof buff === 'function') {\n buff = buff(offset + size)\n }\n if (size === v4.size) {\n return v4.encode(ip, buff, offset)\n }\n return v6.encode(ip, buff, offset)\n}\n\nexport function decode (buff, offset, length) {\n offset = ~~offset\n length = length || (buff.length - offset)\n if (length === v4.size) {\n return v4.decode(buff, offset, length)\n }\n if (length === v6.size) {\n return v6.decode(buff, offset, length)\n }\n throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`)\n}\n","export function toString (type) {\n switch (type) {\n case 1: return 'A'\n case 10: return 'NULL'\n case 28: return 'AAAA'\n case 18: return 'AFSDB'\n case 42: return 'APL'\n case 257: return 'CAA'\n case 60: return 'CDNSKEY'\n case 59: return 'CDS'\n case 37: return 'CERT'\n case 5: return 'CNAME'\n case 49: return 'DHCID'\n case 32769: return 'DLV'\n case 39: return 'DNAME'\n case 48: return 'DNSKEY'\n case 43: return 'DS'\n case 55: return 'HIP'\n case 13: return 'HINFO'\n case 45: return 'IPSECKEY'\n case 25: return 'KEY'\n case 36: return 'KX'\n case 29: return 'LOC'\n case 15: return 'MX'\n case 35: return 'NAPTR'\n case 2: return 'NS'\n case 47: return 'NSEC'\n case 50: return 'NSEC3'\n case 51: return 'NSEC3PARAM'\n case 12: return 'PTR'\n case 46: return 'RRSIG'\n case 17: return 'RP'\n case 24: return 'SIG'\n case 6: return 'SOA'\n case 99: return 'SPF'\n case 33: return 'SRV'\n case 44: return 'SSHFP'\n case 32768: return 'TA'\n case 249: return 'TKEY'\n case 52: return 'TLSA'\n case 250: return 'TSIG'\n case 16: return 'TXT'\n case 252: return 'AXFR'\n case 251: return 'IXFR'\n case 41: return 'OPT'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + type\n}\n\nexport function toType (name) {\n switch (name.toUpperCase()) {\n case 'A': return 1\n case 'NULL': return 10\n case 'AAAA': return 28\n case 'AFSDB': return 18\n case 'APL': return 42\n case 'CAA': return 257\n case 'CDNSKEY': return 60\n case 'CDS': return 59\n case 'CERT': return 37\n case 'CNAME': return 5\n case 'DHCID': return 49\n case 'DLV': return 32769\n case 'DNAME': return 39\n case 'DNSKEY': return 48\n case 'DS': return 43\n case 'HIP': return 55\n case 'HINFO': return 13\n case 'IPSECKEY': return 45\n case 'KEY': return 25\n case 'KX': return 36\n case 'LOC': return 29\n case 'MX': return 15\n case 'NAPTR': return 35\n case 'NS': return 2\n case 'NSEC': return 47\n case 'NSEC3': return 50\n case 'NSEC3PARAM': return 51\n case 'PTR': return 12\n case 'RRSIG': return 46\n case 'RP': return 17\n case 'SIG': return 24\n case 'SOA': return 6\n case 'SPF': return 99\n case 'SRV': return 33\n case 'SSHFP': return 44\n case 'TA': return 32768\n case 'TKEY': return 249\n case 'TLSA': return 52\n case 'TSIG': return 250\n case 'TXT': return 16\n case 'AXFR': return 252\n case 'IXFR': return 251\n case 'OPT': return 41\n case 'ANY': return 255\n case '*': return 255\n }\n if (name.toUpperCase().startsWith('UNKNOWN_')) return parseInt(name.slice(8))\n return 0\n}\n","/*\n * Traditional DNS header RCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml\n */\n\nexport function toString (rcode) {\n switch (rcode) {\n case 0: return 'NOERROR'\n case 1: return 'FORMERR'\n case 2: return 'SERVFAIL'\n case 3: return 'NXDOMAIN'\n case 4: return 'NOTIMP'\n case 5: return 'REFUSED'\n case 6: return 'YXDOMAIN'\n case 7: return 'YXRRSET'\n case 8: return 'NXRRSET'\n case 9: return 'NOTAUTH'\n case 10: return 'NOTZONE'\n case 11: return 'RCODE_11'\n case 12: return 'RCODE_12'\n case 13: return 'RCODE_13'\n case 14: return 'RCODE_14'\n case 15: return 'RCODE_15'\n }\n return 'RCODE_' + rcode\n}\n\nexport function toRcode (code) {\n switch (code.toUpperCase()) {\n case 'NOERROR': return 0\n case 'FORMERR': return 1\n case 'SERVFAIL': return 2\n case 'NXDOMAIN': return 3\n case 'NOTIMP': return 4\n case 'REFUSED': return 5\n case 'YXDOMAIN': return 6\n case 'YXRRSET': return 7\n case 'NXRRSET': return 8\n case 'NOTAUTH': return 9\n case 'NOTZONE': return 10\n case 'RCODE_11': return 11\n case 'RCODE_12': return 12\n case 'RCODE_13': return 13\n case 'RCODE_14': return 14\n case 'RCODE_15': return 15\n }\n return 0\n}\n","/*\n * Traditional DNS header OPCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5\n */\n\nexport function toString (opcode) {\n switch (opcode) {\n case 0: return 'QUERY'\n case 1: return 'IQUERY'\n case 2: return 'STATUS'\n case 3: return 'OPCODE_3'\n case 4: return 'NOTIFY'\n case 5: return 'UPDATE'\n case 6: return 'OPCODE_6'\n case 7: return 'OPCODE_7'\n case 8: return 'OPCODE_8'\n case 9: return 'OPCODE_9'\n case 10: return 'OPCODE_10'\n case 11: return 'OPCODE_11'\n case 12: return 'OPCODE_12'\n case 13: return 'OPCODE_13'\n case 14: return 'OPCODE_14'\n case 15: return 'OPCODE_15'\n }\n return 'OPCODE_' + opcode\n}\n\nexport function toOpcode (code) {\n switch (code.toUpperCase()) {\n case 'QUERY': return 0\n case 'IQUERY': return 1\n case 'STATUS': return 2\n case 'OPCODE_3': return 3\n case 'NOTIFY': return 4\n case 'UPDATE': return 5\n case 'OPCODE_6': return 6\n case 'OPCODE_7': return 7\n case 'OPCODE_8': return 8\n case 'OPCODE_9': return 9\n case 'OPCODE_10': return 10\n case 'OPCODE_11': return 11\n case 'OPCODE_12': return 12\n case 'OPCODE_13': return 13\n case 'OPCODE_14': return 14\n case 'OPCODE_15': return 15\n }\n return 0\n}\n","export function toString (klass) {\n switch (klass) {\n case 1: return 'IN'\n case 2: return 'CS'\n case 3: return 'CH'\n case 4: return 'HS'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + klass\n}\n\nexport function toClass (name) {\n switch (name.toUpperCase()) {\n case 'IN': return 1\n case 'CS': return 2\n case 'CH': return 3\n case 'HS': return 4\n case 'ANY': return 255\n }\n return 0\n}\n","export function toString (type) {\n switch (type) {\n // list at\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11\n case 1: return 'LLQ'\n case 2: return 'UL'\n case 3: return 'NSID'\n case 5: return 'DAU'\n case 6: return 'DHU'\n case 7: return 'N3U'\n case 8: return 'CLIENT_SUBNET'\n case 9: return 'EXPIRE'\n case 10: return 'COOKIE'\n case 11: return 'TCP_KEEPALIVE'\n case 12: return 'PADDING'\n case 13: return 'CHAIN'\n case 14: return 'KEY_TAG'\n case 26946: return 'DEVICEID'\n }\n if (type < 0) {\n return null\n }\n return `OPTION_${type}`\n}\n\nexport function toCode (name) {\n if (typeof name === 'number') {\n return name\n }\n if (!name) {\n return -1\n }\n switch (name.toUpperCase()) {\n case 'OPTION_0': return 0\n case 'LLQ': return 1\n case 'UL': return 2\n case 'NSID': return 3\n case 'OPTION_4': return 4\n case 'DAU': return 5\n case 'DHU': return 6\n case 'N3U': return 7\n case 'CLIENT_SUBNET': return 8\n case 'EXPIRE': return 9\n case 'COOKIE': return 10\n case 'TCP_KEEPALIVE': return 11\n case 'PADDING': return 12\n case 'CHAIN': return 13\n case 'KEY_TAG': return 14\n case 'DEVICEID': return 26946\n case 'OPTION_65535': return 65535\n }\n const m = name.match(/_(\\d+)$/)\n if (m) {\n return parseInt(m[1], 10)\n }\n return -1\n}\n","const SURROGATE_A = 0b1101100000000000\nconst SURROGATE_B = 0b1101110000000000\n\nexport const name = 'utf8'\n\nexport function encodingLength (str) {\n let len = 0\n const strLen = str.length\n for (let i = 0; i < strLen; i += 1) {\n const code = str.charCodeAt(i)\n if (code <= 0x7F) {\n len += 1\n } else if (code <= 0x07FF) {\n len += 2\n } else if ((code & 0xF800) !== SURROGATE_A) {\n len += 3\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n len += 3\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n len += 3\n } else {\n i = next\n len += 4\n }\n }\n }\n }\n return len\n}\n\nexport function encode (str, buf, offset) {\n const strLen = str.length\n if (offset === undefined || offset === null) {\n offset = 0\n }\n if (buf === undefined) {\n buf = new Uint8Array(encodingLength(str) + offset)\n }\n let off = offset\n for (let i = 0; i < strLen; i += 1) {\n let code = str.charCodeAt(i)\n if (code <= 0x7F) {\n buf[off++] = code\n } else if (code <= 0x07FF) {\n buf[off++] = 0b11000000 | ((code & 0b11111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b00000111111)\n } else if ((code & 0xF800) !== SURROGATE_A) {\n buf[off++] = 0b11100000 | ((code & 0b1111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b0000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b0000000000111111)\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n // Incorrectly started surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n // Incorrect surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n i = next\n code = 0b000010000000000000000 |\n ((code & 0b1111111111) << 10) |\n (nextCode & 0b1111111111)\n buf[off++] = 0b11110000 | ((code & 0b111000000000000000000) >> 18)\n buf[off++] = 0b10000000 | ((code & 0b000111111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b000000000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b000000000000000111111)\n }\n }\n }\n }\n encode.bytes = off - offset\n return buf\n}\nencode.bytes = 0\n\nexport function decode (buf, start, end) {\n let result = ''\n if (start === undefined || start === null) {\n start = 0\n }\n if (end === undefined || end === null) {\n end = buf.length\n }\n for (let offset = start; offset < end;) {\n const code = buf[offset++]\n let num\n if (code <= 128) {\n num = code\n } else if (code > 191 && code < 224) {\n num = ((code & 0b11111) << 6) | (buf[offset++] & 0b111111)\n } else if (code > 239 && code < 365) {\n num = (\n ((code & 0b111) << 18) |\n ((buf[offset++] & 0b111111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n ) - 0x10000\n const numA = SURROGATE_A | ((num >> 10) & 0b1111111111)\n result += String.fromCharCode(numA)\n num = SURROGATE_B | (num & 0b1111111111)\n } else {\n num = ((code & 0b1111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n }\n result += String.fromCharCode(num)\n }\n decode.bytes = end - start\n return result\n}\ndecode.bytes = 0\n","import * as utf8 from 'utf8-codec'\n\nexport const isU8Arr = input => input instanceof Uint8Array\n\nexport function bytelength (input) {\n return typeof input === 'string' ? utf8.encodingLength(input) : input.byteLength\n}\n\nexport function from (input) {\n if (input instanceof Uint8Array) {\n return input\n }\n if (Array.isArray(input)) {\n return new Uint8Array(input)\n }\n return utf8.encode(input)\n}\n\nexport function write (arr, str, start) {\n if (typeof str !== 'string') {\n throw new Error('unknown input type')\n }\n utf8.encode(str, arr, start)\n return utf8.encode.bytes\n}\n\nexport function toHex (buf, start, end) {\n let result = ''\n for (let offset = start; offset < end;) {\n const num = buf[offset++]\n const str = num.toString(16)\n result += (str.length === 1) ? '0' + str : str\n }\n return result\n}\n\nconst P_24 = Math.pow(2, 24)\nconst P_16 = Math.pow(2, 16)\nconst P_8 = Math.pow(2, 8)\nexport const readUInt32BE = (buf, offset) => buf[offset] * P_24 +\n buf[offset + 1] * P_16 +\n buf[offset + 2] * P_8 +\n buf[offset + 3]\n\nexport const readUInt16BE = (buf, offset) => (buf[offset] << 8) | buf[offset + 1]\nexport const writeUInt32BE = (buf, value, offset) => {\n value = +value\n buf[offset + 3] = value\n value = value >>> 8\n buf[offset + 2] = value\n value = value >>> 8\n buf[offset + 1] = value\n value = value >>> 8\n buf[offset] = value\n return offset + 4\n}\nexport const writeUInt16BE = (buf, value, offset) => {\n buf[offset] = value >> 8\n buf[offset + 1] = value & 0xFF\n return offset + 2\n}\n\nexport function copy (source, target, targetStart, sourceStart, sourceEnd) {\n if (targetStart < 0) {\n sourceStart -= targetStart\n targetStart = 0\n }\n\n if (sourceStart < 0) {\n sourceStart = 0\n }\n\n if (sourceEnd < 0) {\n return new Uint8Array(0)\n }\n\n if (targetStart >= target.length || sourceStart >= sourceEnd) {\n return 0\n }\n\n return _copyActual(source, target, targetStart, sourceStart, sourceEnd)\n}\n\nfunction _copyActual (source, target, targetStart, sourceStart, sourceEnd) {\n if (sourceEnd - sourceStart > target.length - targetStart) {\n sourceEnd = sourceStart + target.length - targetStart\n }\n\n let nb = sourceEnd - sourceStart\n const sourceLen = source.length - sourceStart\n if (nb > sourceLen) {\n nb = sourceLen\n }\n\n if (sourceStart !== 0 || sourceEnd < source.length) {\n source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb)\n }\n\n target.set(source, targetStart)\n\n return nb\n}\n","import * as ip from '@leichtgewicht/ip-codec'\nimport * as types from './types.mjs'\nimport * as rcodes from './rcodes.mjs'\nimport * as opcodes from './opcodes.mjs'\nimport * as classes from './classes.mjs'\nimport * as optioncodes from './optioncodes.mjs'\nimport * as b from './buffer_utils.mjs'\nimport { decode as toUtf8 } from 'utf8-codec'\n\nconst QUERY_FLAG = 0\nconst RESPONSE_FLAG = 1 << 15\nconst FLUSH_MASK = 1 << 15\nconst NOT_FLUSH_MASK = ~FLUSH_MASK\nconst QU_MASK = 1 << 15\nconst NOT_QU_MASK = ~QU_MASK\n\nfunction codec ({ bytes = 0, encode, decode, encodingLength }) {\n encode.bytes = bytes\n decode.bytes = bytes\n return {\n encode,\n decode,\n encodingLength: encodingLength || (() => bytes)\n }\n}\n\nexport const name = codec({\n encode (str, buf, offset) {\n if (!buf) buf = new Uint8Array(name.encodingLength(str))\n if (!offset) offset = 0\n const oldOffset = offset\n\n // strip leading and trailing .\n const n = str.replace(/^\\.|\\.$/gm, '')\n if (n.length) {\n const list = n.split('.')\n\n for (let i = 0; i < list.length; i++) {\n const len = b.write(buf, list[i], offset + 1)\n buf[offset] = len\n offset += len + 1\n }\n }\n\n buf[offset++] = 0\n\n name.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const list = []\n let oldOffset = offset\n let totalLength = 0\n let consumedBytes = 0\n let jumped = false\n\n while (true) {\n if (offset >= buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const len = buf[offset++]\n consumedBytes += jumped ? 0 : 1\n\n if (len === 0) {\n break\n } else if ((len & 0xc0) === 0) {\n if (offset + len > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n totalLength += len + 1\n if (totalLength > 254) {\n throw new Error('Cannot decode name (name too long)')\n }\n list.push(toUtf8(buf, offset, offset + len))\n offset += len\n consumedBytes += jumped ? 0 : len\n } else if ((len & 0xc0) === 0xc0) {\n if (offset + 1 > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const jumpOffset = b.readUInt16BE(buf, offset - 1) - 0xc000\n if (jumpOffset >= oldOffset) {\n // Allow only pointers to prior data. RFC 1035, section 4.1.4 states:\n // \"[...] an entire domain name or a list of labels at the end of a domain name\n // is replaced with a pointer to a prior occurance (sic) of the same name.\"\n throw new Error('Cannot decode name (bad pointer)')\n }\n offset = jumpOffset\n oldOffset = jumpOffset\n consumedBytes += jumped ? 0 : 1\n jumped = true\n } else {\n throw new Error('Cannot decode name (bad label)')\n }\n }\n\n name.decode.bytes = consumedBytes\n return list.length === 0 ? '.' : list.join('.')\n },\n encodingLength (n) {\n if (n === '.' || n === '..') return 1\n return b.bytelength(n.replace(/^\\.|\\.$/gm, '')) + 2\n }\n})\n\nconst string = codec({\n encode (s, buf, offset) {\n if (!buf) buf = new Uint8Array(string.encodingLength(s))\n if (!offset) offset = 0\n\n const len = b.write(buf, s, offset + 1)\n buf[offset] = len\n string.encode.bytes = len + 1\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = buf[offset]\n const s = toUtf8(buf, offset + 1, offset + 1 + len)\n string.decode.bytes = len + 1\n return s\n },\n encodingLength (s) {\n return b.bytelength(s) + 1\n }\n})\n\nconst header = codec({\n bytes: 12,\n encode (h, buf, offset) {\n if (!buf) buf = new Uint8Array(header.encodingLength(h))\n if (!offset) offset = 0\n\n const flags = (h.flags || 0) & 32767\n const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG\n\n b.writeUInt16BE(buf, h.id || 0, offset)\n b.writeUInt16BE(buf, flags | type, offset + 2)\n b.writeUInt16BE(buf, h.questions.length, offset + 4)\n b.writeUInt16BE(buf, h.answers.length, offset + 6)\n b.writeUInt16BE(buf, h.authorities.length, offset + 8)\n b.writeUInt16BE(buf, h.additionals.length, offset + 10)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n if (buf.length < 12) throw new Error('Header must be 12 bytes')\n const flags = b.readUInt16BE(buf, offset + 2)\n\n return {\n id: b.readUInt16BE(buf, offset),\n type: flags & RESPONSE_FLAG ? 'response' : 'query',\n flags: flags & 32767,\n flag_qr: ((flags >> 15) & 0x1) === 1,\n opcode: opcodes.toString((flags >> 11) & 0xf),\n flag_aa: ((flags >> 10) & 0x1) === 1,\n flag_tc: ((flags >> 9) & 0x1) === 1,\n flag_rd: ((flags >> 8) & 0x1) === 1,\n flag_ra: ((flags >> 7) & 0x1) === 1,\n flag_z: ((flags >> 6) & 0x1) === 1,\n flag_ad: ((flags >> 5) & 0x1) === 1,\n flag_cd: ((flags >> 4) & 0x1) === 1,\n rcode: rcodes.toString(flags & 0xf),\n questions: new Array(b.readUInt16BE(buf, offset + 4)),\n answers: new Array(b.readUInt16BE(buf, offset + 6)),\n authorities: new Array(b.readUInt16BE(buf, offset + 8)),\n additionals: new Array(b.readUInt16BE(buf, offset + 10))\n }\n },\n encodingLength () {\n return 12\n }\n})\n\nconst runknown = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(runknown.encodingLength(data))\n if (!offset) offset = 0\n\n const dLen = data.length\n b.writeUInt16BE(buf, dLen, offset)\n b.copy(data, buf, offset + 2, 0, dLen)\n\n runknown.encode.bytes = dLen + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const data = buf.slice(offset + 2, offset + 2 + len)\n runknown.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return data.length + 2\n }\n})\n\nconst rns = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rns.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rns.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const dd = name.decode(buf, offset + 2)\n\n rns.decode.bytes = len + 2\n return dd\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsoa = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsoa.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n name.encode(data.mname, buf, offset)\n offset += name.encode.bytes\n name.encode(data.rname, buf, offset)\n offset += name.encode.bytes\n b.writeUInt32BE(buf, data.serial || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.refresh || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.retry || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.expire || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.minimum || 0, offset)\n offset += 4\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rsoa.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.rname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.serial = b.readUInt32BE(buf, offset)\n offset += 4\n data.refresh = b.readUInt32BE(buf, offset)\n offset += 4\n data.retry = b.readUInt32BE(buf, offset)\n offset += 4\n data.expire = b.readUInt32BE(buf, offset)\n offset += 4\n data.minimum = b.readUInt32BE(buf, offset)\n offset += 4\n\n rsoa.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)\n }\n})\n\nconst rtxt = codec({\n encode (data, buf, offset) {\n if (!Array.isArray(data)) data = [data]\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] === 'string') {\n data[i] = b.from(data[i])\n }\n if (!b.isU8Arr(data[i])) {\n throw new Error('Must be a Buffer')\n }\n }\n\n if (!buf) buf = new Uint8Array(rtxt.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n\n data.forEach(function (d) {\n buf[offset++] = d.length\n b.copy(d, buf, offset, 0, d.length)\n offset += d.length\n })\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rtxt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n let remaining = b.readUInt16BE(buf, offset)\n offset += 2\n\n const data = []\n while (remaining > 0) {\n const len = buf[offset++]\n --remaining\n if (remaining < len) {\n throw new Error('Buffer overflow')\n }\n data.push(buf.slice(offset, offset + len))\n offset += len\n remaining -= len\n }\n\n rtxt.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!Array.isArray(data)) data = [data]\n let length = 2\n data.forEach(function (buf) {\n if (typeof buf === 'string') {\n length += b.bytelength(buf) + 1\n } else {\n length += buf.length + 1\n }\n })\n return length\n }\n})\n\nconst rnull = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rnull.encodingLength(data))\n if (!offset) offset = 0\n\n if (typeof data === 'string') data = b.from(data)\n if (!data) data = new Uint8Array(0)\n\n const oldOffset = offset\n offset += 2\n\n const len = data.length\n b.copy(data, buf, offset, 0, len)\n offset += len\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rnull.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n const len = b.readUInt16BE(buf, offset)\n\n offset += 2\n\n const data = buf.slice(offset, offset + len)\n offset += len\n\n rnull.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!data) return 2\n return (b.isU8Arr(data) ? data.length : b.bytelength(data)) + 2\n }\n})\n\nconst rhinfo = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rhinfo.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n string.encode(data.cpu, buf, offset)\n offset += string.encode.bytes\n string.encode(data.os, buf, offset)\n offset += string.encode.bytes\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rhinfo.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.cpu = string.decode(buf, offset)\n offset += string.decode.bytes\n data.os = string.decode(buf, offset)\n offset += string.decode.bytes\n rhinfo.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2\n }\n})\n\nconst rptr = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rptr.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rptr.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const data = name.decode(buf, offset + 2)\n rptr.decode.bytes = name.decode.bytes + 2\n return data\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsrv = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsrv.encodingLength(data))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, data.priority || 0, offset + 2)\n b.writeUInt16BE(buf, data.weight || 0, offset + 4)\n b.writeUInt16BE(buf, data.port || 0, offset + 6)\n name.encode(data.target, buf, offset + 8)\n\n const len = name.encode.bytes + 6\n b.writeUInt16BE(buf, len, offset)\n\n rsrv.encode.bytes = len + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n\n const data = {}\n data.priority = b.readUInt16BE(buf, offset + 2)\n data.weight = b.readUInt16BE(buf, offset + 4)\n data.port = b.readUInt16BE(buf, offset + 6)\n data.target = name.decode(buf, offset + 8)\n\n rsrv.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return 8 + name.encodingLength(data.target)\n }\n})\n\nconst rcaa = codec({\n encode (data, buf, offset) {\n const len = rcaa.encodingLength(data)\n\n if (!buf) buf = new Uint8Array(rcaa.encodingLength(data))\n if (!offset) offset = 0\n\n if (data.issuerCritical) {\n data.flags = rcaa.ISSUER_CRITICAL\n }\n\n b.writeUInt16BE(buf, len - 2, offset)\n offset += 2\n buf[offset] = data.flags || 0\n offset += 1\n string.encode(data.tag, buf, offset)\n offset += string.encode.bytes\n b.write(buf, data.value, offset)\n offset += b.bytelength(data.value)\n\n rcaa.encode.bytes = len\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n\n const oldOffset = offset\n const data = {}\n data.flags = buf[offset]\n offset += 1\n data.tag = string.decode(buf, offset)\n offset += string.decode.bytes\n data.value = toUtf8(buf, offset, oldOffset + len)\n\n data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)\n\n rcaa.decode.bytes = len + 2\n\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2\n }\n})\n\nrcaa.ISSUER_CRITICAL = 1 << 7\n\nconst rmx = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rmx.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n b.writeUInt16BE(buf, data.preference || 0, offset)\n offset += 2\n name.encode(data.exchange, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rmx.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.preference = b.readUInt16BE(buf, offset)\n offset += 2\n data.exchange = name.decode(buf, offset)\n offset += name.decode.bytes\n\n rmx.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 4 + name.encodingLength(data.exchange)\n }\n})\n\nconst ra = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(ra.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 4, offset)\n offset += 2\n ip.v4.encode(host, buf, offset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v4.decode(buf, offset)\n return host\n },\n bytes: 6\n})\n\nconst raaaa = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(raaaa.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 16, offset)\n offset += 2\n ip.v6.encode(host, buf, offset)\n raaaa.encode.bytes = 18\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v6.decode(buf, offset)\n raaaa.decode.bytes = 18\n return host\n },\n bytes: 18\n})\n\nconst alloc = size => new Uint8Array(size)\n\nconst roption = codec({\n encode (option, buf, offset) {\n if (!buf) buf = new Uint8Array(roption.encodingLength(option))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const code = optioncodes.toCode(option.code)\n b.writeUInt16BE(buf, code, offset)\n offset += 2\n if (option.data) {\n b.writeUInt16BE(buf, option.data.length, offset)\n offset += 2\n b.copy(option.data, buf, offset)\n offset += option.data.length\n } else {\n switch (code) {\n // case 3: NSID. No encode makes sense.\n // case 5,6,7: Not implementable\n case 8: // ECS\n {\n // note: do IP math before calling\n const spl = option.sourcePrefixLength || 0\n const fam = option.family || ip.familyOf(option.ip, alloc)\n const ipBuf = ip.encode(option.ip, alloc)\n const ipLen = Math.ceil(spl / 8)\n b.writeUInt16BE(buf, ipLen + 4, offset)\n offset += 2\n b.writeUInt16BE(buf, fam, offset)\n offset += 2\n buf[offset++] = spl\n buf[offset++] = option.scopePrefixLength || 0\n\n b.copy(ipBuf, buf, offset, 0, ipLen)\n offset += ipLen\n }\n break\n // case 9: EXPIRE (experimental)\n // case 10: COOKIE. No encode makes sense.\n case 11: // KEEP-ALIVE\n if (option.timeout) {\n b.writeUInt16BE(buf, 2, offset)\n offset += 2\n b.writeUInt16BE(buf, option.timeout, offset)\n offset += 2\n } else {\n b.writeUInt16BE(buf, 0, offset)\n offset += 2\n }\n break\n case 12: // PADDING\n {\n const len = option.length || 0\n b.writeUInt16BE(buf, len, offset)\n offset += 2\n buf.fill(0, offset, offset + len)\n offset += len\n }\n break\n // case 13: CHAIN. Experimental.\n case 14: // KEY-TAG\n {\n const tagsLen = option.tags.length * 2\n b.writeUInt16BE(buf, tagsLen, offset)\n offset += 2\n for (const tag of option.tags) {\n b.writeUInt16BE(buf, tag, offset)\n offset += 2\n }\n }\n break\n default:\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n }\n\n roption.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const option = {}\n option.code = b.readUInt16BE(buf, offset)\n option.type = optioncodes.toString(option.code)\n offset += 2\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n option.data = buf.slice(offset, offset + len)\n switch (option.code) {\n // case 3: NSID. No decode makes sense.\n case 8: // ECS\n option.family = b.readUInt16BE(buf, offset)\n offset += 2\n option.sourcePrefixLength = buf[offset++]\n option.scopePrefixLength = buf[offset++]\n {\n const padded = new Uint8Array((option.family === 1) ? 4 : 16)\n b.copy(buf, padded, 0, offset, offset + len - 4)\n option.ip = ip.decode(padded)\n }\n break\n // case 12: Padding. No decode makes sense.\n case 11: // KEEP-ALIVE\n if (len > 0) {\n option.timeout = b.readUInt16BE(buf, offset)\n offset += 2\n }\n break\n case 14:\n option.tags = []\n for (let i = 0; i < len; i += 2) {\n option.tags.push(b.readUInt16BE(buf, offset))\n offset += 2\n }\n // don't worry about default. caller will use data if desired\n }\n\n roption.decode.bytes = len + 4\n return option\n },\n encodingLength (option) {\n if (option.data) {\n return option.data.length + 4\n }\n const code = optioncodes.toCode(option.code)\n switch (code) {\n case 8: // ECS\n {\n const spl = option.sourcePrefixLength || 0\n return Math.ceil(spl / 8) + 8\n }\n case 11: // KEEP-ALIVE\n return (typeof option.timeout === 'number') ? 6 : 4\n case 12: // PADDING\n return option.length + 4\n case 14: // KEY-TAG\n return 4 + (option.tags.length * 2)\n }\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n})\n\nconst ropt = codec({\n encode (options, buf, offset) {\n if (!buf) buf = new Uint8Array(ropt.encodingLength(options))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const rdlen = encodingLengthList(options, roption)\n b.writeUInt16BE(buf, rdlen, offset)\n offset = encodeList(options, roption, buf, offset + 2)\n\n ropt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const options = []\n let rdlen = b.readUInt16BE(buf, offset)\n offset += 2\n let o = 0\n while (rdlen > 0) {\n options[o++] = roption.decode(buf, offset)\n offset += roption.decode.bytes\n rdlen -= roption.decode.bytes\n }\n ropt.decode.bytes = offset - oldOffset\n return options\n },\n encodingLength (options) {\n return 2 + encodingLengthList(options || [], roption)\n }\n})\n\nconst rdnskey = codec({\n encode (key, buf, offset) {\n if (!buf) buf = new Uint8Array(rdnskey.encodingLength(key))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const keydata = key.key\n if (!b.isU8Arr(keydata)) {\n throw new Error('Key must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, key.flags, offset)\n offset += 2\n buf[offset] = rdnskey.PROTOCOL_DNSSEC\n offset += 1\n buf[offset] = key.algorithm\n offset += 1\n b.copy(keydata, buf, offset, 0, keydata.length)\n offset += keydata.length\n\n rdnskey.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rdnskey.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const key = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n key.flags = b.readUInt16BE(buf, offset)\n offset += 2\n if (buf[offset] !== rdnskey.PROTOCOL_DNSSEC) {\n throw new Error('Protocol must be 3')\n }\n offset += 1\n key.algorithm = buf[offset]\n offset += 1\n key.key = buf.slice(offset, oldOffset + length + 2)\n offset += key.key.length\n rdnskey.decode.bytes = offset - oldOffset\n return key\n },\n encodingLength (key) {\n return 6 + b.bytelength(key.key)\n }\n})\n\nrdnskey.PROTOCOL_DNSSEC = 3\nrdnskey.ZONE_KEY = 0x80\nrdnskey.SECURE_ENTRYPOINT = 0x8000\n\nconst rrrsig = codec({\n encode (sig, buf, offset) {\n if (!buf) buf = new Uint8Array(rrrsig.encodingLength(sig))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const signature = sig.signature\n if (!b.isU8Arr(signature)) {\n throw new Error('Signature must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, types.toType(sig.typeCovered), offset)\n offset += 2\n buf[offset] = sig.algorithm\n offset += 1\n buf[offset] = sig.labels\n offset += 1\n b.writeUInt32BE(buf, sig.originalTTL, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.expiration, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.inception, offset)\n offset += 4\n b.writeUInt16BE(buf, sig.keyTag, offset)\n offset += 2\n name.encode(sig.signersName, buf, offset)\n offset += name.encode.bytes\n b.copy(signature, buf, offset, 0, signature.length)\n offset += signature.length\n\n rrrsig.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrrsig.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const sig = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n sig.typeCovered = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n sig.algorithm = buf[offset]\n offset += 1\n sig.labels = buf[offset]\n offset += 1\n sig.originalTTL = b.readUInt32BE(buf, offset)\n offset += 4\n sig.expiration = b.readUInt32BE(buf, offset)\n offset += 4\n sig.inception = b.readUInt32BE(buf, offset)\n offset += 4\n sig.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n sig.signersName = name.decode(buf, offset)\n offset += name.decode.bytes\n sig.signature = buf.slice(offset, oldOffset + length + 2)\n offset += sig.signature.length\n rrrsig.decode.bytes = offset - oldOffset\n return sig\n },\n encodingLength (sig) {\n return 20 +\n name.encodingLength(sig.signersName) +\n b.bytelength(sig.signature)\n }\n})\nconst rrp = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rrp.encodingLength(data))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(data.mbox || '.', buf, offset)\n offset += name.encode.bytes\n name.encode(data.txt || '.', buf, offset)\n offset += name.encode.bytes\n rrp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrp.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mbox = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n data.txt = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n rrp.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 2 + name.encodingLength(data.mbox || '.') + name.encodingLength(data.txt || '.')\n }\n})\n\nconst typebitmap = codec({\n encode (typelist, buf, offset) {\n if (!buf) buf = new Uint8Array(typebitmap.encodingLength(typelist))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typesByWindow = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n if (typesByWindow[typeid >> 8] === undefined) {\n typesByWindow[typeid >> 8] = []\n }\n typesByWindow[typeid >> 8][(typeid >> 3) & 0x1F] |= 1 << (7 - (typeid & 0x7))\n }\n\n for (let i = 0; i < typesByWindow.length; i++) {\n if (typesByWindow[i] !== undefined) {\n const windowBuf = b.from(typesByWindow[i])\n buf[offset] = i\n offset += 1\n buf[offset] = windowBuf.length\n offset += 1\n b.copy(windowBuf, buf, offset, 0, windowBuf.length)\n offset += windowBuf.length\n }\n }\n\n typebitmap.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset, length) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typelist = []\n while (offset - oldOffset < length) {\n const window = buf[offset]\n offset += 1\n const windowLength = buf[offset]\n offset += 1\n for (let i = 0; i < windowLength; i++) {\n const b = buf[offset + i]\n for (let j = 0; j < 8; j++) {\n if (b & (1 << (7 - j))) {\n const typeid = types.toString((window << 8) | (i << 3) | j)\n typelist.push(typeid)\n }\n }\n }\n offset += windowLength\n }\n\n typebitmap.decode.bytes = offset - oldOffset\n return typelist\n },\n encodingLength (typelist) {\n const extents = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 0xFF)\n }\n\n let len = 0\n for (let i = 0; i < extents.length; i++) {\n if (extents[i] !== undefined) {\n len += 2 + Math.ceil((extents[i] + 1) / 8)\n }\n }\n\n return len\n }\n})\n\nconst rnsec = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(record.nextDomain, buf, offset)\n offset += name.encode.bytes\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.nextDomain = name.decode(buf, offset)\n offset += name.decode.bytes\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 2 +\n name.encodingLength(record.nextDomain) +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rnsec3 = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec3.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const salt = record.salt\n if (!b.isU8Arr(salt)) {\n throw new Error('salt must be a Buffer')\n }\n\n const nextDomain = record.nextDomain\n if (!b.isU8Arr(nextDomain)) {\n throw new Error('nextDomain must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.flags\n offset += 1\n b.writeUInt16BE(buf, record.iterations, offset)\n offset += 2\n buf[offset] = salt.length\n offset += 1\n b.copy(salt, buf, offset, 0, salt.length)\n offset += salt.length\n buf[offset] = nextDomain.length\n offset += 1\n b.copy(nextDomain, buf, offset, 0, nextDomain.length)\n offset += nextDomain.length\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec3.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec3.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.algorithm = buf[offset]\n offset += 1\n record.flags = buf[offset]\n offset += 1\n record.iterations = b.readUInt16BE(buf, offset)\n offset += 2\n const saltLength = buf[offset]\n offset += 1\n record.salt = buf.slice(offset, offset + saltLength)\n offset += saltLength\n const hashLength = buf[offset]\n offset += 1\n record.nextDomain = buf.slice(offset, offset + hashLength)\n offset += hashLength\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec3.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 8 +\n record.salt.length +\n record.nextDomain.length +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rds = codec({\n encode (digest, buf, offset) {\n if (!buf) buf = new Uint8Array(rds.encodingLength(digest))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digestdata = digest.digest\n if (!b.isU8Arr(digestdata)) {\n throw new Error('Digest must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, digest.keyTag, offset)\n offset += 2\n buf[offset] = digest.algorithm\n offset += 1\n buf[offset] = digest.digestType\n offset += 1\n b.copy(digestdata, buf, offset, 0, digestdata.length)\n offset += digestdata.length\n\n rds.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rds.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digest = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n digest.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n digest.algorithm = buf[offset]\n offset += 1\n digest.digestType = buf[offset]\n offset += 1\n digest.digest = buf.slice(offset, oldOffset + length + 2)\n offset += digest.digest.length\n rds.decode.bytes = offset - oldOffset\n return digest\n },\n encodingLength (digest) {\n return 6 + b.bytelength(digest.digest)\n }\n})\n\nfunction renc (type) {\n switch (type.toUpperCase()) {\n case 'A': return ra\n case 'PTR': return rptr\n case 'CNAME': return rptr\n case 'DNAME': return rptr\n case 'TXT': return rtxt\n case 'NULL': return rnull\n case 'AAAA': return raaaa\n case 'SRV': return rsrv\n case 'HINFO': return rhinfo\n case 'CAA': return rcaa\n case 'NS': return rns\n case 'SOA': return rsoa\n case 'MX': return rmx\n case 'OPT': return ropt\n case 'DNSKEY': return rdnskey\n case 'RRSIG': return rrrsig\n case 'RP': return rrp\n case 'NSEC': return rnsec\n case 'NSEC3': return rnsec3\n case 'DS': return rds\n }\n return runknown\n}\n\nexport const answer = codec({\n encode (a, buf, offset) {\n if (!buf) buf = new Uint8Array(answer.encodingLength(a))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(a.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(a.type), offset)\n\n if (a.type.toUpperCase() === 'OPT') {\n if (a.name !== '.') {\n throw new Error('OPT name must be root.')\n }\n b.writeUInt16BE(buf, a.udpPayloadSize || 4096, offset + 2)\n buf[offset + 4] = a.extendedRcode || 0\n buf[offset + 5] = a.ednsVersion || 0\n b.writeUInt16BE(buf, a.flags || 0, offset + 6)\n\n offset += 8\n ropt.encode(a.options || [], buf, offset)\n offset += ropt.encode.bytes\n } else {\n let klass = classes.toClass(a.class === undefined ? 'IN' : a.class)\n if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit\n b.writeUInt16BE(buf, klass, offset + 2)\n b.writeUInt32BE(buf, a.ttl || 0, offset + 4)\n\n offset += 8\n const enc = renc(a.type)\n enc.encode(a.data, buf, offset)\n offset += enc.encode.bytes\n }\n\n answer.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const a = {}\n const oldOffset = offset\n\n a.name = name.decode(buf, offset)\n offset += name.decode.bytes\n a.type = types.toString(b.readUInt16BE(buf, offset))\n if (a.type === 'OPT') {\n a.udpPayloadSize = b.readUInt16BE(buf, offset + 2)\n a.extendedRcode = buf[offset + 4]\n a.ednsVersion = buf[offset + 5]\n a.flags = b.readUInt16BE(buf, offset + 6)\n a.flag_do = ((a.flags >> 15) & 0x1) === 1\n a.options = ropt.decode(buf, offset + 8)\n offset += 8 + ropt.decode.bytes\n } else {\n const klass = b.readUInt16BE(buf, offset + 2)\n a.ttl = b.readUInt32BE(buf, offset + 4)\n\n a.class = classes.toString(klass & NOT_FLUSH_MASK)\n a.flush = !!(klass & FLUSH_MASK)\n\n const enc = renc(a.type)\n a.data = enc.decode(buf, offset + 8)\n offset += 8 + enc.decode.bytes\n }\n\n answer.decode.bytes = offset - oldOffset\n return a\n },\n encodingLength (a) {\n const data = (a.data !== null && a.data !== undefined) ? a.data : a.options\n return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data)\n }\n})\n\nexport const question = codec({\n encode (q, buf, offset) {\n if (!buf) buf = new Uint8Array(question.encodingLength(q))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(q.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(q.type), offset)\n offset += 2\n\n b.writeUInt16BE(buf, classes.toClass(q.class === undefined ? 'IN' : q.class), offset)\n offset += 2\n\n question.encode.bytes = offset - oldOffset\n return q\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const q = {}\n\n q.name = name.decode(buf, offset)\n offset += name.decode.bytes\n\n q.type = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n q.class = classes.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n const qu = !!(q.class & QU_MASK)\n if (qu) q.class &= NOT_QU_MASK\n\n question.decode.bytes = offset - oldOffset\n return q\n },\n encodingLength (q) {\n return name.encodingLength(q.name) + 4\n }\n})\n\nexport {\n rsoa as soa,\n rtxt as txt,\n rnull as null,\n runknown as unknown,\n rns as ns,\n rhinfo as hinfo,\n rptr as ptr,\n rptr as cname,\n rptr as dname,\n rsrv as srv,\n rcaa as caa,\n rmx as mx,\n ra as a,\n raaaa as aaaa,\n roption as option,\n ropt as opt,\n rdnskey as dnskey,\n rrrsig as rrsig,\n rrp as rp,\n rnsec as nsec,\n rnsec3 as nsec3,\n rds as ds,\n renc as enc\n}\n\nexport const AUTHORITATIVE_ANSWER = 1 << 10\nexport const TRUNCATED_RESPONSE = 1 << 9\nexport const RECURSION_DESIRED = 1 << 8\nexport const RECURSION_AVAILABLE = 1 << 7\nexport const AUTHENTIC_DATA = 1 << 5\nexport const CHECKING_DISABLED = 1 << 4\nexport const DNSSEC_OK = 1 << 15\n\nexport const packet = {\n encode: function (result, buf, offset) {\n const allocing = !buf\n\n if (allocing) buf = new Uint8Array(encodingLength(result))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n if (!result.questions) result.questions = []\n if (!result.answers) result.answers = []\n if (!result.authorities) result.authorities = []\n if (!result.additionals) result.additionals = []\n\n header.encode(result, buf, offset)\n offset += header.encode.bytes\n\n offset = encodeList(result.questions, question, buf, offset)\n offset = encodeList(result.answers, answer, buf, offset)\n offset = encodeList(result.authorities, answer, buf, offset)\n offset = encodeList(result.additionals, answer, buf, offset)\n\n packet.encode.bytes = offset - oldOffset\n\n // just a quick sanity check\n if (allocing && encode.bytes !== buf.length) {\n return buf.slice(0, encode.bytes)\n }\n\n return buf\n },\n decode: function (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const result = header.decode(buf, offset)\n offset += header.decode.bytes\n\n offset = decodeList(result.questions, question, buf, offset)\n offset = decodeList(result.answers, answer, buf, offset)\n offset = decodeList(result.authorities, answer, buf, offset)\n offset = decodeList(result.additionals, answer, buf, offset)\n\n packet.decode.bytes = offset - oldOffset\n\n return result\n },\n encodingLength: function (result) {\n return header.encodingLength(result) +\n encodingLengthList(result.questions || [], question) +\n encodingLengthList(result.answers || [], answer) +\n encodingLengthList(result.authorities || [], answer) +\n encodingLengthList(result.additionals || [], answer)\n }\n}\npacket.encode.bytes = 0\npacket.decode.bytes = 0\n\nfunction sanitizeSingle (input, type) {\n if (input.questions) {\n throw new Error('Only one .question object expected instead of a .questions array!')\n }\n const sanitized = Object.assign({\n type\n }, input)\n if (sanitized.question) {\n sanitized.questions = [sanitized.question]\n delete sanitized.question\n }\n return sanitized\n}\n\nexport const query = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'query'), buf, offset)\n query.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n query.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'query'))\n }\n}\nquery.encode.bytes = 0\nquery.decode.bytes = 0\n\nexport const response = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'response'), buf, offset)\n response.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n response.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'response'))\n }\n}\nresponse.encode.bytes = 0\nresponse.decode.bytes = 0\n\nexport const encode = packet.encode\nexport const decode = packet.decode\nexport const encodingLength = packet.encodingLength\n\nexport function streamEncode (result) {\n const buf = encode(result)\n const combine = new Uint8Array(2 + buf.byteLength)\n b.writeUInt16BE(combine, buf.byteLength)\n b.copy(buf, combine, 2, 0, buf.length)\n streamEncode.bytes = combine.byteLength\n return combine\n}\nstreamEncode.bytes = 0\n\nexport function streamDecode (sbuf) {\n const len = b.readUInt16BE(sbuf, 0)\n if (sbuf.byteLength < len + 2) {\n // not enough data\n return null\n }\n const result = decode(sbuf.slice(2))\n streamDecode.bytes = decode.bytes\n return result\n}\nstreamDecode.bytes = 0\n\nexport function encodingLengthList (list, enc) {\n let len = 0\n for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i])\n return len\n}\n\nexport function encodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n enc.encode(list[i], buf, offset)\n offset += enc.encode.bytes\n }\n return offset\n}\n\nexport function decodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n list[i] = enc.decode(buf, offset)\n offset += enc.decode.bytes\n }\n return offset\n}\n","export const PREFERS_PADDING = 1\nexport const PREFERS_NO_PADDING = 2\n\nexport function make (name, charset, padding, paddingMode) {\n if (charset.length !== 64) {\n throw new Error(`Charset needs to be 64 characters long! (${charset.length})`)\n }\n const byCharCode = new Uint8Array(256)\n const byNum = new Uint8Array(64)\n for (let i = 0; i < 64; i += 1) {\n const code = charset.charCodeAt(i)\n if (code > 255) {\n throw new Error(`Character #${i} in charset [code=${code}, char=${charset.charAt(i)}] is too high! (max=255)`)\n }\n if (byCharCode[code] !== 0) {\n throw new Error(`Character [code=${code}, char=${charset.charAt(i)}] is more than once in the charset!`)\n }\n byCharCode[code] = i\n byNum[i] = code\n }\n const padCode = padding.charCodeAt(0)\n const codec = {\n name,\n encodingLength (str) {\n const strLen = str.length\n const len = strLen * 0.75 | 0\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n return len - 2\n }\n return len - 1\n }\n return len\n },\n encode (str, buffer, offset) {\n if (buffer === null || buffer === undefined) {\n buffer = new Uint8Array(codec.encodingLength(str))\n }\n if (offset === null || offset === undefined) {\n offset = 0\n }\n\n let strLen = str.length\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n strLen -= 2\n } else {\n strLen -= 1\n }\n }\n\n const padding = strLen % 4\n const safeLen = strLen - padding\n\n let off = offset\n let i = 0\n while (i < safeLen) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 18) |\n (byCharCode[str.charCodeAt(i + 1)] << 12) |\n (byCharCode[str.charCodeAt(i + 2)] << 6) |\n byCharCode[str.charCodeAt(i + 3)]\n buffer[off++] = code >> 16\n buffer[off++] = code >> 8\n buffer[off++] = code\n i += 4\n }\n\n if (padding === 3) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 10) |\n (byCharCode[str.charCodeAt(i + 1)] << 4) |\n (byCharCode[str.charCodeAt(i + 2)] >> 2)\n buffer[off++] = code >> 8\n buffer[off++] = code\n } else if (padding === 2) {\n buffer[off++] = (byCharCode[str.charCodeAt(i)] << 2) |\n (byCharCode[str.charCodeAt(i + 1)] >> 4)\n }\n\n codec.encode.bytes = off - offset\n return buffer\n },\n decode (buffer, start, end) {\n if (start === null || start === undefined) {\n start = 0\n }\n if (end === null || end === undefined) {\n end = buffer.length\n }\n\n const length = end - start\n const pad = length % 3\n const safeEnd = start + length - pad\n const codes = []\n for (let off = start; off < safeEnd; off += 3) {\n const num = (buffer[off] << 16) | ((buffer[off + 1] << 8)) | buffer[off + 2]\n codes.push(\n byNum[num >> 18 & 0x3F],\n byNum[num >> 12 & 0x3F],\n byNum[num >> 6 & 0x3F],\n byNum[num & 0x3F]\n )\n }\n\n if (pad === 2) {\n const num = (buffer[end - 2] << 8) + buffer[end - 1]\n codes.push(\n byNum[num >> 10],\n byNum[(num >> 4) & 0x3F],\n byNum[(num << 2) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode)\n }\n } else if (pad === 1) {\n const num = buffer[end - 1]\n codes.push(\n byNum[num >> 2],\n byNum[(num << 4) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode, padCode)\n }\n }\n\n codec.decode.bytes = length\n return String.fromCharCode.apply(String, codes)\n }\n }\n return codec\n}\n\nexport const base64 = make('base64', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', '=', PREFERS_PADDING)\n// https://datatracker.ietf.org/doc/html/rfc4648#section-5\nexport const base64URL = make('base64-url', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', '=', PREFERS_NO_PADDING)\n","let AbortError = typeof global !== 'undefined' ? global.AbortError : typeof window !== 'undefined' ? window.AbortError : null\nif (!AbortError) {\n AbortError = class AbortError extends Error {\n constructor (message = 'Request aborted.') {\n super(message)\n }\n }\n}\nAbortError.prototype.name = 'AbortError'\nAbortError.prototype.code = 'ABORT_ERR'\n\nconst URL = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL\n\nexport { AbortError, URL }\n\nexport class HTTPStatusError extends Error {\n constructor (uri, code, method) {\n super('status=' + code + ' while requesting ' + uri + ' [' + method + ']')\n this.uri = uri\n this.status = code\n this.method = method\n }\n\n toJSON () {\n return {\n code: this.code,\n uri: this.uri,\n status: this.status,\n method: this.method,\n endpoint: this.endpoint\n }\n }\n}\nHTTPStatusError.prototype.name = 'HTTPStatusError'\nHTTPStatusError.prototype.code = 'HTTP_STATUS'\n\nexport class ResponseError extends Error {\n constructor (message, cause) {\n super(message)\n this.cause = cause\n }\n\n toJSON () {\n return {\n message: this.message,\n endpoint: this.endpoint,\n code: this.code,\n cause: reduceError(this.cause)\n }\n }\n}\nResponseError.prototype.name = 'ResponseError'\nResponseError.prototype.code = 'RESPONSE_ERR'\n\nexport class TimeoutError extends Error {\n constructor (timeout) {\n super('Timeout (t=' + timeout + ').')\n this.timeout = timeout\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nTimeoutError.prototype.name = 'TimeoutError'\nTimeoutError.prototype.code = 'ETIMEOUT'\n\nconst v4Regex = /^((\\d{1,3}\\.){3,3}\\d{1,3})(:(\\d{2,5}))?$/\nconst v6Regex = /^((::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\\d{2,5}))?$/i\n\nexport function reduceError (err) {\n if (typeof err === 'string') {\n return {\n message: err\n }\n }\n try {\n const json = JSON.stringify(err)\n if (json !== '{}') {\n return JSON.parse(json)\n }\n } catch (e) {}\n const error = {\n message: String(err.message || err)\n }\n if (err.code !== undefined) {\n error.code = String(err.code)\n }\n return error\n}\n\nconst baseParts = /^(([a-z0-9]+:)\\/\\/)?([^/[\\s:]+|\\[[^\\]]+\\])?(:([^/\\s]+))?(\\/[^\\s]*)?(.*)$/\nconst httpFlags = /\\[(post|get|((ipv4|ipv6|name)=([^\\]]+)))\\]/ig\nconst updFlags = /\\[(((pk|name)=([^\\]]+)))\\]/ig\n\nexport function parseEndpoint (endpoint) {\n const parts = baseParts.exec(endpoint)\n const protocol = parts[2] || 'https:'\n const host = parts[3]\n const port = parts[5]\n const path = parts[6]\n const rest = parts[7]\n if (protocol === 'https:' || protocol === 'http:') {\n const flags = parseFlags(rest, httpFlags)\n return {\n name: flags.name,\n protocol,\n ipv4: flags.ipv4,\n ipv6: flags.ipv6,\n host,\n port,\n path,\n method: flags.post ? 'POST' : 'GET'\n }\n }\n if (protocol === 'udp:' || protocol === 'udp4:' || protocol === 'udp6:') {\n const flags = parseFlags(rest, updFlags)\n const v6Parts = /^\\[(.*)\\]$/.exec(host)\n if (v6Parts && protocol === 'udp4:') {\n throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${endpoint})`)\n }\n if (!v6Parts && protocol === 'udp6:') {\n throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${endpoint})`)\n }\n if (v6Parts) {\n return new UDP6Endpoint({ protocol: 'udp6:', ipv6: v6Parts[1], port, pk: flags.pk, name: flags.name })\n }\n return new UDP4Endpoint({ protocol: 'udp4:', ipv4: host, port, pk: flags.pk, name: flags.name })\n }\n throw new InvalidProtocolError(protocol, endpoint)\n}\n\nfunction parseFlags (rest, regex) {\n regex.lastIndex = 0\n const result = {}\n while (true) {\n const match = regex.exec(rest)\n if (!match) break\n if (match[2]) {\n result[match[3].toLowerCase()] = match[4]\n } else {\n result[match[1].toLowerCase()] = true\n }\n }\n return result\n}\n\nexport class InvalidProtocolError extends Error {\n constructor (protocol, endpoint) {\n super(`Invalid Endpoint: unsupported protocol \"${protocol}\" for endpoint: ${endpoint}, supported protocols: ${supportedProtocols.join(', ')}`)\n this.protocol = protocol\n this.endpoint = endpoint\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nInvalidProtocolError.prototype.name = 'InvalidProtocolError'\nInvalidProtocolError.prototype.code = 'EPROTOCOL'\n\nexport const supportedProtocols = ['http:', 'https:', 'udp4:', 'udp6:']\n\nexport class BaseEndpoint {\n constructor (opts, isHTTP) {\n this.name = opts.name || null\n this.protocol = opts.protocol\n const port = typeof opts.port === 'string' ? opts.port = parseInt(opts.port, 10) : opts.port\n if (port === undefined || port === null) {\n this.port = isHTTP\n ? (this.protocol === 'https:' ? 443 : 80)\n : (opts.pk ? 443 : 53)\n } else if (typeof port !== 'number' && !isNaN(port)) {\n throw new Error(`Invalid Endpoint: port \"${opts.port}\" needs to be a number: ${JSON.stringify(opts)}`)\n } else {\n this.port = port\n }\n }\n\n toJSON () {\n return this.toString()\n }\n}\n\nexport class UDPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(opts, false)\n this.pk = opts.pk || null\n }\n\n toString () {\n const port = this.port !== (this.pk ? 443 : 53) ? `:${this.port}` : ''\n const pk = this.pk ? ` [pk=${this.pk}]` : ''\n const name = this.name ? ` [name=${this.name}]` : ''\n return `udp://${this.ipv4 || `[${this.ipv6}]`}${port}${pk}${name}`\n }\n}\n\nexport class UDP4Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp4:' }, opts))\n if (!opts.ipv4 || typeof opts.ipv4 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv4 \"${opts.ipv4}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv4 = opts.ipv4\n }\n}\n\nexport class UDP6Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp6:' }, opts))\n if (!opts.ipv6 || typeof opts.ipv6 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv6 \"${opts.ipv6}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv6 = opts.ipv6\n }\n}\n\nfunction safeHost (host) {\n return v6Regex.test(host) && !v4Regex.test(host) ? `[${host}]` : host\n}\n\nexport class HTTPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'https:' }, opts), true)\n if (!opts.host) {\n if (opts.ipv4) {\n opts.host = opts.ipv4\n }\n if (opts.ipv6) {\n opts.host = `[${opts.ipv6}]`\n }\n }\n if (!opts.host || typeof opts.host !== 'string') {\n throw new Error(`Invalid Endpoint: host \"${opts.path}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.host = opts.host\n this.path = opts.path || '/dns-query'\n this.method = /^post$/i.test(opts.method) ? 'POST' : 'GET'\n this.ipv4 = opts.ipv4\n this.ipv6 = opts.ipv6\n if (!this.ipv6) {\n const v6Parts = v6Regex.exec(this.host)\n if (v6Parts) {\n this.ipv6 = v6Parts[1]\n }\n }\n if (!this.ipv4) {\n if (v4Regex.test(this.host)) {\n this.ipv4 = this.host\n }\n }\n const url = `${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`\n try {\n this.url = new URL(url)\n } catch (err) {\n throw new Error(err.message + ` [${url}]`)\n }\n }\n\n toString () {\n const protocol = this.protocol === 'https:' ? '' : 'http://'\n const port = this.port !== (this.protocol === 'https:' ? 443 : 80) ? `:${this.port}` : ''\n const method = this.method !== 'GET' ? ' [post]' : ''\n const path = this.path === '/dns-query' ? '' : this.path\n const name = this.name ? ` [name=${this.name}]` : ''\n const ipv4 = this.ipv4 && this.ipv4 !== this.host ? ` [ipv4=${this.ipv4}]` : ''\n const ipv6 = this.ipv6 && this.ipv6 !== this.host ? ` [ipv6=${this.ipv6}]` : ''\n return `${protocol}${safeHost(this.host)}${port}${path}${method}${ipv4}${ipv6}${name}`\n }\n}\n\nexport function toEndpoint (input) {\n let opts\n if (typeof input === 'string') {\n opts = parseEndpoint(input)\n } else {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error(`Can not convert ${input} to an endpoint`)\n } else if (input instanceof BaseEndpoint) {\n return input\n }\n opts = input\n }\n if (opts.protocol === null || opts.protocol === undefined) {\n opts.protocol = 'https:'\n }\n const protocol = opts.protocol\n if (protocol === 'udp4:') {\n return new UDP4Endpoint(opts)\n }\n if (protocol === 'udp6:') {\n return new UDP6Endpoint(opts)\n }\n if (protocol === 'https:' || protocol === 'http:') {\n return new HTTPEndpoint(opts)\n }\n throw new InvalidProtocolError(protocol, JSON.stringify(opts))\n}\n","/* global XMLHttpRequest, localStorage */\nimport * as utf8Codec from 'utf8-codec'\nimport { base64URL } from '@leichtgewicht/base64-codec'\nimport {\n AbortError,\n HTTPStatusError,\n TimeoutError,\n URL\n} from './common.mjs'\nconst contentType = 'application/dns-message'\n\nfunction noop () { }\n\nexport function queryDns () {\n throw new Error('Only \"doh\" endpoints are supported in the browser')\n}\n\nexport async function loadJSON (url, cache, timeout, abortSignal) {\n const cacheKey = cache ? cache.localStoragePrefix + cache.name : null\n if (cacheKey) {\n try {\n const cached = JSON.parse(localStorage.getItem(cacheKey))\n if (cached && cached.time > cache.maxTime) {\n return cached\n }\n } catch (err) {}\n }\n const { data } = await requestRaw(url, 'GET', null, timeout, abortSignal)\n const result = {\n time: Date.now(),\n data: JSON.parse(utf8Codec.decode(data))\n }\n if (cacheKey) {\n try {\n localStorage.setItem(cacheKey, JSON.stringify(result))\n } catch (err) {\n result.time = null\n }\n }\n return result\n}\n\nfunction requestRaw (url, method, data, timeout, abortSignal) {\n return new Promise((resolve, reject) => {\n const target = new URL(url)\n if (method === 'GET' && data) {\n target.search = '?dns=' + base64URL.decode(data)\n }\n const uri = target.toString()\n const xhr = new XMLHttpRequest()\n xhr.open(method, uri, true)\n xhr.setRequestHeader('Accept', contentType)\n if (method === 'POST') {\n xhr.setRequestHeader('Content-Type', contentType)\n }\n xhr.responseType = 'arraybuffer'\n xhr.timeout = timeout\n xhr.ontimeout = ontimeout\n xhr.onreadystatechange = onreadystatechange\n xhr.onerror = onerror\n xhr.onload = onload\n if (method === 'POST') {\n xhr.send(data)\n } else {\n xhr.send()\n }\n\n if (abortSignal) {\n abortSignal.addEventListener('abort', onabort)\n }\n\n function ontimeout () {\n finish(new TimeoutError(timeout))\n try {\n xhr.abort()\n } catch (e) { }\n }\n\n function onload () {\n if (xhr.status !== 200) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n } else {\n let buf\n if (typeof xhr.response === 'string') {\n buf = utf8Codec.encode(xhr.response)\n } else if (xhr.response instanceof Uint8Array) {\n buf = xhr.response\n } else if (Array.isArray(xhr.response) || xhr.response instanceof ArrayBuffer) {\n buf = new Uint8Array(xhr.response)\n } else {\n throw new Error('Unprocessable response ' + xhr.response)\n }\n finish(null, buf)\n }\n }\n\n function onreadystatechange () {\n if (xhr.readyState > 1 && xhr.status !== 200 && xhr.status !== 0) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n try {\n xhr.abort()\n } catch (e) { }\n }\n }\n\n let finish = function (error, data) {\n finish = noop\n if (abortSignal) {\n abortSignal.removeEventListener('abort', onabort)\n }\n if (error) {\n resolve({\n error,\n response: xhr\n })\n } else {\n resolve({\n data,\n response: xhr\n })\n }\n }\n\n function onerror () {\n finish(xhr.status === 200 ? new Error('Inexplicable XHR Error') : new HTTPStatusError(uri, xhr.status, method))\n }\n\n function onabort () {\n finish(new AbortError())\n try {\n xhr.abort()\n } catch (e) { }\n }\n })\n}\n\nexport function request (url, method, packet, timeout, abortSignal) {\n return requestRaw(url, method, packet, timeout, abortSignal)\n}\n\nexport function processResolvers (resolvers) {\n return resolvers.filter(resolver => resolver.cors || resolver.endpoint.cors)\n}\n","import * as packet from '@leichtgewicht/dns-packet'\nimport { toRcode } from '@leichtgewicht/dns-packet/rcodes.js'\nimport { decode } from 'utf8-codec'\nimport * as lib from './lib.mjs'\nimport { resolvers as backupResolvers } from './resolvers.mjs'\nimport {\n AbortError,\n ResponseError,\n URL,\n toEndpoint\n} from './common.mjs'\n\nexport {\n TimeoutError,\n HTTPStatusError,\n AbortError,\n ResponseError,\n BaseEndpoint,\n HTTPEndpoint,\n UDP4Endpoint,\n UDP6Endpoint,\n parseEndpoint,\n toEndpoint\n} from './common.mjs'\n\nexport const DNS_RCODE_ERROR = {\n 1: 'FormErr',\n 2: 'ServFail',\n 3: 'NXDomain',\n 4: 'NotImp',\n 5: 'Refused',\n 6: 'YXDomain',\n 7: 'YXRRSet',\n 8: 'NXRRSet',\n 9: 'NotAuth',\n 10: 'NotZone',\n 11: 'DSOTYPENI'\n}\n\nexport const DNS_RCODE_MESSAGE = {\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n 1: 'The name server was unable to interpret the query.',\n 2: 'The name server was unable to process this query due to a problem with the name server.',\n 3: 'Non-Existent Domain.',\n 4: 'The name server does not support the requested kind of query.',\n 5: 'The name server refuses to perform the specified operation for policy reasons.',\n 6: 'Name Exists when it should not.',\n 7: 'RR Set Exists when it should not.',\n 8: 'RR Set that should exist does not.',\n 9: 'Server Not Authoritative for zone / Not Authorized.',\n 10: 'Name not contained in zone.',\n 11: 'DSO-TYPE Not Implemented.'\n}\n\nexport class DNSRcodeError extends Error {\n constructor (rcode, question) {\n super(`${(DNS_RCODE_MESSAGE[rcode] || 'Undefined error.')} (rcode=${rcode}${DNS_RCODE_ERROR[rcode] ? `, error=${DNS_RCODE_ERROR[rcode]}` : ''}, question=${JSON.stringify(question)})`)\n this.rcode = rcode\n this.code = `DNS_RCODE_${rcode}`\n this.error = DNS_RCODE_ERROR[rcode]\n this.question = question\n }\n\n toJSON () {\n return {\n code: this.code,\n error: this.error,\n question: this.question,\n endpoint: this.endpoint\n }\n }\n}\n\nexport function validateResponse (data, question) {\n const rcode = toRcode(data.rcode)\n if (rcode !== 0) {\n const err = new DNSRcodeError(rcode, question)\n err.endpoint = data.endpoint\n throw err\n }\n return data\n}\n\nfunction processResolvers (res) {\n const time = (res.time === null || res.time === undefined) ? Date.now() : res.time\n const resolvers = lib.processResolvers(res.data.map(resolver => {\n resolver.endpoint = toEndpoint(Object.assign({ name: resolver.name }, resolver.endpoint))\n return resolver\n }))\n const endpoints = resolvers.map(resolver => resolver.endpoint)\n return {\n data: {\n resolvers,\n resolverByName: resolvers.reduce((byName, resolver) => {\n byName[resolver.name] = resolver\n return byName\n }, {}),\n endpoints,\n endpointByName: endpoints.reduce((byName, endpoint) => {\n byName[endpoint.name] = endpoint\n return byName\n }, {})\n },\n time\n }\n}\n\nexport const backup = processResolvers(backupResolvers)\n\nfunction toMultiQuery (singleQuery) {\n const query = Object.assign({\n type: 'query'\n }, singleQuery)\n delete query.question\n query.questions = []\n if (singleQuery.question) {\n query.questions.push(singleQuery.question)\n }\n return query\n}\n\nfunction queryOne (endpoint, query, timeout, abortSignal) {\n if (abortSignal && abortSignal.aborted) {\n return Promise.reject(new AbortError())\n }\n if (endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:') {\n return lib.queryDns(endpoint, query, timeout, abortSignal)\n }\n return queryDoh(endpoint, query, timeout, abortSignal)\n}\n\nfunction queryDoh (endpoint, query, timeout, abortSignal) {\n return lib.request(\n endpoint.url,\n endpoint.method,\n packet.encode(Object.assign({\n flags: packet.RECURSION_DESIRED\n }, query)),\n timeout,\n abortSignal\n ).then(\n function (res) {\n const data = res.data\n const response = res.response\n let error = res.error\n if (error === undefined) {\n if (data.length === 0) {\n error = new ResponseError('Empty.')\n } else {\n try {\n const decoded = packet.decode(data)\n decoded.response = response\n return decoded\n } catch (err) {\n error = new ResponseError('Invalid packet (cause=' + err.message + ')', err)\n }\n }\n }\n throw Object.assign(error, { response })\n }\n )\n}\n\nconst UPDATE_URL = new URL('https://martinheidegger.github.io/dns-query/resolvers.json')\n\nfunction concatUint8 (arrs) {\n const res = new Uint8Array(\n arrs.reduce((len, arr) => len + arr.length, 0)\n )\n let pos = 0\n for (const arr of arrs) {\n res.set(arr, pos)\n pos += arr.length\n }\n return res\n}\n\nexport function combineTXT (inputs) {\n return decode(concatUint8(inputs))\n}\n\nfunction isNameString (entry) {\n return /^@/.test(entry)\n}\n\nexport class Wellknown {\n constructor (opts) {\n this.opts = Object.assign({\n timeout: 5000,\n update: true,\n updateURL: UPDATE_URL,\n persist: false,\n localStoragePrefix: 'dnsquery_',\n maxAge: 300000 // 5 minutes\n }, opts)\n this._dataP = null\n }\n\n _data (force, outdated) {\n if (!force && this._dataP !== null) {\n return this._dataP.then(res => {\n if (res.time < Date.now() - this.opts.maxAge) {\n return this._data(true, res)\n }\n return res\n })\n }\n this._dataP = (!this.opts.update\n ? Promise.resolve(backup)\n : lib.loadJSON(\n this.opts.updateURL,\n this.opts.persist\n ? {\n name: 'resolvers.json',\n localStoragePrefix: this.opts.localStoragePrefix,\n maxTime: Date.now() - this.opts.maxAge\n }\n : null,\n this.opts.timeout\n )\n .then(res => processResolvers({\n data: res.data.resolvers,\n time: res.time\n }))\n .catch(() => outdated || backup)\n )\n return this._dataP\n }\n\n data () {\n return this._data(false).then(data => data.data)\n }\n\n endpoints (input) {\n if (input === null || input === undefined) {\n return this.data().then(data => data.endpoints)\n }\n if (input === 'doh') {\n input = filterDoh\n }\n if (input === 'dns') {\n input = filterDns\n }\n if (typeof input === 'function') {\n return this.data().then(data => data.endpoints.filter(input))\n }\n if (typeof input === 'string' || typeof input[Symbol.iterator] !== 'function') {\n return Promise.reject(new Error(`Endpoints (${input}) needs to be iterable (array).`))\n }\n input = Array.from(input).filter(Boolean)\n if (input.findIndex(isNameString) === -1) {\n try {\n return Promise.resolve(input.map(toEndpoint))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n return this.data().then(data =>\n input.map(entry => {\n if (isNameString(entry)) {\n const found = data.endpointByName[entry.substring(1)]\n if (!found) {\n throw new Error(`Endpoint ${entry} is not known.`)\n }\n return found\n }\n return toEndpoint(entry)\n })\n )\n }\n}\n\nexport const wellknown = new Wellknown()\n\nfunction isPromise (input) {\n if (input === null) {\n return false\n }\n if (typeof input !== 'object') {\n return false\n }\n return typeof input.then === 'function'\n}\n\nfunction toPromise (input) {\n return isPromise(input) ? input : Promise.resolve(input)\n}\n\nexport function query (q, opts) {\n opts = Object.assign({\n retries: 5,\n timeout: 30000 // 30 seconds\n }, opts)\n if (!q.question) return Promise.reject(new Error('To request data you need to specify a .question!'))\n return toPromise(opts.endpoints)\n .then(endpoints => {\n if (!Array.isArray(endpoints) || endpoints.length === 0) {\n throw new Error('No endpoints defined to lookup dns records.')\n }\n return queryN(endpoints.map(toEndpoint), toMultiQuery(q), opts)\n })\n .then(data => {\n data.question = data.questions[0]\n delete data.questions\n return data\n })\n}\n\nexport function lookupTxt (domain, opts) {\n const q = Object.assign({\n question: {\n type: 'TXT',\n name: domain\n }\n }, opts.query)\n return query(q, opts)\n .then(data => {\n validateResponse(data, q)\n return {\n entries: (data.answers || [])\n .filter(answer => answer.type === 'TXT' && answer.data)\n .map(answer => {\n return ({\n data: combineTXT(answer.data),\n ttl: answer.ttl\n })\n })\n .sort((a, b) => {\n if (a.data > b.data) return 1\n if (a.data < b.data) return -1\n return 0\n }),\n endpoint: data.endpoint\n }\n })\n}\n\nfunction queryN (endpoints, q, opts) {\n const endpoint = endpoints.length === 1\n ? endpoints[0]\n : endpoints[Math.floor(Math.random() * endpoints.length) % endpoints.length]\n return queryOne(endpoint, q, opts.timeout, opts.signal)\n .then(\n data => {\n // Add the endpoint to give a chance to identify which endpoint returned the result\n data.endpoint = endpoint.toString()\n return data\n },\n err => {\n if (err.name === 'AbortError' || opts.retries === 0) {\n err.endpoint = endpoint.toString()\n throw err\n }\n if (opts.retries > 0) {\n opts.retries -= 1\n }\n return queryN(endpoints, q, opts)\n }\n )\n}\n\nfunction filterDoh (endpoint) {\n return endpoint.protocol === 'https:' || endpoint.protocol === 'http:'\n}\n\nfunction filterDns (endpoint) {\n return endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:'\n}\n","export const resolvers = {\n data: [\n {\n name: 'adfree.usableprivacy.net',\n endpoint: {\n protocol: 'https:',\n host: 'adfree.usableprivacy.net'\n },\n description: 'Public updns DoH service with advertising, tracker and malware filters.\\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true\n },\n {\n name: 'adguard-dns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.adguard.com',\n ipv4: '94.140.15.15'\n },\n description: 'Remove ads and protect your computer from malware (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-family-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-family.adguard.com',\n ipv4: '94.140.15.16'\n },\n description: 'Adguard DNS with safesearch and adult content blocking (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-unfiltered-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-unfiltered.adguard.com',\n ipv4: '94.140.14.140'\n },\n description: 'AdGuard public DNS servers without filters (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n }\n },\n {\n name: 'ahadns-doh-chi',\n endpoint: {\n protocol: 'https:',\n host: 'doh.chi.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 41.8483,\n long: -87.6517\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-in',\n endpoint: {\n protocol: 'https:',\n host: 'doh.in.ahadns.net',\n cors: true\n },\n 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',\n country: 'India',\n location: {\n lat: 19.0748,\n long: 72.8856\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-la',\n endpoint: {\n protocol: 'https:',\n host: 'doh.la.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 34.0549,\n long: -118.2578\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.nl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-ny',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ny.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 40.7308,\n long: -73.9975\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-pl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'alidns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.alidns.com',\n ipv4: '223.5.5.5',\n cors: true\n },\n 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/',\n country: 'China',\n location: {\n lat: 34.7725,\n long: 113.7266\n },\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'ams-ads-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl-noads.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n },\n filter: true\n },\n {\n name: 'ams-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n }\n },\n {\n name: 'att',\n endpoint: {\n protocol: 'https:',\n host: 'dohtrial.att.net'\n },\n description: 'AT&T test DoH server.',\n log: true\n },\n {\n name: 'bcn-ads-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses-noads.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n },\n filter: true\n },\n {\n name: 'bcn-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n }\n },\n {\n name: 'brahma-world',\n endpoint: {\n protocol: 'https:',\n host: 'dns.brahma.world'\n },\n 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)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'cisco-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.opendns.com',\n ipv4: '146.112.41.2'\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true,\n log: true\n },\n {\n name: 'cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'dns.cloudflare.com',\n ipv4: '1.0.0.1',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n cors: true\n },\n {\n name: 'cloudflare-family',\n endpoint: {\n protocol: 'https:',\n host: 'family.cloudflare-dns.com',\n ipv4: '1.0.0.3',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'cloudflare-ipv6',\n endpoint: {\n protocol: 'https:',\n host: '1dot1dot1dot1.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare DNS over IPv6 (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'cloudflare-security',\n endpoint: {\n protocol: 'https:',\n host: 'security.cloudflare-dns.com',\n ipv4: '1.0.0.2',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'controld-block-malware',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p1'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p2'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad-social',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p3'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-family-friendly',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/family'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-uncensored',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/uncensored'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'controld-unfiltered',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p0'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'dns.digitale-gesellschaft.ch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.digitale-gesellschaft.ch'\n },\n description: 'Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\\nHosted in Zurich, Switzerland.\\nNon-logging, non-filtering, supports DNSSEC.',\n country: 'Switzerland',\n location: {\n lat: 47.1449,\n long: 8.1551\n }\n },\n {\n name: 'dns.ryan-palmer',\n endpoint: {\n protocol: 'https:',\n host: 'dns1.ryan-palmer.com'\n },\n description: 'Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.',\n country: 'United Kingdom',\n location: {\n lat: 51.5164,\n long: -0.093\n }\n },\n {\n name: 'dns.sb',\n endpoint: {\n protocol: 'https:',\n host: 'doh.sb',\n ipv4: '185.222.222.222',\n cors: true\n },\n description: 'DNSSEC-enabled DoH server by https://xtom.com/\\nhttps://dns.sb/doh/',\n country: 'Unknown',\n location: {\n lat: 47,\n long: 8\n },\n cors: true\n },\n {\n name: 'dns.therifleman.name',\n endpoint: {\n protocol: 'https:',\n host: 'dns.therifleman.name'\n },\n 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',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh-no-safe-search',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh-no-safe-search.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforge.de',\n endpoint: {\n protocol: 'https:',\n host: 'dnsforge.de',\n cors: true\n },\n description: 'Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.',\n country: 'Germany',\n location: {\n lat: 52.2998,\n long: 9.447\n },\n filter: true,\n cors: true\n },\n {\n name: 'dnshome-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.dnshome.de'\n },\n description: 'https://www.dnshome.de/ public resolver in Germany'\n },\n {\n name: 'dnspod-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pub',\n cors: true\n },\n description: 'A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en',\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'dnswarden-asia-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adblock'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-adultfilter-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adultfilter'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-uncensor-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/uncensored'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n }\n },\n {\n name: 'dnswarden-eu-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.eu.dnswarden.com'\n },\n description: 'Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Germany',\n location: {\n lat: 50.1103,\n long: 8.7147\n },\n filter: true\n },\n {\n name: 'dnswarden-us-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.us.dnswarden.com'\n },\n description: 'Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'United States',\n location: {\n lat: 32.7889,\n long: -96.8021\n },\n filter: true\n },\n {\n name: 'doh-ch-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ch.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-adult',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/adult-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-family',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/family-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-security',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/security-filter/',\n cors: true\n },\n description: 'Block access to phishing, malware and malicious domains. It does not block adult content.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'doh.crypto.sx',\n cors: true\n },\n description: 'DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\\nBackend hosted by Scaleway, globally cached via Cloudflare.\\nMaintained by Frank Denis.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-crypto-sx-ipv6',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ipv6.crypto.sx',\n cors: true\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-de-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-de.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-fi-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-fi.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-ibksturm',\n endpoint: {\n protocol: 'https:',\n host: 'ibksturm.synology.me'\n },\n description: 'DoH & DoT Server, No Logging, No Filters, DNSSEC\\nRunning privately by ibksturm in Thurgau, Switzerland'\n },\n {\n name: 'doh-jp-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-jp.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh.ffmuc.net',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ffmuc.net'\n },\n description: 'An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\\nhttps://ffmuc.net/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'doh.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org'\n },\n description: 'Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'google',\n endpoint: {\n protocol: 'https:',\n host: 'dns.google',\n ipv4: '8.8.8.8',\n cors: true\n },\n description: 'Google DNS (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true,\n cors: true\n },\n {\n name: 'hdns',\n endpoint: {\n protocol: 'https:',\n host: 'query.hdns.io',\n cors: true\n },\n description: 'HDNS is a public DNS resolver that supports Handshake domains.\\nhttps://www.hdns.io',\n country: 'United States',\n location: {\n lat: 37.7771,\n long: -122.406\n },\n cors: true\n },\n {\n name: 'he',\n endpoint: {\n protocol: 'https:',\n host: 'ordns.he.net'\n },\n description: 'Hurricane Electric DoH server (anycast)\\nUnknown logging policy.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true\n },\n {\n name: 'id-gmail-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app'\n },\n description: 'Non-Logging DNS-over-HTTPS server located in Singapore.\\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'iij',\n endpoint: {\n protocol: 'https:',\n host: 'public.dns.iij.jp'\n },\n description: 'DoH server operated by Internet Initiative Japan in Tokyo.\\nhttps://www.iij.ad.jp/',\n country: 'Japan',\n location: {\n lat: 35.69,\n long: 139.69\n },\n log: true\n },\n {\n name: 'iqdns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'a.passcloud.xyz'\n },\n 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',\n filter: true\n },\n {\n name: 'jp.tiar.app-doh',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app'\n },\n description: 'Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\\nNo ECS, Support DNSSEC',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n }\n },\n {\n name: 'jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org'\n },\n description: 'DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\\nCached via Cloudflare.'\n },\n {\n name: 'libredns',\n endpoint: {\n protocol: 'https:',\n host: 'doh.libredns.gr'\n },\n description: 'DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\\nhttps://libredns.gr/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'nextdns',\n endpoint: {\n protocol: 'https:',\n host: 'anycsast.dns.nextdns.io'\n },\n 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/',\n country: 'Netherlands',\n location: {\n lat: 52.3891,\n long: 4.6563\n }\n },\n {\n name: 'nextdns-ultralow',\n endpoint: {\n protocol: 'https:',\n host: 'dns.nextdns.io',\n path: '/dnscrypt-proxy'\n },\n 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.'\n },\n {\n name: 'njalla-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.njal.la',\n cors: true\n },\n description: 'Non-logging DoH server in Sweden operated by Njalla.\\nhttps://dns.njal.la/',\n country: 'Sweden',\n location: {\n lat: 59.3247,\n long: 18.056\n },\n cors: true\n },\n {\n name: 'odoh-cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare ODoH server.\\nhttps://cloudflare.com',\n cors: true\n },\n {\n name: 'odoh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.crypto.sx',\n cors: true\n },\n description: 'ODoH target server. Anycast, no logs.\\nBackend hosted by Scaleway. Maintained by Frank Denis.',\n cors: true\n },\n {\n name: 'odoh-id-gmail',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. Based in Singapore, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'odoh-jp.tiar.app',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. no logs.'\n },\n {\n name: 'odoh-jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.'\n },\n {\n name: 'odoh-resolver4.dns.openinternet.io',\n endpoint: {\n protocol: 'https:',\n host: 'resolver4.dns.openinternet.io'\n },\n 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\"\n },\n {\n name: 'odoh-tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'publicarray-au2-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh-2.seby.io',\n cors: true\n },\n description: 'DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\\nMaintained by publicarray - https://dns.seby.io',\n country: 'Australia',\n location: {\n lat: -33.8591,\n long: 151.2002\n },\n cors: true\n },\n {\n name: 'puredns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'puredns.org',\n ipv4: '146.190.6.13',\n cors: true\n },\n description: 'Public uncensored DNS resolver in Singapore - https://puredns.org\\n** Only available in Indonesia and Singapore **',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'quad101',\n endpoint: {\n protocol: 'https:',\n host: 'dns.twnic.tw',\n cors: true\n },\n description: 'DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\\nhttps://101.101.101.101/index_en.html',\n cors: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns11.quad9.net',\n ipv4: '149.112.112.11'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns.quad9.net',\n ipv4: '149.112.112.112'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns12.quad9.net',\n ipv4: '9.9.9.12'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns10.quad9.net',\n ipv4: '149.112.112.10'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip6-port5053-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns9.quad9.net'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'safesurfer-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.safesurfer.io'\n },\n 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',\n filter: true,\n log: true\n },\n {\n name: 'sth-ads-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse-noads.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n },\n filter: true\n },\n {\n name: 'sth-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n }\n },\n {\n name: 'switch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.switch.ch'\n },\n description: 'Public DoH service provided by SWITCH in Switzerland\\nhttps://www.switch.ch\\nProvides protection against malware, but does not block ads.',\n filter: true\n },\n {\n name: 'uncensoreddns-dk-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'unicast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'uncensoreddns-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'anycast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'v.dnscrypt.uk-doh-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'v.dnscrypt.uk'\n },\n description: 'DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\\nhttps://www.dnscrypt.uk',\n country: 'United Kingdom',\n location: {\n lat: 51.4964,\n long: -0.1224\n }\n }\n ],\n time: 1654187067783\n}\n","import { Logger } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { query, wellknown } from \"dns-query\";\nconst log = new Logger(\"dns-over-https\");\nexport class DnsOverHttps {\n endpoints;\n retries;\n /**\n * Create new Dns-Over-Http DNS client.\n *\n * @param endpoints The endpoints for Dns-Over-Https queries;\n * Defaults to using dns-query's API..\n * @param retries Retries if a given endpoint fails.\n *\n * @throws {code: string} If DNS query fails.\n */\n static async create(endpoints, retries) {\n const _endpoints = endpoints ?? (await wellknown.endpoints(\"doh\"));\n return new DnsOverHttps(_endpoints, retries);\n }\n constructor(endpoints, retries = 3) {\n this.endpoints = endpoints;\n this.retries = retries;\n }\n /**\n * Resolves a TXT record\n *\n * @param domain The domain name\n *\n * @throws if the query fails\n */\n async resolveTXT(domain) {\n let answers;\n try {\n const res = await query({\n question: { type: \"TXT\", name: domain }\n }, {\n endpoints: this.endpoints,\n retries: this.retries\n });\n answers = res.answers;\n }\n catch (error) {\n log.error(\"query failed: \", error);\n throw new Error(\"DNS query failed\");\n }\n if (!answers)\n throw new Error(`Could not resolve ${domain}`);\n const data = answers.map((a) => a.data);\n const result = [];\n data.forEach((d) => {\n if (typeof d === \"string\") {\n result.push(d);\n }\n else if (Array.isArray(d)) {\n d.forEach((sd) => {\n if (typeof sd === \"string\") {\n result.push(sd);\n }\n else {\n result.push(bytesToUtf8(sd));\n }\n });\n }\n else {\n result.push(bytesToUtf8(d));\n }\n });\n return result;\n }\n}\n//# sourceMappingURL=dns_over_https.js.map","import { ENR } from \"@waku/enr\";\nimport { keccak256, verifySignature } from \"@waku/enr\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport base32 from \"hi-base32\";\nimport { fromString } from \"uint8arrays/from-string\";\nexport class ENRTree {\n static RECORD_PREFIX = ENR.RECORD_PREFIX;\n static TREE_PREFIX = \"enrtree:\";\n static BRANCH_PREFIX = \"enrtree-branch:\";\n static ROOT_PREFIX = \"enrtree-root:\";\n /**\n * Extracts the branch subdomain referenced by a DNS tree root string after verifying\n * the root record signature with its base32 compressed public key.\n */\n static parseAndVerifyRoot(root, publicKey) {\n if (!root.startsWith(this.ROOT_PREFIX))\n throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);\n const rootValues = ENRTree.parseRootValues(root);\n const decodedPublicKey = base32.decode.asBytes(publicKey);\n // The signature is a 65-byte secp256k1 over the keccak256 hash\n // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string\n // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)\n const signedComponent = root.split(\" sig\")[0];\n const signedComponentBuffer = utf8ToBytes(signedComponent);\n const signatureBuffer = fromString(rootValues.signature, \"base64url\").slice(0, 64);\n const isVerified = verifySignature(signatureBuffer, keccak256(signedComponentBuffer), new Uint8Array(decodedPublicKey));\n if (!isVerified)\n throw new Error(\"Unable to verify ENRTree root signature\");\n return rootValues.eRoot;\n }\n static parseRootValues(txt) {\n const matches = txt.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\\d+) sig=([^ ]+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree root entry\");\n matches.shift(); // The first entry is the full match\n const [eRoot, lRoot, seq, signature] = matches;\n if (!eRoot)\n throw new Error(\"Could not parse 'e' value from ENRTree root entry\");\n if (!lRoot)\n throw new Error(\"Could not parse 'l' value from ENRTree root entry\");\n if (!seq)\n throw new Error(\"Could not parse 'seq' value from ENRTree root entry\");\n if (!signature)\n throw new Error(\"Could not parse 'sig' value from ENRTree root entry\");\n return { eRoot, lRoot, seq: Number(seq), signature };\n }\n /**\n * Returns the public key and top level domain of an ENR tree entry.\n * The domain is the starting point for traversing a set of linked DNS TXT records\n * and the public key is used to verify the root entry record\n */\n static parseTree(tree) {\n if (!tree.startsWith(this.TREE_PREFIX))\n throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);\n const matches = tree.match(/^enrtree:\\/\\/([^@]+)@(.+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree tree entry\");\n matches.shift(); // The first entry is the full match\n const [publicKey, domain] = matches;\n if (!publicKey)\n throw new Error(\"Could not parse public key from ENRTree tree entry\");\n if (!domain)\n throw new Error(\"Could not parse domain from ENRTree tree entry\");\n return { publicKey, domain };\n }\n /**\n * Returns subdomains listed in an ENR branch entry. These in turn lead to\n * either further branch entries or ENR records.\n */\n static parseBranch(branch) {\n if (!branch.startsWith(this.BRANCH_PREFIX))\n throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);\n return branch.split(this.BRANCH_PREFIX)[1].split(\",\");\n }\n}\n//# sourceMappingURL=enrtree.js.map","import { Logger } from \"@waku/utils\";\nconst log = new Logger(\"discovery:fetch_nodes\");\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peers = [];\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && isNewPeer(peer, peers)) {\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n peers.push(peer);\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n return peers;\n}\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function* yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peerNodeIds = new Set();\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && peer.nodeId && !peerNodeIds.has(peer.nodeId)) {\n peerNodeIds.add(peer.nodeId);\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n yield peer;\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n}\nfunction isSatisfied(wanted, actual) {\n return (actual.relay >= wanted.relay &&\n actual.store >= wanted.store &&\n actual.filter >= wanted.filter &&\n actual.lightPush >= wanted.lightPush);\n}\nfunction isNewPeer(peer, peers) {\n if (!peer.nodeId)\n return false;\n for (const existingPeer of peers) {\n if (peer.nodeId === existingPeer.nodeId) {\n return false;\n }\n }\n return true;\n}\nfunction addCapabilities(node, total) {\n if (node.relay)\n total.relay += 1;\n if (node.store)\n total.store += 1;\n if (node.filter)\n total.filter += 1;\n if (node.lightPush)\n total.lightPush += 1;\n}\n/**\n * Checks if the proposed ENR [[node]] helps satisfy the [[wanted]] capabilities,\n * considering the [[actual]] capabilities of nodes retrieved so far..\n *\n * @throws If the function is called when the wanted capabilities are already fulfilled.\n */\nfunction helpsSatisfyCapabilities(node, wanted, actual) {\n if (isSatisfied(wanted, actual)) {\n throw \"Internal Error: Waku2 wanted capabilities are already fulfilled\";\n }\n const missing = missingCapabilities(wanted, actual);\n return ((missing.relay && node.relay) ||\n (missing.store && node.store) ||\n (missing.filter && node.filter) ||\n (missing.lightPush && node.lightPush));\n}\n/**\n * Return a [[Waku2]] Object for which capabilities are set to true if they are\n * [[wanted]] yet missing from [[actual]].\n */\nfunction missingCapabilities(wanted, actual) {\n return {\n relay: actual.relay < wanted.relay,\n store: actual.store < wanted.store,\n filter: actual.filter < wanted.filter,\n lightPush: actual.lightPush < wanted.lightPush\n };\n}\n//# sourceMappingURL=fetch_nodes.js.map","import { EnrDecoder } from \"@waku/enr\";\nimport { Logger } from \"@waku/utils\";\nimport { DnsOverHttps } from \"./dns_over_https.js\";\nimport { ENRTree } from \"./enrtree.js\";\nimport { fetchNodesUntilCapabilitiesFulfilled, yieldNodesUntilCapabilitiesFulfilled } from \"./fetch_nodes.js\";\nconst log = new Logger(\"discovery:dns\");\nexport class DnsNodeDiscovery {\n dns;\n _DNSTreeCache;\n _errorTolerance = 10;\n static async dnsOverHttp(dnsClient) {\n if (!dnsClient) {\n dnsClient = await DnsOverHttps.create();\n }\n return new DnsNodeDiscovery(dnsClient);\n }\n /**\n * Returns a list of verified peers listed in an EIP-1459 DNS tree. Method may\n * return fewer peers than requested if @link wantedNodeCapabilityCount requires\n * larger quantity of peers than available or the number of errors/duplicate\n * peers encountered by randomized search exceeds the sum of the fields of\n * @link wantedNodeCapabilityCount plus the @link _errorTolerance factor.\n */\n async getPeers(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n const peers = await fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context));\n log.info(\"retrieved peers: \", peers.map((peer) => {\n return {\n id: peer.peerId?.toString(),\n multiaddrs: peer.multiaddrs?.map((ma) => ma.toString())\n };\n }));\n return peers;\n }\n constructor(dns) {\n this._DNSTreeCache = {};\n this.dns = dns;\n }\n /**\n * {@inheritDoc getPeers}\n */\n async *getNextPeer(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n for await (const peer of yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context))) {\n yield peer;\n }\n }\n /**\n * Runs a recursive, randomized descent of the DNS tree to retrieve a single\n * ENR record as an ENR. Returns null if parsing or DNS resolution fails.\n */\n async _search(subdomain, context) {\n try {\n const entry = await this._getTXTRecord(subdomain, context);\n context.visits[subdomain] = true;\n let next;\n let branches;\n const entryType = getEntryType(entry);\n try {\n switch (entryType) {\n case ENRTree.ROOT_PREFIX:\n next = ENRTree.parseAndVerifyRoot(entry, context.publicKey);\n return await this._search(next, context);\n case ENRTree.BRANCH_PREFIX:\n branches = ENRTree.parseBranch(entry);\n next = selectRandomPath(branches, context);\n return await this._search(next, context);\n case ENRTree.RECORD_PREFIX:\n return EnrDecoder.fromString(entry);\n default:\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to search DNS tree ${entryType} at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n /**\n * Retrieves the TXT record stored at a location from either\n * this DNS tree cache or via DNS query.\n *\n * @throws if the TXT Record contains non-UTF-8 values.\n */\n async _getTXTRecord(subdomain, context) {\n if (this._DNSTreeCache[subdomain]) {\n return this._DNSTreeCache[subdomain];\n }\n // Location is either the top level tree entry host or a subdomain of it.\n const location = subdomain !== context.domain\n ? `${subdomain}.${context.domain}`\n : context.domain;\n const response = await this.dns.resolveTXT(location);\n if (!response.length)\n throw new Error(\"Received empty result array while fetching TXT record\");\n if (!response[0].length)\n throw new Error(\"Received empty TXT record\");\n // Branch entries can be an array of strings of comma delimited subdomains, with\n // some subdomain strings split across the array elements\n const result = response.join(\"\");\n this._DNSTreeCache[subdomain] = result;\n return result;\n }\n}\nfunction getEntryType(entry) {\n if (entry.startsWith(ENRTree.ROOT_PREFIX))\n return ENRTree.ROOT_PREFIX;\n if (entry.startsWith(ENRTree.BRANCH_PREFIX))\n return ENRTree.BRANCH_PREFIX;\n if (entry.startsWith(ENRTree.RECORD_PREFIX))\n return ENRTree.RECORD_PREFIX;\n return \"\";\n}\n/**\n * Returns a randomly selected subdomain string from the list provided by a branch\n * entry record.\n *\n * The client must track subdomains which are already resolved to avoid\n * going into an infinite loop b/c branch entries can contain\n * circular references. It’s in the client’s best interest to traverse the\n * tree in random order.\n */\nfunction selectRandomPath(branches, context) {\n // Identify domains already visited in this traversal of the DNS tree.\n // Then filter against them to prevent cycles.\n const circularRefs = {};\n for (const [idx, subdomain] of branches.entries()) {\n if (context.visits[subdomain]) {\n circularRefs[idx] = true;\n }\n }\n // If all possible paths are circular...\n if (Object.keys(circularRefs).length === branches.length) {\n throw new Error(\"Unresolvable circular path detected\");\n }\n // Randomly select a viable path\n let index;\n do {\n index = Math.floor(Math.random() * branches.length);\n } while (circularRefs[index]);\n return branches[index];\n}\n//# sourceMappingURL=dns.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\nimport { DEFAULT_BOOTSTRAP_TAG_NAME, DEFAULT_BOOTSTRAP_TAG_TTL, DEFAULT_BOOTSTRAP_TAG_VALUE, DEFAULT_NODE_REQUIREMENTS } from \"./constants.js\";\nimport { DnsNodeDiscovery } from \"./dns.js\";\nconst log = new Logger(\"peer-discovery-dns\");\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n */\nexport class PeerDiscoveryDns extends TypedEventEmitter {\n nextPeer;\n _started;\n _components;\n _options;\n constructor(components, options) {\n super();\n this._started = false;\n this._components = components;\n this._options = options;\n const { enrUrls } = options;\n log.info(\"Use following EIP-1459 ENR Tree URLs: \", enrUrls);\n }\n /**\n * Start discovery process\n */\n async start() {\n log.info(\"Starting peer discovery via dns\");\n this._started = true;\n if (this.nextPeer === undefined) {\n let { enrUrls } = this._options;\n if (!Array.isArray(enrUrls))\n enrUrls = [enrUrls];\n const { wantedNodeCapabilityCount } = this._options;\n const dns = await DnsNodeDiscovery.dnsOverHttp();\n this.nextPeer = dns.getNextPeer.bind(dns, enrUrls, wantedNodeCapabilityCount);\n }\n for await (const peerEnr of this.nextPeer()) {\n if (!this._started) {\n return;\n }\n const { peerInfo, shardInfo } = peerEnr;\n if (!peerInfo) {\n continue;\n }\n const tagsToUpdate = {\n [DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._options.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._options.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n };\n let isPeerChanged = false;\n const isPeerExists = await this._components.peerStore.has(peerInfo.id);\n if (isPeerExists) {\n const peer = await this._components.peerStore.get(peerInfo.id);\n const hasBootstrapTag = peer.tags.has(DEFAULT_BOOTSTRAP_TAG_NAME);\n if (!hasBootstrapTag) {\n isPeerChanged = true;\n await this._components.peerStore.merge(peerInfo.id, {\n tags: tagsToUpdate\n });\n }\n }\n else {\n isPeerChanged = true;\n await this._components.peerStore.save(peerInfo.id, {\n tags: tagsToUpdate,\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n }\n if (isPeerChanged) {\n this.dispatchEvent(new CustomEvent(\"peer\", { detail: peerInfo }));\n }\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n this._started = false;\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return \"@waku/bootstrap\";\n }\n}\nexport function wakuDnsDiscovery(enrUrls, wantedNodeCapabilityCount = DEFAULT_NODE_REQUIREMENTS) {\n return (components) => new PeerDiscoveryDns(components, { enrUrls, wantedNodeCapabilityCount });\n}\n//# sourceMappingURL=dns_discovery.js.map","import { proto_peer_exchange as proto } from \"@waku/proto\";\n/**\n * PeerExchangeRPC represents a message conforming to the Waku Peer Exchange protocol\n */\nexport class PeerExchangeRPC {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(params) {\n const { numPeers } = params;\n return new PeerExchangeRPC({\n query: {\n numPeers: numPeers\n },\n response: undefined\n });\n }\n /**\n * Encode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n encode() {\n return proto.PeerExchangeRPC.encode(this.proto);\n }\n /**\n * Decode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n static decode(bytes) {\n const res = proto.PeerExchangeRPC.decode(bytes);\n return new PeerExchangeRPC(res);\n }\n get query() {\n return this.proto.query;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=rpc.js.map","import { BaseProtocol } from \"@waku/core/lib/base_protocol\";\nimport { EnrDecoder } from \"@waku/enr\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { isDefined } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { PeerExchangeRPC } from \"./rpc.js\";\nexport const PeerExchangeCodec = \"/vac/waku/peer-exchange/2.0.0-alpha1\";\nconst log = new Logger(\"peer-exchange\");\n/**\n * Implementation of the Peer Exchange protocol (https://rfc.vac.dev/spec/34/)\n */\nexport class WakuPeerExchange extends BaseProtocol {\n /**\n * @param components - libp2p components\n */\n constructor(components, pubsubTopics) {\n super(PeerExchangeCodec, components, log, pubsubTopics);\n }\n /**\n * Make a peer exchange query to a peer\n */\n async query(params) {\n const { numPeers } = params;\n const rpcQuery = PeerExchangeRPC.createRequest({\n numPeers: BigInt(numPeers)\n });\n const peer = await this.peerStore.get(params.peerId);\n if (!peer) {\n return {\n peerInfos: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (err) {\n log.error(\"Failed to get stream\", err);\n return {\n peerInfos: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const res = await pipe([rpcQuery.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n try {\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const { response } = PeerExchangeRPC.decode(bytes);\n if (!response) {\n log.error(\"PeerExchangeRPC message did not contains a `response` field\");\n return {\n peerInfos: null,\n error: ProtocolError.EMPTY_PAYLOAD\n };\n }\n const peerInfos = await Promise.all(response.peerInfos\n .map((peerInfo) => peerInfo.enr)\n .filter(isDefined)\n .map(async (enr) => {\n return { ENR: await EnrDecoder.fromRLP(enr) };\n }));\n return {\n peerInfos,\n error: null\n };\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n peerInfos: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n }\n}\n/**\n *\n * @returns A function that creates a new peer exchange protocol\n */\nexport function wakuPeerExchange(pubsubTopics) {\n return (components) => new WakuPeerExchange(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { Tags } from \"@waku/interfaces\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\nimport { PeerExchangeCodec, WakuPeerExchange } from \"./waku_peer_exchange.js\";\nconst log = new Logger(\"peer-exchange-discovery\");\nconst DEFAULT_PEER_EXCHANGE_REQUEST_NODES = 10;\nconst DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS = 10 * 1000;\nconst DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags.PEER_EXCHANGE;\nconst DEFAULT_PEER_EXCHANGE_TAG_VALUE = 50;\nconst DEFAULT_PEER_EXCHANGE_TAG_TTL = 100_000_000;\nexport class PeerExchangeDiscovery extends TypedEventEmitter {\n components;\n peerExchange;\n options;\n isStarted;\n queryingPeers = new Set();\n queryAttempts = new Map();\n handleDiscoveredPeer = (event) => {\n const { protocols, peerId } = event.detail;\n if (!protocols.includes(PeerExchangeCodec) ||\n this.queryingPeers.has(peerId.toString()))\n return;\n this.queryingPeers.add(peerId.toString());\n this.startRecurringQueries(peerId).catch((error) => log.error(`Error querying peer ${error}`));\n };\n constructor(components, pubsubTopics, options = {}) {\n super();\n this.components = components;\n this.peerExchange = new WakuPeerExchange(components, pubsubTopics);\n this.options = options;\n this.isStarted = false;\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted) {\n return;\n }\n log.info(\"Starting peer exchange node discovery, discovering peers\");\n // might be better to use \"peer:identify\" or \"peer:update\"\n this.components.events.addEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n /**\n * Remove event listener\n */\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping peer exchange node discovery\");\n this.isStarted = false;\n this.queryingPeers.clear();\n this.components.events.removeEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return \"@waku/peer-exchange\";\n }\n startRecurringQueries = async (peerId) => {\n const peerIdStr = peerId.toString();\n const { queryInterval = DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS, maxRetries = DEFAULT_MAX_RETRIES } = this.options;\n log.info(`Querying peer: ${peerIdStr} (attempt ${this.queryAttempts.get(peerIdStr) ?? 1})`);\n await this.query(peerId);\n const currentAttempt = this.queryAttempts.get(peerIdStr) ?? 1;\n if (currentAttempt > maxRetries) {\n this.abortQueriesForPeer(peerIdStr);\n return;\n }\n setTimeout(() => {\n this.queryAttempts.set(peerIdStr, currentAttempt + 1);\n this.startRecurringQueries(peerId).catch((error) => {\n log.error(`Error in startRecurringQueries: ${error}`);\n });\n }, queryInterval * currentAttempt);\n };\n async query(peerId) {\n const { error, peerInfos } = await this.peerExchange.query({\n numPeers: DEFAULT_PEER_EXCHANGE_REQUEST_NODES,\n peerId\n });\n if (error) {\n log.error(\"Peer exchange query failed\", error);\n return { error, peerInfos: null };\n }\n for (const _peerInfo of peerInfos) {\n const { ENR } = _peerInfo;\n if (!ENR) {\n log.warn(\"No ENR in peerInfo object, skipping\");\n continue;\n }\n const { peerId, peerInfo, shardInfo } = ENR;\n if (!peerId || !peerInfo) {\n continue;\n }\n const hasPeer = await this.components.peerStore.has(peerId);\n if (hasPeer) {\n continue;\n }\n // update the tags for the peer\n await this.components.peerStore.save(peerId, {\n tags: {\n [DEFAULT_PEER_EXCHANGE_TAG_NAME]: {\n value: this.options.tagValue ?? DEFAULT_PEER_EXCHANGE_TAG_VALUE,\n ttl: this.options.tagTTL ?? DEFAULT_PEER_EXCHANGE_TAG_TTL\n }\n },\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n log.info(`Discovered peer: ${peerId.toString()}`);\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n }));\n }\n return { error: null, peerInfos };\n }\n abortQueriesForPeer(peerIdStr) {\n log.info(`Aborting queries for peer: ${peerIdStr}`);\n this.queryingPeers.delete(peerIdStr);\n this.queryAttempts.delete(peerIdStr);\n }\n}\nexport function wakuPeerExchangeDiscovery(pubsubTopics) {\n return (components) => new PeerExchangeDiscovery(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange_discovery.js.map","export * from \"./is_defined.js\";\nexport * from \"./random_subset.js\";\nexport * from \"./group_by.js\";\nexport * from \"./to_async_iterator.js\";\nexport * from \"./is_size_valid.js\";\nexport * from \"./sharding.js\";\nexport * from \"./push_or_init_map.js\";\nexport * from \"./relay_shard_codec.js\";\nexport function removeItemFromArray(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n }\n return arr;\n}\nexport function getWsMultiaddrFromMultiaddrs(addresses) {\n const wsMultiaddr = addresses.find((addr) => addr.toString().includes(\"ws\") || addr.toString().includes(\"wss\"));\n if (!wsMultiaddr) {\n throw new Error(\"No ws multiaddr found in the given addresses\");\n }\n return wsMultiaddr;\n}\n//# sourceMappingURL=index.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var TelemetryType;\n(function (TelemetryType) {\n TelemetryType[\"LIGHT_PUSH_FILTER\"] = \"LightPushFilter\";\n})(TelemetryType || (TelemetryType = {}));\nvar TelemetryClient = /** @class */ (function () {\n function TelemetryClient(url, intervalPeriod) {\n if (intervalPeriod === void 0) { intervalPeriod = 5000; }\n this.url = url;\n this.intervalPeriod = intervalPeriod;\n this.queue = [];\n this.intervalId = null;\n this.requestId = 0;\n }\n TelemetryClient.prototype.push = function (messages) {\n var _a;\n (_a = this.queue).push.apply(_a, messages);\n };\n TelemetryClient.prototype.start = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n if (!this.intervalId) {\n this.intervalId = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {\n var success;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.queue.length > 0)) return [3 /*break*/, 2];\n return [4 /*yield*/, this.send(this.queue)];\n case 1:\n success = _a.sent();\n if (success) {\n console.log(\"Sent \", this.queue.length, \" telemetry logs\");\n this.queue = [];\n }\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n }); }, this.intervalPeriod);\n }\n return [2 /*return*/];\n });\n });\n };\n TelemetryClient.prototype.stop = function () {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n };\n TelemetryClient.prototype.send = function (messages) {\n return __awaiter(this, void 0, void 0, function () {\n var telemetryRequests, res, e_1;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n telemetryRequests = messages.map(function (message) { return ({\n id: ++_this.requestId,\n telemetryType: message.messageType.toString(),\n telemetryData: message\n }); });\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, fetch(this.url, {\n method: \"POST\",\n body: JSON.stringify(telemetryRequests),\n })];\n case 2:\n res = _a.sent();\n if (res.status !== 201) {\n console.error(\"Error sending messages to telemetry service: \", res.status, res.statusText, res.json);\n return [2 /*return*/, false];\n }\n return [2 /*return*/, true];\n case 3:\n e_1 = _a.sent();\n console.error(\"Error sending messages to telemetry service: \", e_1);\n console.error(\"Failed trying to send the following messages: \", telemetryRequests);\n return [2 /*return*/, false];\n case 4: return [2 /*return*/];\n }\n });\n });\n };\n return TelemetryClient;\n}());\nexport { TelemetryClient };\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var generateRandomNumber = function () {\n return Math.floor(Math.random() * 1000000);\n};\nexport var hashNumber = function (number) { return __awaiter(void 0, void 0, void 0, function () {\n var encoder, data, buffer;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n encoder = new TextEncoder();\n data = encoder.encode(number.toString());\n return [4 /*yield*/, crypto.subtle.digest(\"SHA-256\", data)];\n case 1:\n buffer = _a.sent();\n return [2 /*return*/, Array.from(new Uint8Array(buffer))\n .map(function (b) { return b.toString(16).padStart(2, \"0\"); })\n .join(\"\")];\n }\n });\n}); };\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { createLightNode, createEncoder, createDecoder, waitForRemotePeer, utils } from \"@waku/sdk\";\nimport { Type, Field } from \"protobufjs\";\nimport { TelemetryClient, TelemetryType, } from \"./telemetry_client\";\nimport { generateRandomNumber, hashNumber } from \"./util\";\nvar DEFAULT_CONTENT_TOPIC = \"/js-waku-examples/1/message-ratio/utf8\";\nvar TELEMETRY_URL = process.env.TELEMETRY_URL || \"http://localhost:8080/waku-metrics\";\nvar ProtoSequencedMessage = new Type(\"SequencedMessage\")\n .add(new Field(\"hash\", 1, \"string\"))\n .add(new Field(\"total\", 2, \"uint64\"))\n .add(new Field(\"index\", 3, \"uint64\"))\n .add(new Field(\"sender\", 4, \"string\"));\nvar sequenceCompletedEvent = new CustomEvent(\"sequenceCompleted\");\nvar messageSentEvent = new CustomEvent(\"messageSent\");\nvar wakuNode = function () { return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, createLightNode({\n contentTopics: [DEFAULT_CONTENT_TOPIC],\n defaultBootstrap: true,\n })];\n case 1: return [2 /*return*/, _a.sent()];\n }\n });\n}); };\nexport function app(telemetryClient) {\n return __awaiter(this, void 0, void 0, function () {\n var node, peerId, encoder, startLightPushSequence, startFilterSubscription;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, wakuNode()];\n case 1:\n node = _a.sent();\n return [4 /*yield*/, node.start()];\n case 2:\n _a.sent();\n // TODO: https://github.com/waku-org/js-waku/issues/2079\n // Dialing bootstrap peers right on start in order to have Filter subscription initiated properly\n return [4 /*yield*/, node.dial(\"/dns4/node-01.do-ams3.waku.test.status.im/tcp/8000/wss\")];\n case 3:\n // TODO: https://github.com/waku-org/js-waku/issues/2079\n // Dialing bootstrap peers right on start in order to have Filter subscription initiated properly\n _a.sent();\n return [4 /*yield*/, node.dial(\"/dns4/node-01.ac-cn-hongkong-c.waku.test.status.im/tcp/8000/wss\")];\n case 4:\n _a.sent();\n return [4 /*yield*/, node.dial(\"/dns4/node-01.gc-us-central1-a.waku.test.status.im/tcp/8000/wss\")];\n case 5:\n _a.sent();\n return [4 /*yield*/, waitForRemotePeer(node)];\n case 6:\n _a.sent();\n peerId = node.libp2p.peerId.toString();\n encoder = createEncoder({\n contentTopic: DEFAULT_CONTENT_TOPIC,\n });\n startLightPushSequence = function (numMessages_1) {\n var args_1 = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args_1[_i - 1] = arguments[_i];\n }\n return __awaiter(_this, __spreadArray([numMessages_1], args_1, true), void 0, function (numMessages, period) {\n var sequenceHash, sequenceTotal, sequenceIndex, sendMessage;\n var _this = this;\n if (period === void 0) { period = 3000; }\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, hashNumber(generateRandomNumber())];\n case 1:\n sequenceHash = _a.sent();\n sequenceTotal = numMessages;\n sequenceIndex = 0;\n sendMessage = function () { return __awaiter(_this, void 0, void 0, function () {\n var message, payload, result, messageElement, messagesSent, error_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n message = ProtoSequencedMessage.create({\n hash: sequenceHash,\n total: sequenceTotal,\n index: sequenceIndex,\n sender: peerId,\n });\n payload = ProtoSequencedMessage.encode(message).finish();\n return [4 /*yield*/, node.lightPush.send(encoder, {\n payload: payload,\n timestamp: new Date(),\n })];\n case 1:\n result = _a.sent();\n console.log(\"light push successes: \", result.successes.length);\n console.log(\"light push failures: \", result.failures.length);\n if (result.successes.length > 0) {\n // Push to telemetry client\n telemetryClient.push([\n {\n messageType: TelemetryType.LIGHT_PUSH_FILTER,\n timestamp: Math.floor(new Date().getTime() / 1000),\n peerIdSender: peerId,\n peerIdReporter: peerId,\n sequenceHash: sequenceHash,\n sequenceTotal: sequenceTotal,\n sequenceIndex: sequenceIndex,\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: utils.contentTopicToPubsubTopic(DEFAULT_CONTENT_TOPIC),\n },\n ]);\n messageElement = document.createElement(\"div\");\n messagesSent = document.getElementById(\"messagesSent\");\n messageElement.textContent = \"Message: \".concat(sequenceHash, \" \").concat(sequenceIndex, \" of \").concat(sequenceTotal);\n messagesSent.insertBefore(messageElement, messagesSent.firstChild);\n messagesSent.insertBefore(document.createElement(\"br\"), messagesSent.firstChild);\n document.dispatchEvent(messageSentEvent);\n // Increment sequence\n sequenceIndex++;\n }\n if (result.failures.length > 0) {\n console.error(\"Failed to send message\", result.failures);\n }\n if (sequenceIndex < sequenceTotal) {\n setTimeout(sendMessage, period); // Schedule the next send\n }\n else {\n document.dispatchEvent(sequenceCompletedEvent);\n }\n return [3 /*break*/, 3];\n case 2:\n error_1 = _a.sent();\n console.error(\"Error sending message\", error_1);\n return [3 /*break*/, 3];\n case 3: return [2 /*return*/];\n }\n });\n }); };\n sendMessage(); // Start the recursive sending\n return [2 /*return*/];\n }\n });\n });\n };\n startFilterSubscription = function () { return __awaiter(_this, void 0, void 0, function () {\n var decoder, messagesReceived, subscriptionCallback;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n decoder = createDecoder(DEFAULT_CONTENT_TOPIC);\n messagesReceived = document.getElementById(\"messagesReceived\");\n subscriptionCallback = function (message) {\n var sequencedMessage = ProtoSequencedMessage.decode(message.payload);\n // Don't bother reporting messages sent by this same node\n if (sequencedMessage.sender === peerId) {\n return;\n }\n telemetryClient.push([\n {\n messageType: TelemetryType.LIGHT_PUSH_FILTER,\n timestamp: Math.floor(new Date().getTime() / 1000),\n peerIdSender: sequencedMessage.sender,\n peerIdReporter: peerId,\n sequenceHash: sequencedMessage.hash,\n sequenceTotal: sequencedMessage.total,\n sequenceIndex: sequencedMessage.index,\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: utils.contentTopicToPubsubTopic(DEFAULT_CONTENT_TOPIC),\n },\n ]);\n var messageElement = document.createElement(\"div\");\n messageElement.textContent = \"Message: \".concat(sequencedMessage.hash, \" \").concat(sequencedMessage.index, \" of \").concat(sequencedMessage.total);\n messagesReceived.appendChild(messageElement);\n messagesReceived.appendChild(document.createElement(\"br\"));\n };\n return [4 /*yield*/, node.filter.subscribe(decoder, subscriptionCallback)];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n }); };\n return [2 /*return*/, {\n node: node,\n startLightPushSequence: startLightPushSequence,\n startFilterSubscription: startFilterSubscription,\n }];\n }\n });\n });\n}\n(function () { return __awaiter(void 0, void 0, void 0, function () {\n function startSequence() {\n var numMessages = Math.floor(Math.random() * 16) + 5;\n var messagePeriod = Math.floor(Math.random() * 2001) + 5000;\n startLightPushSequence(numMessages, messagePeriod);\n }\n var telemetryClient, _a, node, startLightPushSequence, startFilterSubscription, runningScreen, sentMessagesCount, sentMessagesCounter;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n telemetryClient = new TelemetryClient(TELEMETRY_URL, 5000);\n return [4 /*yield*/, app(telemetryClient)];\n case 1:\n _a = _b.sent(), node = _a.node, startLightPushSequence = _a.startLightPushSequence, startFilterSubscription = _a.startFilterSubscription;\n window.waku = node;\n runningScreen = document.getElementById(\"runningScreen\");\n runningScreen.style.display = \"block\";\n return [4 /*yield*/, telemetryClient.start()];\n case 2:\n _b.sent();\n startFilterSubscription();\n sentMessagesCount = 0;\n sentMessagesCounter = document.getElementById(\"numSent\");\n document.addEventListener(\"messageSent\", function () {\n sentMessagesCount++;\n sentMessagesCounter.textContent = sentMessagesCount.toString();\n });\n document.addEventListener(sequenceCompletedEvent.type, function () { return startSequence(); });\n startSequence();\n return [2 /*return*/];\n }\n });\n}); })();\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","inquire","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","moduleName","mod","eval","e","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","formatArgs","useColors","namespace","humanize","diff","color","lastC","match","save","namespaces","storage","setItem","removeItem","error","load","r","getItem","process","env","DEBUG","window","type","__nwjs","navigator","userAgent","toLowerCase","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","RegExp","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","v","message","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","self","curr","Date","ms","prev","coerce","unshift","format","formatter","selectColor","extend","defineProperty","enumerable","configurable","get","set","init","delimiter","newDebug","toNamespace","regexp","substring","default","stack","disable","names","map","skips","enable","name","forEach","key","hash","abs","Denque","array","_capacity","capacity","_head","_tail","isArray","_fromArray","_capacityMask","_list","peekAt","peek","peekFront","peekBack","item","_growArray","pop","head","_shrinkArray","tail","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","_nextPowerOf2","fullCopy","src","dest","newList","num","nextPow2","max","assign","obj","props","code","TypeError","_","ErrClass","create","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","constructor","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","result","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","cache","_cache","update","root","HI_BASE32_NO_NODE_JS","versions","node","global","COMMON_JS","HI_BASE32_NO_COMMON_JS","AMD","BASE32_ENCODE_CHAR","BASE32_DECODE_CHAR","blocks","throwInvalidUtf8","position","partial","substr","decodeAsBytes","base32Str","v1","v2","v3","v4","v5","v6","v7","v8","bytes","remain","asciiOnly","str","followingChars","toUtf8String","indexOf","input","notString","ArrayBuffer","encodeBytes","encodeAscii","encodeUtf8","asBytes","base32","electron","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","isView","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","formatMessage","empty","cloneArray","newArray","createOutputMethod","bits","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","s","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","w","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","reset","finalized","block","blockCount","byteCount","outputBlocks","extraBytes","isString","lastByteIndex","f","x","right","o","encodeString","strs","paddingBytes","zeros","finalize","hex","arrayBuffer","Uint32Array","digest","h","c0","c3","c4","c5","c6","c7","c8","c9","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","globalThis","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneOptionObject","mergeKeys","merged","config","merge","resultIndex","indices","filter","includes","option","m","d","plural","msAbs","isPlural","exec","parseFloat","parse","isFinite","long","fmtShort","library","_validBytes","isInteger","_x86Multiply","_x86Rotl","_x86Fmix","_x64Add","_x64Multiply","_x64Rotl","_x64LeftShift","_x64Xor","_x64Fmix","x86","hash32","seed","inputValidation","remainder","h1","k1","hash128","h2","h3","h4","k2","k3","k4","x64","murmurHash3","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","ip","ref","base","dmax","net","mask","maskLong","error1","bitmask","netLong","hostmask","first","last","broadcast","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","output","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","blockSize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","util","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","ctr","gcm","sbox","isbox","rcon","mix","imix","Nb","xtime","e2","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","sub","a","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","_fromDer","depth","getByte","tagClass","bitStringContents","longFormBytes","getInt","_getValueLength","strict","constructed","getBytes","Class","UNIVERSAL","Type","BITSTRING","decodeBitStrings","savedRead","savedRemaining","unused","composed","used","tc","CONTEXT_SPECIFIC","ex","BMPSTRING","getInt16","asn1Options","APPLICATION","PRIVATE","NONE","BOOLEAN","INTEGER","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","original","copy","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","values","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","carry","at","_encodeWithByteBuffer","regex","Buffer","from","reverse","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","finish","pad","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","tagLength","_tag","tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","y","z_i","v_i","out","lsb","tableMultiply","z","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","left","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_key","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","BigInteger","data","fromNumber","fromString","nbi","am3","xl","xh","jsbn","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","r2","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","min","q","pm","pt","ts","nsh","ys","y0","yt","d1","d2","qd","isEven","exp","g","negate","toRadix","km","bitLength","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","prng","random","modPow","byteValue","shortValue","toByteArray","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","add","divideAndRemainder","g2","is1","modInverse","ac","u","gcd","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","password","saltSize","dkLen","encryptionAlgorithm","encryptedData","salt","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","version","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","digestLength","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","crypto","isNodejs","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","maskLength","encode_rsa_oaep","label","mgf1Md","mgf1","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","decode_rsa_oaep","em","expectedLength","maskedSeed","db","lHashPrime","in_ps","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","range","workerScript","estimateCores","cores","generate","addEventListener","workerMessage","found","terminate","target","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","_crypto","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","getRandomValues","globalScope","msCrypto","arr","entropy","QuotaExceededError","pool","generateSync","increment","nextTick","seedFile","_reseed","randomBytes","collectInt","registerWorker","worker","removeEventListener","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","sha256","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","word","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","K","getInt16Le","R","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","digestAlgorithm","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","toHex","yhex","ed","expected","xhex","createKeyPairGenerationState","state","eInt","qBits","pBits","pqState","stepKeyPairGenerationState","t2","t1","total","p1","q1","phi","privateKey","setPrivateKey","publicKey","setPublicKey","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","privateKeyFromPem","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","getPrime","_generateKeyPair","scheme","schemeOptions","signature","_parseAllDigestBytes","verify","algorithmIdentifier","md2","sha224","sha384","setRsaPrivateKey","rsaEncryption","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","_state","fullMessageLength","messageLengthSize","messageLength64","int32s","h0","encoding","_update","finalBlock","s2","_k","h5","h6","h7","s0","maj","_states","_h","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","setTimeout","callbacks","stopPropagation","MutationObserver","now","attr","div","createElement","observe","attributes","oldSetImmediate","setAttribute","byteLength","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","DataView","byteOffset","writeOffset","accommodate","amount","dst","setUint8","view","raw","Uint16Array","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","subarray","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","prop","_clearItems","_callStorageFunction","func","location","idx","clearItems","part","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","URL","createObjectURL","st","et","sample","samples","avg","revokeObjectURL","results","overlaps","r1","overlap","common","timeType","commonRe","json","nested","google","protobuf","Any","fields","type_url","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","kind","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","genValuePartial_fromObject","gen","field","fieldIndex","defaultAlreadyEmitted","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","low","high","unsigned","toNumber","arrayDefault","hasKs2","_fieldsArray","types","defaults","basic","packed","rfield","required","missing","wireType","mapKey","genTypePartial","ReflectionObject","className","Namespace","comment","comments","valuesOptions","reserved","fromJSON","enm","toJSON","toJSONOptions","keepComments","Boolean","isReservedId","isReservedName","allow_alias","Field","ruleRe","isObject","defaultValue","Long","extensionField","declaringField","_packed","getOption","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","newBuffer","emptyObject","emptyArray","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","_configure","Type_","build","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","configure","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","define","resolveAll","lookup","filterTypes","parentAlreadyChecked","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","propName","opt","find","newValue","setProperty","newOpt","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","skip","cmnt","isProto3","applyCase","camelCase","illegal","insideTryCatch","readString","readValue","acceptTypeRef","parseNumber","readRanges","acceptStrings","parseId","dummy","ifBlock","parseOption","parseInlineOptions","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseType","parseEnum","service","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseMapField","parseOneOf","extensions","endsWith","startsWith","lcFirst","ucFirst","parseGroup","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","LongBits","indexOutOfRange","writeLength","RangeError","create_array","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skipType","BufferReader_","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","deferred","files","SYNC","resolvePath","sync","cb","getBundledFileName","lastIndexOf","altname","parsed","queued","weak","readFileSync","isNode","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","isReserved","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","lastCommentLine","stringDelim","subject","setComment","isLeading","lineEmpty","leading","commentOffset","trim","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","repeat","isDoc","isLeadingComment","actual","ret","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","fork","ldelim","typeName","bake","safePropBackslashRe","safePropQuoteRe","camelCaseRe","decorateRoot","decorateEnumIndex","setProp","zero","zzEncode","zeroHash","toLong","fromHash","toHash","part0","part1","part2","newError","CustomError","captureStackTrace","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","allocUnsafe","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","Op","noop","State","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","BufferWriter_","writeStringBuffer","writeBytesBuffer","BufferSourceConverter","toArrayBuffer","toUint8Array","toView","isBufferSource","isEqual","aView","bView","buffers","res","STRING_TYPE","HEX_REGEX","BASE64_REGEX","BASE64URL_REGEX","Utf8Converter","uintArray","encodedString","Utf16Converter","littleEndian","dataView","getUint16","setUint16","Convert","isHex","isBase64","isBase64Url","ToString","enc","ToUtf8String","ToBinary","ToHex","ToBase64","ToBase64Url","FromString","FromUtf8String","FromBinary","FromHex","FromBase64","FromBase64Url","btoa","formatted","formatString","base64url","Base64Padding","DEFAULT_UTF8_ENCODING","stringLength","resultView","byte","hexString","ToUtf16String","FromUtf16String","padCount","__webpack_module_cache__","leafPrototypes","getProto","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","__esModule","ns","def","current","getOwnPropertyNames","definition","toStringTag","N1","N2","N3","N4","N5","N6","N7","MSB","REST","encodingLength","MAX_SAFE_INTEGER","encodeUint8Array","decodeUint8Array","encodeUint8ArrayList","decodeUint8ArrayList","d8b","MAX_SAFE_NUMBER_INTEGER","BigInt","MIN_SAFE_NUMBER_INTEGER","MIN_SAFE_INTEGER","toBigInt","fromBigInt","negative","TWO_32","readFixed32End","Uint8ArrayReader","int64Number","int64String","uint64Number","uint64String","sint64Number","sint64String","fixed64Number","fixed64String","sfixed64Number","sfixed64String","decodeMessage","codec","createReader","ALPHABET","BASE_MAP","xc","BASE","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","prefixCodePoint","codePointAt","ComposedDecoder","decoders","Codec","baseX","rfc4648","bitsPerChar","codes","written","SyntaxError","base10","base16","base16upper","base2","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","char","byt","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64urlpad","base8","identity","TextDecoder","TextEncoder","textEncoder","textDecoder","MSBALL","INT","MSB$1","REST$1","N8","N9","oldOffset","counter","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","async","link","cid","toStringV0","baseCache","toStringV1","WeakMap","Map","CID","asCID","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","other","unknown","aa","bb","ii","for","encodeCID","cidSymbol","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","createCodec","ascii","latin1","bufferPool","Uint8ArrayWriter","writeVarint32","super","encodeMessage","lengthDelimited","CODEC_TYPES","RateLimitProof","WakuMessage","FilterRequest","MessagePush","FilterRpc","TopicOnlyMessage","FilterSubscribeRequest","PushRequest","PushResponse","Index","PagingInfo","ContentFilter","HistoryQuery","HistoryResponse","PeerInfo","PeerExchangeQuery","PeerExchangeResponse","WakuMetadataRequest","WakuMetadataResponse","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","isDefined","groupByContentTopic","groupedDecoders","decs","contentTopic","wait","_codec","proof","merkleRoot","epoch","shareX","shareY","nullifier","rlnIdentifier","payload","timestamp","meta","rateLimitProof","ephemeral","limits","subscribe","topic","contentFilters","contentFilters$","messages","messages$","requestId","FilterSubscribeType","__FilterSubscribeTypeValues","filterSubscribeType","pubsubTopic","contentTopics","SUBSCRIBER_PING","FilterSubscribeResponse","statusCode","statusDesc","wakuMessage","isSuccess","info","PushRpc","receiverTime","senderTime","Direction","__DirectionValues","pageSize","direction","pagingInfo","startTime","endTime","HistoryError","__HistoryErrorValues","HistoryRpc","query","enr","numPeers","peerInfos","peerInfos$","PeerExchangeRPC","clusterId","shards","isSafeInteger","outputLen","blockLen","exists","instance","checkFinished","destroyed","finished","rotr","asyncLoop","iters","tick","toBytes","arrays","sum","Hash","_cloneInto","toStr","hashCons","hashC","bytesLength","Maj","HashMD","padOffset","isLE","take","roundClean","digestInto","fill","setBigUint64","_32n","_u32_max","wh","wl","setUint32","oview","outLen","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","C","E","F","G","H","getUint32","W15","W2","T2","Protocols","PageDirection","Tags","EPeersByDiscoveryEvents","EConnectionStateEvents","DefaultPubsubTopic","DEFAULT_CLUSTER_ID","bytesToUtf8","byteArrays","totalLength","acc","singleShardInfoToPubsubTopic","shardInfo","shard","shardInfoToPubsubTopics","Set","contentTopicToPubsubTopic","application","pubsubTopicToSingleShardInfo","pubsubTopics","ensurePubsubTopicIsConfigured","configuredTopics","contentTopicToShardIndex","networkShards","generation","topicName","ensureValidContentTopic","dataview","getBigUint64","determinePubsubTopic","pubsubTopicShardInfo","ensureShardingConfigured","isShardsConfigured","isContentTopicsConfigured","isApplicationVersionConfigured","shardingParams","decodeRelayShard","byteIndex","bitIndex","numIndices","encodeRelayShard","APP_NAME","Logger","_info","_warn","_error","createDebugNamespace","logger","OneMillion","DecodedMessage","proto","_rawTimestamp","metaSetter","toWire","toProtoObj","protoMessage","valueOf","createEncoder","fromWireToProtoObj","fromProtoObj","createDecoder","entry","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","iterator","append","prepend","prependAll","consume","trunc","beginInclusive","endExclusive","_subList","sublist","list","bufStart","sliceStartInBuf","sliceEndsInBuf","search","needle","M","rightmostPositions","Int32Array","lastPatIndex","getBigInt64","setBigInt64","getFloat32","setFloat32","getFloat64","setFloat64","fromUint8Arrays","thing","defaultEncoder","lengthLength","lengthBuf","encodeLength","lengthEncoder","maybeYield","single","ReadMode","defaultDecoder","LENGTH","dataLength","lengthDecoder","maxLengthLength","maxDataLength","dataLengthLength","onLength","DATA","onData","pDefer","promise","fromReader","FixedFIFO","top","btm","hwm","FIFO","splitLimit","calculateSize","AbortError","pushable","getNext","onNext","ended","onEnd","drain","bufferNext","objectMode","bufferError","queueMicrotask","throw","readableLength","onEmpty","signal","throwIfAborted","cancel","race","_pushable","sources","syncSources","all","pipe","rest","isDuplex","duplex","isIterable","fns","sink","duplexPipelineFn","rawPipe","stream","sourceWrap","StreamManager","multicodec","getConnections","streamPool","handlePeerUpdateStreamPool","getStream","peer","peerIdStr","streamPromise","createStream","delete","prepareStream","retries","connection","connections","latestConnection","timeline","selectConnection","newStream","backoff","timeoutPromise","detail","protocols","isConnectedTo","peerId","some","BaseProtocol","components","addLibp2pEventListener","removeLibp2pEventListener","streamManager","connectionManager","peerStore","allPeers","peers","getPeersForProtocol","connectedPeers","getPeers","maxBootstrapPeers","filteredPeers","bootstrapPeers","tags","BOOTSTRAP","nonBootstrapPeers","selectedPeers","randomIndex","randomPeer","filterPeersByDiscovery","peerPromises","remotePeer","protocol","encodedPeerShardInfo","metadata","peerShardInfo","getConnectedPeersForProtocolAndShard","sortedFilteredPeers","pingBytes","ping","sortPeersByLatency","randomUUID","rnds8","byteToHex","rnds","unsafeStringify","FilterPushRpc","FilterSubscribeRpc","createSubscribeRequest","SUBSCRIBE","createUnsubscribeRequest","UNSUBSCRIBE","createUnsubscribeAllRequest","UNSUBSCRIBE_ALL","createSubscriberPingRequest","FilterCodecs","FilterCore","handleIncomingMessage","libp2p","handle","onRequest","maxInboundStreams","streamData","success","failure","GENERIC_FAIL","REMOTE_PEER_REJECTED","unsubscribe","REMOTE_PEER_FAULT","unsubscribeRequest","unsubscribeAll","createRequest","LightPushCore","preparePushMessage","EMPTY_PAYLOAD","isWireSizeUnderCap","isMessageSizeUnderCap","SIZE_TOO_BIG","ENCODE_FAILED","preparationError","NO_STREAM_AVAILABLE","DECODE_FAILED","EmptyMessage","createQuery","pageDirection","BACKWARD","FORWARD","directionToProto","StoreCore","queryPerPage","queryOpts","currentCursor","historyRpcQuery","reply","protoMsg","wire","nextCursor","responsePageSize","queryPageSize","TimeoutError","getDOMException","errorMessage","DOMException","getAbortedReason","reason","pTimeout","milliseconds","fallback","customTimers","clearTimeout","timer","cancelablePromise","aborted","POSITIVE_INFINITY","timeoutError","finally","normalizeEmitter","pEvent","arrayPromise","returnValue","rejectionEvents","multiArgs","resolveImmediately","flat","items","onItem","arguments_","rejectHandler","rejectionEvent","timeout","pEventMultiple","waitForRemotePeer","waku","timeoutMs","relay","Relay","Filter","store","Store","lightPush","LightPush","getEnabledProtocols","isStarted","promises","getMeshPeers","gossipSub","waitForGossipSubPeerInMesh","waitForConnectedPeer","services","rejectReason","awaitTimeout","rejectOnTimeout","metadataService","any","confirmOrAttemptHandshake","_resolve","TypedEventEmitter","EventTarget","dispatchEvent","safeDispatchEvent","CustomEventPolyfill","Event","CustomEvent","KeepAliveManager","pingKeepAliveTimers","relayKeepAliveTimers","libp2pPing","pingKeepAlive","pingPeriodSecs","relayKeepAlive","relayPeriodSecs","interval","setInterval","intervals","scheduleRelayPings","clearInterval","stopAll","connectionsExist","ConnectionManager","configuredPubsubTopics","static","keepAliveManager","dialAttemptsForPeer","dialErrorsForPeer","currentActiveParallelDialCount","pendingPeerDialQueue","online","isConnected","toggleOnline","CONNECTION_STATUS","toggleOffline","keepAliveOptions","instances","getPeersByDiscovery","peersDiscovered","peersConnected","conn","peersDiscoveredByBootstrap","peersDiscoveredByPeerExchange","peersDiscoveredByLocal","peersConnectedByBootstrap","peersConnectedByPeerExchange","peersConnectedByLocal","getTagNamesForPeer","PEER_EXCHANGE","LOCAL","DISCOVERED","CONNECTED","maxDialAttemptsForPeer","maxBootstrapPeersAllowed","maxParallelDials","run","dialPeerStorePeers","dialPromises","peerInfo","attemptDial","startPeerDiscoveryListener","startPeerConnectionListener","startPeerDisconnectionListener","onEventHandlers","dialPeer","dialAttempt","dial","AggregateError","processDialQueue","dropConnection","hangUp","shouldDialPeer","dispatchDiscoveryEvent","PEER_CONNECT_BOOTSTRAP","PEER_CONNECT_PEER_EXCHANGE","isPeerTopicConfigured","getPeerShardInfo","isPeerDialableBasedOnBootstrapStatus","tagName","isBootstrap","PEER_DISCOVERY_BOOTSTRAP","PEER_DISCOVERY_PEER_EXCHANGE","shardInfoBytes","MetadataCodec","Metadata","libp2pComponents","handshakesConfirmed","registrar","encodedShardInfo","encodedResponse","decodeMetadataResponse","savePeerShardInfo","NO_PEER_AVAILABLE","wakuMetadata","raceSignal","errorCode","QueuelessPushable","readNext","haveNext","nextResult","lpStream","readBuffer","W","abortPromise","unwrap","originalStream","yieldBytes","byteStream","decodeLength","lengthBuffer","writeV","flatMap","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","wrapCipher","u8to16","Poly1305","t0","t3","t4","t5","t6","t7","isLast","hibit","r0","r3","r4","r5","r6","r7","r8","r9","h8","h9","d0","d3","d4","d5","d6","d7","d8","d9","opos","poly1305","wrapConstructorWithKey","sigma16","sigma32","sigma16_32","sigma32_32","isAligned32","MAX_COUNTER","U32_EMPTY","core","allowShortKeys","extendNonceFn","counterLength","counterRight","rounds","nonce","toClean","sigma","k32","nonceNcLen","nc","n32","isAligned","d32","o32","pos32","posj","runCipher","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","oi","chacha20","xchacha20","ZEROS16","updatePadded","ZEROS32","computeTag","AAD","authKey","_poly1305_aead","xorStream","plaintext","plength","clength","ciphertext","chacha20poly1305","nonceLength","U32_MASK64","fromBig","lst","Ah","Al","_l","Bh","Bl","Cl","Ch","Dl","Dh","Eh","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_1n","_2n","padStart","_0","_9","_A","_F","_a","_f","hl","al","ai","n2","title","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reseed","sl","pred","validatorFns","bigint","function","boolean","stringOrUint8Array","Fp","isValid","validateObject","validators","optValidators","checkField","isOptional","checkVal","entries","_3n","_4n","_5n","_8n","power","modulo","pow2","invert","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","ORDER","bitLen","redef","BYTES","sqrtP","p1div4","eql","sqr","mul","nv","legendreC","Q","Z","Q1div2","neg","ge","tonelliShanks","FpSqrt","MASK","is0","isOdd","lhs","rhs","FpPow","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","getMinHashLength","wNAF","constTimeNegate","condition","windows","windowSize","unsafeLadder","elm","precomputeWindow","points","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFCached","precomputesMap","transform","_WINDOW_SIZE","comp","validateBasic","curve","validateField","Gx","Gy","VERIFY_DEFAULT","zip215","twistedEdwards","curveDef","CURVE","adjustScalarBytes","domain","uvRatio","mapToCurve","validateOpts","prehash","cHash","cofactor","modP","phflag","inBig","inRange","in0MaskRange","assertInRange","assertGE0","CURVE_ORDER","pointPrecomputes","isPoint","Point","ey","ez","toAffine","fromAffine","normalizeZ","toInv","_setWindowSize","assertValidity","X","Y","X2","Y2","Z2","Z4","aX2","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","wnaf","scalar","multiplyUnsafe","isSmallOrder","isTorsionFree","iz","ax","ay","zz","clearCofactor","fromHex","normed","lastByte","y2","isXOdd","isLastByteOdd","fromPrivateKey","privKey","getExtendedPublicKey","point","toRawBytes","modN","modN_LE","hashed","pointBytes","hashDomainToScalar","msgs","verifyOpts","getPublicKey","sig","SB","ExtendedPoint","utils","randomPrivateKey","precompute","ED25519_P","ED25519_SQRT_M1","_10n","_20n","_40n","_80n","ed25519_pow_2_252_3","b80","b160","b240","b250","pow_p_5_8","ed25519","vx2","root1","root2","useRoot1","useRoot2","noRoot","x25519","montgomeryBits","powPminus2","Gu","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","assertFieldElement","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","getSharedSecret","montgomery","ELL2_C1","FpSqrtEven","HMAC","iHash","oHash","HKDF_COUNTER","EMPTY_BUFFER","defaultCrypto","hashSHA256","getHKDF","ck","ikm","prk","extract","okm","HMACTmp","expand","generateX25519KeyPair","secretKey","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","chaCha20Poly1305Decrypt","uint16BEEncode","uint16BEDecode","UnexpectedPeerError","InvalidCryptoExchangeError","AggregateCodeError","ERR_TIMEOUT","bigIntegerToUintBase64url","base64urlToBigInteger","isPromise","PUBLIC_KEY_BYTE_LENGTH","PRIVATE_KEY_BYTE_LENGTH","KEYS_BYTE_LENGTH","concatKeys","privateKeyRaw","win","nativeCrypto","derivedEmptyPasswordKey","alg","ext","key_ops","kty","exporter","aesGcm","cryptoKey","importKey","deriveParams","runtimeDerivedEmptyPassword","deriveKey","rawKey","saltLength","encryptedKey","KeyType","__KeyTypeValues","PublicKey","PrivateKey","Data","Ed25519PublicKey","ensureKey","marshal","Ed25519","Ed25519PrivateKey","_publicKey","public","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","generateKeyPairFromSeed","derivePublicFromPrivate","jwKey","convertKey","fkey","jwk2pub","jwk2priv","keySize","jwk","MAX_KEY_SIZE","RsaPublicKey","RSA","RsaPrivateKey","genSecret","dp","dq","qi","unmarshalRsaPublicKey","fromJwk","b2n","h2b","DER","Err","_parseInt","toSig","sBytes","rBytesLeft","hexFromSig","shl","rhl","rl","weierstrass","bits2int","bits2int_modN","lowS","compressedLen","uncompressedLen","invN","ProjectivePoint","normPrivateKeyToScalar","weierstrassEquation","isWithinCurveOrder","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_c","_isCompressed","x2","x3","assertGE","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","isCompressed","_bits","weierstrassPoints","cat","sqrtError","suffix","numToNByteStr","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","fromDER","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","minLen","reduced","isProbPub","delta","ORDER_MASK","int2octets","defaultSigOpts","defaultVerOpts","privateA","publicB","k2sig","extraEntropy","ent","h1int","seedArgs","kBytes","ik","normS","prepSig","drbg","sg","_sig","derError","is","getHash","secp256k1P","secp256k1N","divNearest","_6n","_11n","_22n","_23n","_44n","_88n","b88","b176","b220","b223","secp256k1","defHash","createCurve","POW_2_128","validatePublicKey","Secp256k1PublicKey","Secp256k1","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","unsupportedKey","peerIdSymbol","isPeerId","inspect","baseDecoder","LIBP2P_KEY_CODE","MARSHALLED_ED225519_PUBLIC_KEY_LENGTH","MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH","PeerIdImpl","toCID","peerIdFromString","RSAPeerIdImpl","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","peerIdFromCID","NoiseExtensions","NoiseHandshakePayload","getPayload","localPeer","staticPublicKey","signedPayload","decoded","unmarshalRsaPrivateKey","signPayload","getHandshakePayload","libp2pPublicKey","identityKey","identitySig","webtransportCerthashes","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","isValidPublicKey","pk","Nonce","getUint64","assertValue","AbstractHandshake","forComponent","encryptWithAd","decryptWithAd","valid","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","dh","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","cs1","cs2","writeMessageRegular","ne","readMessageRegular","XX","initializeInitiator","prologue","rs","psk","initializeResponder","writeMessageA","hs","writeMessageB","spk","writeMessageC","messageBuffer","readMessageA","readMessageB","valid1","valid2","readMessageC","initSession","initiator","mc","sendMessage","session","resultingBuffer","recvMessage","resultingPlaintext","resultingValid","logLocalEphemeralKeys","keyLogger","logRemoteEphemeralKey","XXHandshake","isInitiator","remoteExtensions","xx","staticKeypair","handshake","propose","trace","encode0","receivedMessageBuffer","decode0","exchange","decode1","decodedPayload","setRemoteNoiseExtension","encode1","encode2","decode2","getCS","getRemoteStaticKey","encryption","Noise","staticKeys","metrics","staticNoiseKey","prologueBytes","xxHandshakeSuccesses","registerCounter","help","xxHandshakeErrors","encryptedPackets","decryptedPackets","decryptErrors","registerMetrics","secureOutbound","wrappedConnection","performHandshake","createSecureConnection","secureInbound","performXXHandshake","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","noise","peerDiscoverySymbol","MAX_IPV6_LENGTH","MAX_IPV4_LENGTH","parser","readAtomically","parseWith","peekChar","readChar","readGivenChar","readSeparator","sep","readNumber","radix","maxDigits","allowZeroPrefix","maxBytes","digitCount","leadingChar","hasLeadingZero","maxValue","digit","readIPv4Addr","ix","readIPv6Addr","readGroups","groups","ipv4","headSize","headIp4","limit","tailSize","readIPAddr","isIPv4","new","isIPv6","isIP","isV4","isV6","sections","v4Buffer","argv","V","convertToString","ipBuff","ipString","bytes2ip","bytes2str","bytes2port","address","bytes2mh","addrBytes","portBytes","bytes2onion","bytes2mb","convertToBytes","ip2bytes","str2bytes","port2bytes","mh","mh2bytes","addr","port","portBuf","onion2bytes","onion32bytes","mbstr","mb","anybaseDecoder","mb2bytes","row","resolvable","createProtocol","bytesToMultiaddrParts","tuples","stringTuples","sizeForAddr","ParseError","stringAddr","stringTuplesToString","tup","cleanPath","tuplesToBytes","DNS_CODES","Multiaddr","stringToMultiaddrParts","isMultiaddr","toOptions","family","transport","host","zone","tcp","udp","ip4","ip6","dns6","ip6zone","protos","protoCodes","protoNames","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","p2p","tuple","getPath","resolvableProto","resolver","resolvers","nodeAddress","isThinWaistAddress","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","QUICV1","_WebSockets","WebSockets","_WebSocketsSecure","WebSocketsSecure","HTTP","HTTPS","_WebRTCDirect","WebRTCDirect","_WebTransport","WebTransport","P2PWebRTCStar","P2PWebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","P2P","makeMatchesFunction","partialMatch","ma","arg","matches","pnames","Bootstrap","peerData","multiaddrs","_discoverBootstrapPeers","tagValue","ttl","tagTTL","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","PeerRecord","AddressInfo","multiaddr","seq","addresses","peerRecord","seqNumber","DOMAIN","CODEC","marshaled","localeCompare","every","arrayEquals","asyncTick","DK","PRF","PRFSalt","_password","_salt","_opts","checkOpts","pbkdf2Init","prfW","ti","Ti","pbkdf2Output","utilFromBase","inputBuffer","inputBase","utilToBase","internalReserved","internalValue","biggest","retBuf","retView","basis","utilConcatView","views","outputLength","prevLength","utilDecodeTC","valueHex","condition1","condition2","warnings","bigIntBuffer","bigIntView","bigInt","smallIntBuffer","smallIntView","padNumber","inputNumber","fullLength","dif","assertBigInt","baseBlock","inputOffset","ViewWriter","final","powers2","digitsString","EMPTY_STRING","EMPTY_VIEW","END_OF_CONTENT_NAME","OCTET_STRING_NAME","BIT_STRING_NAME","HexBlock","BaseClass","isHexOnly","valueHexView","fromBER","endLength","toBER","sizeOnly","NAME","LocalBaseBlock","valueBeforeDecode","valueBeforeDecodeView","blockName","ValueBlock","LocalIdentificationBlock","idBlock","_b","_d","tagNumber","isConstructed","firstOctet","encodedBuf","encodedView","curView","inputView","intBuffer","tagNumberMask","intTagNumberBuffer","tagNumberBufferMaxLength","tempBufferView","LocalLengthBlock","lenBlock","isIndefiniteForm","longFormUsed","lenOffset","lengthBufferView","typeStore","BaseBlock","primitiveSchema","valueBlockType","valueBlock","resultOffset","_writer","prepareIndefiniteForm","idBlockBuf","valueBlockBuf","lenBlockBuf","onAsciiEncoding","inputBuffer1","inputBuffer2","view1","view2","Constructed","BaseStringBlock","stringValueBlockType","getValue","setValue","fromBuffer","LocalPrimitiveValueBlock","_a$w","_a$v","_a$u","_a$t","_a$s","_a$r","_a$q","_a$p","_a$o","_a$n","_a$m","_a$l","_a$k","_a$j","_a$i","_a$h","_a$g","_a$f","_a$e","_a$d","_a$c","_a$b","_a$a","_a$9","_a$8","_a$7","_a$6","_a$5","_a$4","_a$3","_a$2","_a$1","Primitive","localFromBER","incomingOffset","returnObject","newASN1Type","EndOfContent","Integer","BitString","OctetString","Null","ObjectIdentifier","Enumerated","Utf8String","RelativeObjectIdentifier","TIME","Sequence","NumericString","PrintableString","TeletexString","VideotexString","UTCTime","GeneralizedTime","GraphicString","VisibleString","GeneralString","UniversalString","CharacterString","BmpString","DATE","TimeOfDay","DateTime","newObject","inputObject","newType","localChangeType","LocalConstructedValueBlock","currentOffset","LocalEndOfContentValueBlock","override","LocalBooleanValueBlock","octet","LocalOctetStringValueBlock","currentBlockName","asn","content","LocalBitStringValueBlock","unusedBits","bitsStr","viewAdd","second","firstView","secondView","firstViewCopy","firstViewCopyLength","secondViewCopy","secondViewCopyLength","power2","viewSub","LocalIntegerValueBlock","_valueDec","setValueHex","valueDec","modValue","tempBuf","tempView","toDER","updatedView","firstBit","currentByte","bitNumber","asn1View","flag","byteNumber","bigIntValue","secondInt","convertToDER","convertFromDER","LocalSidValueBlock","isFirstSid","valueBigInt","sidValue","LocalObjectIdentifierValueBlock","sidBlock","retBuffers","valueBuf","pos1","pos2","sid","plus","parsedSID","sidStr","sidArray","LocalRelativeSidValueBlock","LocalRelativeObjectIdentifierValueBlock","LocalStringValueBlock","LocalSimpleStringValueBlock","LocalSimpleStringBlock","inputString","strLen","LocalUtf8StringValueBlock","LocalBmpStringValueBlock","LocalUniversalStringValueBlock","copyBuffer","valueView","strLength","codeBuf","codeView","valueDate","month","day","hour","minute","fromDate","toBuffer","inputDate","toDate","UTC","parserArray","outputArray","toISOString","millisecond","getUTCMilliseconds","timeString","dateTimeString","fractionPart","hourDifference","minuteDifference","differencePosition","differenceString","fractionPointPosition","fractionPartCheck","fractionResult","tempDate","getUTCDay","bnToBuf","bn","u8","bufToBn","MAX_RSA_KEY_SIZE","der","keyBuf","keyArr","encryptionKey","pbkdf2Params","finalWrapperBuf","Envelope","payloadType","RecordEnvelope","envelopeData","record","signData","formatSignaturePayload","envelope","createFromProtobuf","domainUint8Array","domainLength","payloadTypeLength","payloadLength","vals","pattern","literal","certhash","matcher","matchers","fmt","toParts","exactMatch","_DNS4","_DNS6","_DNSADDR","_DNS","_IP4","_IP6","_IP","_IP_OR_DOMAIN","IP_OR_DOMAIN","_TCP","_UDP","_QUIC","_QUICV1","QUIC_V0_OR_V1","_WEB","pbStream","lp","pb","isEnvWithDom","nodeType","isElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","isReactNative","product","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","signedPeerRecord","MAX_IDENTIFY_MESSAGE_SIZE","defaultValues","identifyProtocolStr","identifyPushProtocolStr","started","addressManager","maxOutboundStreams","maxPushIncomingStreams","maxPushOutgoingStreams","maxIdentifyMessageSize","maxObservedAddresses","runOnTransientConnection","protocolPrefix","nodeInfo","runOnConnectionOpen","identify","AgentVersion","ProtocolVersion","_handleIdentify","_handlePush","unhandle","pushToConnections","listenAddresses","getAddresses","seal","supportedProtocols","getProtocols","pushes","AbortSignal","close","abort","_identify","cleanObservedAddr","getCleanMultiaddr","getObservedAddrs","addObservedAddr","peerRecordEnvelope","remoteAddr","isCertified","openAndCertify","existingPeer","storedEnvelope","storedRecord","patch","closeSource","getIterator","createAbortError","clearMethods","defaultClear","defaultSet","timeoutId","settle","rejectFunction","signalListener","delayPromise","createDelay","RateLimiter","memoryStorage","duration","blockDuration","execEvenly","execEvenlyMinDelayMs","keyPrefix","MemoryStorage","pointsToConsume","rlKey","getKey","secDuration","_getKeySecDuration","incrby","remainingPoints","consumedPoints","msBeforeNext","isFirstInDuration","delayMs","penalty","reward","msDuration","initPoints","customDuration","parseKey","durationSec","existing","msBeforeExpires","expiresAt","getTime","durationMs","unref","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","MAX_MSG_SIZE","_buffer","_headerInfo","_maxMessageSize","_maxUnprocessedMessageQueueSize","maxMessageSize","maxUnprocessedMessageQueueSize","_decodeHeader","readVarInt","POOL_SIZE","_pool","_poolOffset","AbstractStream","readStatus","writeStatus","sinkController","sinkEnd","closed","endErr","streamSource","onCloseRead","onCloseWrite","onReset","onAbort","sendCloseWriteTimeout","sendingData","AbortController","onSourceEnd","sendNewStream","abortListener","sendData","sendCloseWrite","onSinkEnd","closeRead","closeWrite","sendCloseRead","sendReset","_closeSinkAndSource","_closeSink","_closeSource","remoteCloseWrite","remoteCloseRead","sourcePush","sourceReadableLength","MplexStream","streamId","maxDataSize","toSend","printMessage","MplexStreamMuxer","_streamId","_streams","_source","closeController","rateLimiter","closeTimeout","initiators","receivers","_createSink","disconnectThreshold","streams","registry","_newStream","_newReceiverStream","maxMsgSize","onStreamEnd","_handleIncoming","onIncomingStream","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","mplex","ERR_WRONG_PING_ACK","PingService","handleMessage","openConnection","transportSymbol","FaultTolerance","ASSUME_HTTP_CODES","extractSNI","sniProtoCode","hasTLS","interpretNext","headProtoCode","headProtoVal","restMa","interpreter","interpreters","restVal","tailProto","dnsaddr","dns4","dns","ipfs","http","maHasTLS","sni","baseVal","tls","https","ws","wss","socket","cleanup","handleOpen","handleErr","url","closeOnEnd","ready","CLOSING","CLOSED","wasClean","connect","wsUrl","httpProto","wsProto","connectedSource","binaryType","connected","connError","cleanUp","cont","onOpen","onError","onMessage","remoteAddress","remotePort","hostname","CONNECTING","OPEN","websocket","testMa","maConn","socketToMaConn","_connect","upgrader","upgradeOutbound","cOpts","errorPromise","rawSocket","uri","createListener","listenFilter","dialFilter","webSockets","StrictSign","StrictNoSign","TopicValidatorResult","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","defaultDecodeRpcLimits","maxSubscriptions","maxMessages","maxIhaveMessageIDs","maxIwantMessageIDs","maxControlMessages","maxPeerInfos","RPC","SignaturePolicy","PublishConfigType","RejectReason","ValidateError","MessageStatus","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","SubOpts","ControlMessage","ControlIHave","ControlIWant","ControlGraft","ControlPrune","seqno","ihave","iwant","graft","prune","topicID","messageIDs","peerID","subscriptions","control","MessageCache","gossip","msgIdToStrFn","history","notValidatedCount","historyCapacity","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","observeDuplicate","msgId","fromPeerIdStr","getWithIWantCount","getGossipIDs","topics","msgIdsByTopic","msgIds","cacheEntry","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","removeItemsFromSet","superSet","ineed","cond","subset","MapDef","getDefault","getOrDefault","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","knownIPs","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","getRecord","ensureRecord","drec","firstSeenTsMs","expire","gc","PeerScore","peerStats","scoreCache","deliveryRecords","_backgroundInterval","scoreCacheValidityMs","componentLogger","validatePeerScoreParams","background","refreshScores","dumpPeerScoreStats","fromEntries","stats","messageFirstSeenTimestampMs","tparams","graftTime","removeIPsForPeer","scoreFnCalls","inc","cacheUntil","scoreFnRuns","scoreCachedDelta","addPenalty","penaltyLabel","onScorePenalty","addPeer","addIP","removeIP","peersWithIP","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","Blacklisted","ignored","duplicateMessage","cap","validatedTime","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","ipsToRemove","ipToRemove","peerSet","topicStats","computeScoreWeights","topicStrToLabel","byTopic","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","p5w","p6w","p7w","OutboundStream","rawStream","errCallback","pushPrefixed","InboundStream","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsg","requestMsByMsgExpire","requestMsByMsgSize","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","iwantPromiseBroken","isDuplicate","trackMessage","iwantPromiseResolved","iwantPromiseResolvedFromDuplicate","iwantPromiseResolvedPeers","maxMs","iwantMessagePruned","requestMs","iwantPromiseDeliveryTime","SignPrefix","createGossipRpc","ensureControl","messageIdToString","msgIdFnStrictSign","sequenceNumber","seqnoBytes","msgIdFnStrictNoSign","Protocol","GossipStatusCode","SimpleTimeCache","validityMs","validUntilMs","GossipSub","globalSignaturePolicy","multicodecs","publishConfig","dataTransform","streamsInbound","streamsOutbound","outboundInflightQueue","direct","floodsubPeers","seenCache","acceptFromWhitelist","mesh","fanout","fanoutLastpub","peerhave","iasked","outbound","msgIdFn","fastMsgIdFn","fastMsgIdCache","publishedMessageIds","mcache","topicValidators","heartbeatTicks","gossipTracer","directPeerInitial","decodeRpcLimits","stopped","allowedTopics","heartbeatTimer","fallbackToFloodsub","floodPublish","batchPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","heartbeatInterval","fanoutTTL","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","unsubcribeBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","debugName","messageCache","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEventsFanout","meshPeerInclusionEventsRandom","meshPeerInclusionEventsSubscribed","meshPeerInclusionEventsOutbound","meshPeerInclusionEventsNotEnough","meshPeerInclusionEventsOpportunistic","meshPeerInclusionEventsUnknown","meshPeerChurnEventsDisconnected","meshPeerChurnEventsBadScore","meshPeerChurnEventsPrune","meshPeerChurnEventsExcess","meshPeerChurnEventsUnknown","peersPerProtocol","heartbeatDuration","histogram","buckets","heartbeatSkipped","acceptedMessagesTotal","ignoredMessagesTotal","rejectedMessagesTotal","unknownValidationResultsTotal","asyncValidationMcacheHit","asyncValidationDelayFromFirstSeenSec","asyncValidationUnknownFirstSeen","peerReadStreamError","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcDataError","rpcRecvError","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeersByTopic","directPeersPublishedTotal","floodsubPeersPublishedTotal","meshPeersPublishedTotal","fanoutPeersPublishedTotal","msgPublishBytes","msgPublishTime","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedError","prevalidationInvalidTotal","prevalidationValidTotal","prevalidationDuplicateTotal","prevalidationUnknownTotal","msgReceivedInvalid","msgReceivedInvalidByTopic","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","duplicateMsgIgnored","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","iwantPromiseUntracked","connectedPeersBackoffSec","cacheSize","mcacheSize","mcacheNotValidatedCount","fastMsgIdCacheCollision","newConnectionCount","toTopic","topicStr","onJoin","onLeave","onAddToMesh","Fanout","Random","Subscribed","Outbound","NotEnough","Opportunistic","onRemoveFromMesh","Dc","BadScore","Prune","Excess","onReportValidation","messageRecord","firstSeenTimestampMs","hit","Accept","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","floodsub","onMsgRecvPreValidation","onMsgRecvError","onPrevalidationResult","duplicate","onMsgRecvInvalid","onPublishDuplicateMsg","onPeerReadStreamError","onRpcRecvError","onRpcDataError","onRpcRecv","rpcBytes","onRpcSent","registerScores","scores","graylist","publish","registerScoreWeights","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","peersInMesh","meshScores","getMetrics","addCollect","onScrapeMetrics","signaturePolicy","Signing","author","Anonymous","getPublishConfigFromPeerId","createOutboundStream","addrs","topology","onConnect","onPeerConnected","onDisconnect","onPeerDisconnected","notifyOnTransient","registrarTopologyIds","heartbeatTimeout","runHeartbeat","hearbeatStartMs","unregister","closePromises","outboundStream","inboundStream","createInboundStream","maxOutboundBufferSize","sendSubscriptions","priorInboundStream","maxInboundDataLength","pipePeerReadStream","currentIP","multiaddrToIPStr","peersInTopic","getSubscribers","getTopics","control$","prune$","awaitRpcHandler","handleReceivedRpc","handlePeerReadStreamError","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","validationResult","validateReceivedMessage","validationCode","asyncValidation","emitSelf","propagationSource","forwardMessage","fastMsgIdStr","msgIdCached","SignaturePresent","SeqnoPresent","FromPresent","InvalidSeqno","InvalidSignature","InvalidPeerId","fromPeerId","rpcMsgPreSign","validateToRawMessage","inboundTransform","TransformFailed","topicValidator","errCode","getScore","toPeer","sendRpc","controlMsg","handleIHave","handleIWant","handleGraft","handlePrune","sent","iwantMessageIds","messagesAccepted","acceptUntil","LowScore","MaxIhave","MaxIasked","iask","iwantList","GraftBackoff","floodCutoff","addBackoff","makePrune","doAddBackoff","pxConnect","intervalMs","applyIwantPenalties","BrokenPromise","clearBackoff","directConnect","toconnect","pi","consumePeerRecord","getTopologies","wasSubscribed","leave","toAdd","fanoutPeers","fanoutCount","getRandomGossipPeers","sendGraft","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","selectPeersToPublish","newFanoutPeers","rawMsg","startMs","transformedData","outboundTransform","originalData","buildRawMessage","ignoreDuplicatePublishError","recipients","willSendToSelf","allowPublishToZeroPeers","sendRpcInBatch","prefixedData","reportMessageValidationResult","ctrl","piggybackControl","piggybackGossip","outRpc","sendGraftPrune","tograft","toprune","noPX","onUnsubscribe","pruning","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","backoffMs","xid","startTimer","heartbeat","msToNextHeartbeat","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","graftPeer","peersArray","rotate","peersList","medianIndex","medianScore","newMeshPeers","lastpb","topicPeers","candidateFanoutPeers","backoffSize","expiredMs","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","RelayCodecs","contentRoutingSymbol","peerRoutingSymbol","defaultLogger","createDisabledLogger","mapIterable","PeerSet","predicate","intersection","difference","union","createEd25519PeerId","createFromPrivKey","createFromJSON","pubKey","createFromPubKey","createFromParts","PeerMap","PriorityQueue","enqueue","element","priority","comparator","step","it","lowerBound","dequeue","PQueue","carryoverConcurrencyCount","intervalCap","concurrency","autoStart","queueClass","throwOnTimeout","delay","canInitializeInterval","job","newConcurrency","function_","operation","addAll","functions","pause","onSizeLessThan","onIdle","sizeBy","observable","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","identifier","MessageEvent","handler","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","defaultOptions","singleProcess","mutexes","implementation","createReleaseable","ERR_INVALID_PARAMETERS","Peer","Address","Tag","bytesToPeer","peerIdFromPeerId","expiry","Peer$metadataEntry","Peer$tagsEntry","pathSepS","pathSepB","pathSep","Key","_buf","clean","uint8Array","withNamespaces","asKey","less","list1","list2","baseNamespace","namespaceType","namespaceValue","child","isAncestorOf","isDecendantOf","isTopLevel","NAMESPACE_COMMON","peerIdToDatastoreKey","b32key","dedupeFilterAndSortAddresses","addressMap","maStr","existingAddr","toPeerPB","strategy","createSortedMap","validateMetadata","validateTag","mapTag","metadataEntries","tagsEntries","mergedTags","addressFilter","decodePeer","cached","PersistentStore","datastore","lock","isWorker","readLock","writeLock","masterQueue","readQueue","localReadQueue","readPromise","createMutex","existingBuf","peerPb","peerCache","filters","orders","mapQuery","previous","updated","PersistentPeerStore","expectedPeer","peekable","iterable","sorter","BaseDatastore","putMany","getMany","deleteMany","batch","puts","dels","commit","_all","_allKeys","queryKeys","MemoryDatastore","defaultAddressFilter","stripPeerId","observedPeerIdStr","DefaultAddressManager","announce","observed","announceFilter","_updatePeerStoreAddresses","debounce","getAnnounceAddrs","transportManager","getAddrs","confident","getListenAddrs","confirmObservedAddr","startingConfidence","removeObservedAddr","addrSet","DefaultComponents","_started","_invokeStartableMethod","isStartable","startable","beforeStart","afterStart","beforeStop","afterStop","OPTIONAL_SERVICES","NON_SERVICE_PROPERTIES","NETMASK_RANGES","ipRange","isPrivateIp","ipAddr","ipv4Check","connectionGater","gater","denyDialPeer","denyDialMultiaddr","denyInboundConnection","denyOutboundConnection","denyInboundEncryptedConnection","denyOutboundEncryptedConnection","denyInboundUpgradedConnection","denyOutboundUpgradedConnection","filterMultiaddrForPeer","isPrivate","defaultAddressSort","publicResult","isAPrivate","isBPrivate","publicAddressesFirst","relayResult","isACircuit","isBCircuit","circuitRelayAddressesLast","certifiedResult","certifiedAddressesFirst","CustomProgressEvent","getTypes","DEFAULT_TYPES","RecordType","DEFAULT_TTL","toDNSResponse","Status","TC","flag_tc","RD","flag_rd","RA","flag_ra","AD","flag_ad","CD","flag_cd","Question","questions","question","Answer","answers","answer","TTL","dnsJsonOverHttps","httpQueue","queryConcurrency","fqdn","searchParams","URLSearchParams","onProgress","accept","statusText","CachedAnswers","lru","maxSize","hashlru","foundAllAnswers","getAnswers","cachedAnswers","expires","tld","dnsaddrCode","dnsaddrResolver","recursionLimit","maxRecursiveDepth","TXT","DefaultConfig","noAnnounce","addressSorter","faultTolerance","FATAL_ALL","getPeerAddress","ERR_INVALID_MULTIADDR","maPeerIdStr","maPeerId","raceEvent","eventName","removeListeners","eventListener","errorEvent","errorEventListener","JobRecipient","where","Job","controller","created","recipient","Queue","metricName","registerMetricGroup","calculate","running","tryToStartAnother","toGenerator","onQueueJobComplete","onQueueError","onQueueIdle","onSignalAbort","PeerQueue","AUTO_DIAL_PEER_RETRY_THRESHOLD","LAST_DIAL_FAILURE_KEY","AutoDial","minConnections","autoDialPriority","autoDialIntervalMs","autoDialMaxQueueLength","autoDialPeerRetryThresholdMs","autoDialDiscoveredPeersDebounce","autoDialInterval","maxQueueLength","autoDialPeerRetryThreshold","autoDialConcurrency","autoDial","getConnectionsMap","numConnections","sheduleNextAutodial","dialQueue","getDialQueue","peerValues","peersThatHaveNotFailed","peerAValue","peerBValue","lastDialFailure","lastDialFailureTimestamp","DEFAULT_CLOSABLE_PROTOCOLS","maxConnections","allow","ConnectionPruner","maybePruneConnections","sortedConnections","sortConnections","toPrune","toClose","streamProtocols","closableProtocols","safelyCloseConnectionIfUnused","connectionALifespan","connectionBLifespan","anySignal","signals","maxDialQueueLength","maxPeerAddrsToDial","dialTimeout","DialQueue","shutDownController","peerIdOrMultiaddr","existingConnection","force","existingDial","createDialAbortController","addrsToDial","calculateMultiaddrs","dialed","ERR_TOO_MANY_ADDRESSES","ERR_TRANSPORT_DIAL_FAILED","DEFAULT_DIAL_PRIORITY","userSignal","ERR_DIALED_SELF","ERR_PEER_DIAL_INTERCEPTED","ERR_NOT_FOUND","peerRouting","findPeer","ERR_NO_ROUTERS_AVAILABLE","resolvedAddresses","resolveMultiaddrs","peerIdMultiaddr","lastProto","filteredAddrs","dialTransportForMultiaddr","addrPeerId","dedupedAddrs","dedupedMultiaddrs","ERR_NO_VALID_ADDRESSES","gatedAdrs","sortedGatedAddrs","isDialable","DefaultConnectionManager","deny","maxIncomingPendingConnections","incomingPendingConnections","connectionPruner","inboundConnectionRateLimiter","inboundConnectionThreshold","metric","inbound","conns","allStreams","counts","keepAlivePeers","tasks","connectionList","_onConnect","storedConns","isNewPeer","storedConn","ERR_NODE_NOT_STARTED","transient","peerConnections","trackedConnection","closeConnections","acceptIncomingConnection","afterUpgradeInbound","statusMap","errored","complete","CompoundContentRouting","routers","findProviders","seen","router","provide","NOT_STARTED_YET","Fingerprint","fp","fingerprintSize","fnv","hashV","getRandomInt","Bucket","fingerprint","findIndex","FNV_PRIMES","FNV_OFFSETS","cachedEncoder","utf8Buffer","fnvPrime","encodeInto","asUintN","fnv1aEncodeInto","fnv1aUint8Array","fnv1a","numberToBuffer","CuckooFilter","bucketSize","filterSize","rand","swapped","inJ","inK","reliable","MAX_LOAD","optimize","maxItems","errorRate","calculateBucketSize","ScalableCuckooFilter","scale","filterSeries","cuckoo","curSize","DefaultPeerRouting","ERR_FIND_SELF","NOT_FOUND","getClosestPeers","createScalableCuckooFilter","ordered","ops","sourceErr","slotAvailable","resultAvailable","sourceFinished","opErred","valuesAvailable","yieldOrderedValues","ok","yieldUnOrderedValues","task","parallel","useCache","RandomWalk","walking","walkers","shutdownController","walkController","needNext","walk","startWalk","DefaultRegistrar","topologies","_onDisconnect","_onPeerUpdate","_onPeerIdentify","getHandler","ERR_NO_HANDLER_FOR_PROTOCOL","ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED","TrackedMap","registerMetric","updateComponentMetric","deleted","DefaultTransportManager","transports","trackedMap","ERR_INVALID_KEY","ERR_DUPLICATE_TRANSPORT","ERR_TRANSPORT_UNAVAILABLE","getTransports","of","getListeners","listenTransportForMultiaddr","couldNotListen","supportedAddrs","allSettled","NO_FATAL","removeAll","PROTOCOL_ID","MAX_PROTOCOL_LENGTH","NewLine","negotiateFully","originalSink","originalSource","negotiated","negotiating","doneNegotiating","sentProtocol","sendingProtocol","doneSendingProtocol","readProtocol","readingProtocol","doneReadingProtocol","negotiate","doSendProtocol","doReadProtocol","sentData","protocolString","originalCloseRead","originalCloseWrite","originalClose","optimisticSelect","connectionSymbol","ConnectionImpl","multiplexer","_close","_abort","_getStreams","getStreams","countStreams","streamCount","DefaultUpgrader","connectionEncryption","muxers","inboundUpgradeTimeout","encrypter","muxer","shouldBlockConnection","connectionType","ERR_CONNECTION_INTERCEPTED","upgradeInbound","ERR_CONNECTION_DENIED","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","trackMultiaddrConnection","protectedConn","skipProtection","protector","connectionProtector","protect","skipEncryption","_encryptInbound","idStr","remotePeerId","multiplexed","_multiplexInbound","_createConnection","_encryptOutbound","ERR_INVALID_PEER","_multiplexOutbound","muxedStream","incomingLimit","findIncomingStreamLimit","ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS","trackProtocolStream","_onStream","ERR_MUXER_UNAVAILABLE","outgoingLimit","findOutgoingStreamLimit","ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS","ERR_UNSUPPORTED_PROTOCOL","_timeline","Proxy","Reflect","upgraded","ERR_CONNECTION_NOT_MULTIPLEXED","ERR_ENCRYPTION_FAILED","Libp2pNode","contentRouting","originalDispatch","internalResult","externalResult","receiver","defaultComponents","configureComponent","streamMuxers","peerRouters","contentRouters","peerDiscovery","createService","component","dialProtocol","ERR_INVALID_PROTOCOLS_FOR_STREAM","getMultiaddrs","peerKey","ERR_DISCOVERED_SELF","createLibp2pNode","resultingOptions","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","validateConfig","BaseProtocolSDK","numPeersToUse","DEFAULT_SUBSCRIBE_OPTIONS","keepAlive","SubscriptionManager","receivedMessagesHashStr","keepAliveTimer","subscriptionCallbacks","remotePeers","decodersArray","failures","TOPIC_DECODER_MISMATCH","successes","decodersGroupedByCT","finalResult","handleResult","subscriptionCallback","startKeepAlivePings","stopKeepAlivePings","processIncomingMessage","hashedMessageStr","pubsubTopicBytes","contentTopicBytes","timestampBytes","numberToBytes","tryConvertTimestampToBytes","messageHash","messageHashStr","decodePromises","dec","decodedMessage","pushMessage","promiseResult","coreResult","FilterSDK","activeSubscriptions","subscription","getActiveSubscription","setActiveSubscription","createSubscription","uniquePubsubTopics","getUniquePubsubTopics","toSubscriptionIterator","iteratorOptions","iteratorDelay","isWithTimeout","toAsyncIterator","LightPushSDK","TOPIC_NOT_CONFIGURED","sendPromises","StoreSDK","queryGenerator","decodersAsMap","validateDecodersAndPubsubTopic","constructOptions","responseGenerator","queryWithOrderedCallback","processMessages","queryWithPromiseCallback","page","_promises","msgPromise","createCursor","messageTime","uniquePubsubTopicsInQuery","pubsubTopicForQuery","timeFilter","processedMessages","shouldReverseOrder","logWhichShardInfoIsUsed","libp2pOptions","defaultBootstrap","wakuDnsDiscovery","enrTree","LocalPeerCacheDiscovery","wakuPeerExchangeDiscovery","wakuGossipSub","hideWebSocketInfo","pubsubService","pubsub","createLibp2p","DefaultUserAgent","pingMaxInboundStreams","DefaultPingMaxInboundStreams","defaultLibp2p","createLibp2pAndUpdateOptions","wakuStore","wakuLightPush","WakuNode","_protocols","mapToPeerIdOrMultiaddr","codecs","subscribeToContentTopic","prepareSubscription","getLocalMultiaddrWithID","localMultiaddr","SANDBOX","TEST","DEPRECATED_DEFAULT_PUBSUB","DEFAULT_NODE_REQUIREMENTS","groupLen","USE_ENDOMORPHISM","ShaError","assertJacPoint","JacobianPoint","toAffineBatch","scratch","Z1Z1","Z2Z2","S1","S2","x1b","HH","HHH","P0","normalizeScalar","affinePoint","invZ","iz1","iz2","iz3","fromCompressedHex","isShort","bytesToNumber","isValidFieldElement","rt","isYOdd","fromUncompressedHex","normalizePrivateKey","fromSignature","normalizeSignature","truncateHash","rinv","numTo32bStr","toHexX","toRawX","aP","bQ","sliceDER","parseDERInt","parseDERSignature","HALF","sHex","rHex","sHexL","rHexL","sLen","rLen","uint8a","POW_2_256","hexByte","truncateOnly","bits2int_2","_sha256Sync","_hmacSha256Sync","HmacDrbg","hmacSha256","hmacSync","checkSync","incr","reseedSync","kmdToSig","kinv","bits2octets","z1","vopts","web","concatBytes","_bigintTo32Bytes","_normalizePrivateKey","hashToPrivateKey","createHash","ckey","createHmac","sha256Sync","hmacSha256Sync","taggedHash","tagP","tagH","taggedHashSync","_JacobianPoint","keccak256","sha3","verifySignature","normalizePublicKey","sinv","ERR_INVALID_ID","locationMultiaddrFromEnrFields","isIpv6","ipVal","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","encodeMultiaddrs","encodeWaku2","RawEnr","kvs","rsv","getStringValue","setStringValue","getNumberAsStringValue","setNumberAsStringValue","tcp6","udp6","multiaddrBytes","decodeMultiaddrs","deleteUndefined","waku2","decodeWaku2","initSigArgs","canonical","recSig","recovered","finalizeSig","TransportProtocol","TransportProtocolPerIpVersion","createPeerIdFromPublicKey","nodeId","uncompressedPubkey","getLocationMultiaddr","setLocationMultiaddr","getAllLocationMultiaddrs","_multiaddrs","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","_permanentCensorErrors","_censorErrors","LogLevels","warning","_logLevel","_globalLogger","_normalizeError","form","_checkNormalize","LogLevel","ErrorCode","HEX","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","globalLogger","setCensorship","censorship","permanent","setLogLevel","isHexable","addSlice","arrayify","allowMissingPrefix","toHexString","isHexString","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","_decode","consumed","BUFFER_OVERRUN","EnrDecoder","encoded","RECORD_PREFIX","fromRLP","checkValues","_seq","decodeSeq","rlpEncodedBytes","checkSignature","fromValues","v4Regex","v6Regex","isFormat","buff","hexN","decN","prevColon","useDec","sizeOf","toType","rcode","opcode","klass","toClass","toCode","SURROGATE_A","SURROGATE_B","nextCode","numA","isU8Arr","bytelength","P_24","P_16","P_8","readUInt32BE","readUInt16BE","writeUInt32BE","writeUInt16BE","targetStart","sourceStart","sourceEnd","nb","sourceLen","_copyActual","consumedBytes","jumped","jumpOffset","flags","authorities","additionals","flag_qr","flag_aa","flag_z","runknown","dLen","rns","dd","rsoa","mname","rname","serial","refresh","retry","minimum","rtxt","rnull","rhinfo","cpu","os","rptr","rsrv","weight","rcaa","issuerCritical","ISSUER_CRITICAL","rmx","preference","ra","raaaa","roption","spl","sourcePrefixLength","fam","ipBuf","ipLen","scopePrefixLength","tagsLen","padded","ropt","rdlen","encodingLengthList","encodeList","rdnskey","keydata","PROTOCOL_DNSSEC","ZONE_KEY","SECURE_ENTRYPOINT","rrrsig","typeCovered","labels","originalTTL","expiration","inception","keyTag","signersName","rrp","mbox","txt","typebitmap","typelist","typesByWindow","typeid","windowBuf","windowLength","extents","rnsec","nextDomain","rrtypes","rnsec3","hashLength","rds","digestdata","digestType","renc","udpPayloadSize","extendedRcode","ednsVersion","class","flag_do","RECURSION_DESIRED","packet","allocing","decodeList","sanitizeSingle","sanitized","make","charset","paddingMode","byCharCode","byNum","padCode","safeLen","safeEnd","base64URL","require","HTTPStatusError","endpoint","ResponseError","cause","reduceError","baseParts","httpFlags","updFlags","parseFlags","InvalidProtocolError","BaseEndpoint","isHTTP","UDPEndpoint","ipv6","UDP4Endpoint","UDP6Endpoint","safeHost","HTTPEndpoint","v6Parts","toEndpoint","post","parseEndpoint","contentType","requestRaw","abortSignal","setRequestHeader","ontimeout","onload","onabort","cors","endpoints","resolverByName","byName","endpointByName","backup","description","country","lat","UPDATE_URL","isNameString","wellknown","updateURL","persist","localStoragePrefix","maxAge","_dataP","_data","outdated","cacheKey","maxTime","filterDoh","filterDns","queryN","singleQuery","toMultiQuery","queryDoh","queryOne","DnsOverHttps","_endpoints","resolveTXT","sd","ENRTree","parseAndVerifyRoot","ROOT_PREFIX","rootValues","parseRootValues","decodedPublicKey","signedComponent","signedComponentBuffer","eRoot","lRoot","parseTree","tree","TREE_PREFIX","parseBranch","branch","BRANCH_PREFIX","isSatisfied","wanted","addCapabilities","helpsSatisfyCapabilities","missingCapabilities","DnsNodeDiscovery","_DNSTreeCache","_errorTolerance","dnsOverHttp","dnsClient","enrTreeUrls","wantedNodeCapabilityCount","networkIndex","visits","errorTolerance","getNode","maxSearches","totalSearches","fetchNodesUntilCapabilitiesFulfilled","_search","getNextPeer","peerNodeIds","yieldNodesUntilCapabilitiesFulfilled","subdomain","_getTXTRecord","branches","entryType","getEntryType","circularRefs","selectRandomPath","PeerDiscoveryDns","nextPeer","_components","_options","enrUrls","peerEnr","tagsToUpdate","isPeerChanged","PeerExchangeCodec","WakuPeerExchange","rpcQuery","ENR","DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS","DEFAULT_MAX_RETRIES","DEFAULT_PEER_EXCHANGE_TAG_NAME","PeerExchangeDiscovery","peerExchange","queryingPeers","queryAttempts","handleDiscoveredPeer","startRecurringQueries","queryInterval","maxRetries","currentAttempt","abortQueriesForPeer","_peerInfo","DEFAULT_LOCAL_TAG_NAME","getPeersFromLocalStorage","handleNewPeers","savePeersToLocalStorage","websocketMultiaddr","wsMultiaddr","getWsMultiaddrFromMultiaddrs","localStoragePeers","existingPeerIndex","_peer","storedPeersData","isValidStoredPeer","TelemetryType","__awaiter","thisArg","_arguments","generator","fulfilled","rejected","__generator","trys","verb","TelemetryClient","intervalPeriod","intervalId","_this","telemetryRequests","e_1","telemetryType","messageType","telemetryData","hashNumber","DEFAULT_CONTENT_TOPIC","ProtoSequencedMessage","sequenceCompletedEvent","messageSentEvent","app","telemetryClient","startLightPushSequence","startFilterSubscription","numMessages_1","args_1","_i","pack","ar","__spreadArray","numMessages","period","sequenceHash","sequenceTotal","sequenceIndex","messageElement","messagesSent","error_1","sender","LIGHT_PUSH_FILTER","peerIdSender","peerIdReporter","getElementById","textContent","insertBefore","firstChild","messagesReceived","sequencedMessage","appendChild","startSequence","messagePeriod","sentMessagesCount","sentMessagesCounter","display"],"sourceRoot":""} \ No newline at end of file diff --git a/flush-notes/404.html b/flush-notes/404.html index 3c29e1d..bea51ab 100644 --- a/flush-notes/404.html +++ b/flush-notes/404.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/_next/static/VJD631qiVEcQNWfhl6_Ve/_buildManifest.js b/flush-notes/_next/static/QOeKfE5AVixhzCg9mihTc/_buildManifest.js similarity index 100% rename from flush-notes/_next/static/VJD631qiVEcQNWfhl6_Ve/_buildManifest.js rename to flush-notes/_next/static/QOeKfE5AVixhzCg9mihTc/_buildManifest.js diff --git a/flush-notes/_next/static/VJD631qiVEcQNWfhl6_Ve/_ssgManifest.js b/flush-notes/_next/static/QOeKfE5AVixhzCg9mihTc/_ssgManifest.js similarity index 100% rename from flush-notes/_next/static/VJD631qiVEcQNWfhl6_Ve/_ssgManifest.js rename to flush-notes/_next/static/QOeKfE5AVixhzCg9mihTc/_ssgManifest.js diff --git a/flush-notes/index.html b/flush-notes/index.html index 85d1265..553aded 100644 --- a/flush-notes/index.html +++ b/flush-notes/index.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/index.txt b/flush-notes/index.txt index 08fe8e7..55df5bf 100644 --- a/flush-notes/index.txt +++ b/flush-notes/index.txt @@ -1,6 +1,6 @@ 1:HL["/_next/static/media/c9a5bc6a7c948fb0-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/6156c3ee634ecb95.css","style",{"crossOrigin":""}] -0:["VJD631qiVEcQNWfhl6_Ve",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/6156c3ee634ecb95.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +0:["QOeKfE5AVixhzCg9mihTc",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/6156c3ee634ecb95.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] 5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6865c0057cbfa0c2.js"],""] 6:I[6954,[],""] 7:I[7264,[],""] diff --git a/flush-notes/view.html b/flush-notes/view.html index 4ff8581..8477b71 100644 --- a/flush-notes/view.html +++ b/flush-notes/view.html @@ -1 +1 @@ -Share notes

Loading...

\ No newline at end of file +Share notes

Loading...

\ No newline at end of file diff --git a/flush-notes/view.txt b/flush-notes/view.txt index 34f4444..81ccff4 100644 --- a/flush-notes/view.txt +++ b/flush-notes/view.txt @@ -1,6 +1,6 @@ 1:HL["/_next/static/media/c9a5bc6a7c948fb0-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/6156c3ee634ecb95.css","style",{"crossOrigin":""}] -0:["VJD631qiVEcQNWfhl6_Ve",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/6156c3ee634ecb95.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +0:["QOeKfE5AVixhzCg9mihTc",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/6156c3ee634ecb95.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] 5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6865c0057cbfa0c2.js"],""] 6:I[6954,[],""] 7:I[7264,[],""]