@timestope-official/bitcoinkrypton-browser 0.0.1-0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -0
- package/VERSION +5 -0
- package/krypton.js +2 -0
- package/krypton.js.map +1 -0
- package/namespace.d.ts +8 -0
- package/package.json +41 -0
- package/types.d.ts +4353 -0
- package/web-babel.js +2 -0
- package/web-babel.js.map +1 -0
- package/web-offline.js +2 -0
- package/web-offline.js.map +1 -0
- package/web.esm.js +2 -0
- package/web.esm.js.map +1 -0
- package/web.js +2 -0
- package/web.js.map +1 -0
- package/worker-js.js +1 -0
- package/worker-wasm.js +1 -0
- package/worker-wasm.wasm +0 -0
- package/worker.js +2 -0
- package/worker.js.map +1 -0
package/web-offline.js
ADDED
@@ -0,0 +1,2 @@
|
|
1
|
+
if("undefined"==typeof Krypton)var Krypton="undefined"!=typeof window?window:{};var Proxy;!function(e){(Krypton=e="undefined"!=typeof e?e:{})._currentScript||(Krypton._currentScript=document.currentScript);if(!Krypton._currentScript){const e=document.getElementsByTagName("script");Krypton._currentScript=e[e.length-1]}Krypton._path||(Krypton._currentScript&&-1!==Krypton._currentScript.src.indexOf("/")?Krypton._path=Krypton._currentScript.src.substring(0,Krypton._currentScript.src.lastIndexOf("/")+1):Krypton._path="./");class Class{static get scope(){return"undefined"!=typeof e?e:"undefined"!=typeof self?self:window}static register(t){"undefined"!=typeof e&&(e[t.name]=t)}}Class.register(Class);class LogNative{constructor(){this._global_level=Log.INFO;this._tag_levels={};try{if(window.localStorage)try{let t=window.localStorage.getItem("log_tag_levels");t&&"string"==typeof t&&(t=JSON.parse(t));t&&"object"==typeof t&&(this._tag_levels=t)}catch(e){console.warn("Failed to load log configuration from local storage.")}}catch(e){}}isLoggable(e,t){return e&&this._tag_levels[e]?this._tag_levels[e]<=t:this._tag_levels["*"]?this._tag_levels["*"]<=t:this._global_level<=t}setLoggable(e,t){e&&e.name&&(e=e.name);this._tag_levels[e]=t;window.localStorage&&window.localStorage.setItem("log_tag_levels",JSON.stringify(this._tag_levels))}msg(e,t,r){t&&t.name&&(t=t.name);if(this.isLoggable(t,e)){t&&r.unshift(t+":");r.unshift(`[${Log.Level.toStringTag(e)} ${(new Date).toTimeString().substr(0,8)}]`);console.error&&e>=Log.ERROR?console.error.apply(console,r):console.warn&&e>=Log.WARNING?console.warn.apply(console,r):console.info&&e>=Log.INFO?console.info.apply(console,r):console.debug&&e>=Log.DEBUG?console.debug.apply(console,r):console.trace&&e<=Log.TRACE?console.trace.apply(console,r):console.log.apply(console,r)}}}Class.register(LogNative);class Log{static get instance(){Log._instance||(Log._instance=new Log(new LogNative));return Log._instance}constructor(e){this._native=e}setLoggable(e,t){this._native.setLoggable(e,Log.Level.get(t))}get level(){return this._native._global_level}set level(e){this._native._global_level=Log.Level.get(e)}msg(e,t,r){if(this._native.isLoggable(t,e)){for(let e=0;e<r.length;++e){"function"==typeof r[e]&&(r[e]=r[e]());"object"==typeof r[e]&&("function"==typeof r[e].toString?r[e]=r[e].toString():r[e].constructor&&r[e].constructor.name?r[e]=`{Object: ${r[e].constructor.name}}`:r[e]="{Object}")}this._native.msg(e,t,r)}}static d(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.DEBUG,e,r)}static e(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.ERROR,e,r)}static i(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.INFO,e,r)}static v(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.VERBOSE,e,r)}static w(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.WARNING,e,r)}static t(e,t,...r){if(arguments.length>=2){e=arguments[0];r=Array.prototype.slice.call(arguments,1)}else{e=undefined;r=Array.prototype.slice.call(arguments,0)}Log.instance.msg(Log.TRACE,e,r)}}Log.Level={TRACE:1,VERBOSE:2,DEBUG:3,INFO:4,WARNING:5,ERROR:6,ASSERT:7,toStringTag:function(e){switch(e){case Log.Level.TRACE:return"T";case Log.Level.VERBOSE:return"V";case Log.Level.DEBUG:return"D";case Log.Level.INFO:return"I";case Log.Level.WARNING:return"W";case Log.Level.ERROR:return"E";case Log.Level.ASSERT:return"A";default:return"*"}},toString:function(e){switch(e){case Log.Level.TRACE:return"trace";case Log.Level.VERBOSE:return"verbose";case Log.Level.DEBUG:return"debug";case Log.Level.INFO:return"info";case Log.Level.WARNING:return"warn";case Log.Level.ERROR:return"error";case Log.Level.ASSERT:return"assert";default:return"unknown"}},get:function(e){if("number"==typeof e)return e;if(!isNaN(parseInt(e)))return parseInt(e);switch(e.toLowerCase()){case"t":case"trace":return Log.Level.TRACE;case"v":case"verbose":return Log.Level.VERBOSE;case"d":case"debug":return Log.Level.DEBUG;case"i":case"info":return Log.Level.INFO;case"w":case"warn":case"warning":return Log.Level.WARNING;case"e":case"error":case"exception":return Log.Level.ERROR;case"a":case"assert":case"assertion":return Log.Level.ASSERT}return 0}};Log.TRACE=Log.Level.TRACE;Log.VERBOSE=Log.Level.VERBOSE;Log.DEBUG=Log.Level.DEBUG;Log.INFO=Log.Level.INFO;Log.WARNING=Log.Level.WARNING;Log.ERROR=Log.Level.ERROR;Log.ASSERT=Log.Level.ASSERT;Log._instance=null;Log.d.tag=(e=>Log.d.bind(null,e));Log.e.tag=(e=>Log.e.bind(null,e));Log.i.tag=(e=>Log.i.bind(null,e));Log.v.tag=(e=>Log.v.bind(null,e));Log.w.tag=(e=>Log.w.bind(null,e));Log.t.tag=(e=>Log.t.bind(null,e));Class.register(Log);class Observable{static get WILDCARD(){return"*"}constructor(){this._listeners=new Map}_offAll(){this._listeners.clear()}on(e,t){if(this._listeners.has(e))return this._listeners.get(e).push(t)-1;this._listeners.set(e,[t]);return 0}off(e,t){this._listeners.has(e)&&this._listeners.get(e)[t]&&delete this._listeners.get(e)[t]}fire(e,...t){const r=[];if(this._listeners.has(e)){const n=this._listeners.get(e);for(const s in n)if(n.hasOwnProperty(s))try{const o=n[s].apply(null,t);o instanceof Promise&&r.push(o["catch"](t=>Log.e(this.constructor.name,`Exception thrown by '${e}' listener #${s}: ${t.message||t}`,t)))}catch(i){Log.e(this.constructor.name,`Exception thrown by '${e}' listener #${s}: ${i.message||i}`,i)}}if(this._listeners.has(Observable.WILDCARD)){const t=this._listeners.get(Observable.WILDCARD);for(const n in t)if(t.hasOwnProperty(n))try{const s=t[n].apply(null,arguments);s instanceof Promise&&r.push(s["catch"](t=>Log.e(this.constructor.name,`Exception thrown by '${e}' wildcard listener #${n}: ${t.message||t}`,t)))}catch(i){Log.e(this.constructor.name,`Exception thrown by '${e}' wildcard listener #${n}: ${i.message||i}`,i)}}return r.length>0?Promise.all(r):null}bubble(e,...t){for(const r of t){let t;t=r===Observable.WILDCARD?function(){this.fire.apply(this,arguments)}:function(){this.fire.apply(this,[r,...arguments])};e.on(r,t.bind(this))}}}Class.register(Observable);class CryptoLib{static get instance(){if(!CryptoLib._instance){const e={};e.getRandomValues=(window.crypto||window.msCrypto).getRandomValues.bind(window.crypto);CryptoLib._instance=e}return CryptoLib._instance}}CryptoLib._instance=null;Class.register(CryptoLib);class PlatformUtils{static isBrowser(){return!0}static isWeb(){return"undefined"!=typeof window}static isNodeJs(){return!1}static supportsWebRTC(){const e=PlatformUtils.isBrowser()?window.RTCPeerConnection||window.webkitRTCPeerConnection:null;return!!e&&"function"==typeof e.prototype.createDataChannel}static supportsWS(){return location&&"http:"===location.protocol}static isOnline(){return!("onLine"in window.navigator)||window.navigator.onLine}static isWindows(){return/^win/.test(window.navigator.platform)}static get userAgentString(){try{return window.navigator.platform}catch(e){return"unknown"}}static get hardwareConcurrency(){return"object"==typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:1}}Class.register(PlatformUtils);class WasmHelper{static async doImport(){return WasmHelper.doImportBrowser()}static async doImportBrowser(){WasmHelper._importBrowserPromise=WasmHelper._importBrowserPromise||(async()=>{await WasmHelper.importWasmBrowser("worker-wasm.wasm")?await WasmHelper.importScriptBrowser("worker-wasm.js","Module","sha256-Pbm9dyLcorY4zzI5YHfcFL2c8cVh2AJOIsxqa3ceOp4="):await WasmHelper.importScriptBrowser("worker-js.js","Module","sha256-Ym7/F/nwZ7ZVkZcFF1RSK0M0DhYBfB+lQHiEJ1N9lgI=")})();try{await WasmHelper._importBrowserPromise}catch(e){WasmHelper._importBrowserPromise=null;throw e}}static async importWasm(e,t="Module"){return WasmHelper.importWasmBrowser(e,t)}static async importWasmBrowser(e,t="Module"){e=WasmHelper._adjustWasmPath(e);if(!WasmHelper._global.WebAssembly){Log.w(WasmHelper,"No support for WebAssembly available.");return Promise.resolve(!1)}return new Promise(r=>{try{const n=new XMLHttpRequest;n.open("GET",e,!0);n.responseType="arraybuffer";n.onload=function(){WasmHelper._global[t]=WasmHelper._global[t]||{};WasmHelper._global[t].wasmBinary=n.response;r(!0)};n.onerror=function(){Log.w(WasmHelper,`Failed to access WebAssembly module ${e}`);r(!1)};n.send(null)}catch(i){Log.w(WasmHelper,`Failed to access WebAssembly module ${e}`);r(!1)}})}static async importScript(e,t="Module"){return WasmHelper.importScriptBrowser(e,t)}static async importScriptBrowser(e,t="Module",r=null){if(t&&WasmHelper._global[t]&&WasmHelper._global[t].asm)return!1;e=WasmHelper._adjustScriptPath(e);const i=WasmHelper._global[t]||{};return new Promise(async(n,s)=>{const o=new Promise(e=>{i.onRuntimeInitialized=(()=>e(!0))});if("function"==typeof importScripts){await new Promise(r=>{WasmHelper._moduleLoadedCallbacks[t]=r;importScripts(e)});WasmHelper._global[t]=WasmHelper._global[t](i)}else if("object"==typeof window){await new Promise(i=>{WasmHelper._moduleLoadedCallbacks[t]=i;WasmHelper._loadBrowserScript(e,r)});WasmHelper._global[t]=WasmHelper._global[t](i)}else{if("function"!=typeof require){s("No way to load scripts.");return}WasmHelper._global[t]=require(e)(i)}await o;i.asm&&!WasmHelper._global[t].asm&&(WasmHelper._global[t]=i);n(!0)})}static fireModuleLoaded(e="Module"){if("function"==typeof WasmHelper._moduleLoadedCallbacks[e]){WasmHelper._moduleLoadedCallbacks[e]();WasmHelper._moduleLoadedCallbacks[e]=null}}static _loadBrowserScript(e,t){const r=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript";i.src=e;if(null!=t){i.integrity=t;i.crossOrigin="anonymous"}r.appendChild(i)}static _adjustWasmPath(e){"undefined"!=typeof Krypton&&Krypton._path&&(e=`${Krypton._path}${e}`);"string"==typeof __dirname&&-1===e.indexOf("/")&&(e=`${__dirname}/${e}`);return e}static _adjustScriptPath(e){"undefined"!=typeof Krypton&&Krypton._path&&(e=`${Krypton._path}${e}`);"string"==typeof __dirname&&-1===e.indexOf("/")&&(e=`${__dirname}/${e}`);return e}static get _global(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:null}}WasmHelper._moduleLoadedCallbacks={};Class.register(WasmHelper);class ArrayUtils{static randomElement(e){return e[Math.floor(Math.random()*e.length)]}static subarray(e,t,r){function clamp(e,t,r){return e<t?t:e>r?r:e}t===undefined&&(t=0);r===undefined&&(r=e.byteLength);t=clamp(t,0,e.byteLength);let i=(r=clamp(r,0,e.byteLength))-t;i<0&&(i=0);return new Uint8Array(e.buffer,e.byteOffset+t,i)}static*k_combinations(e,t){const r=e.length;if(t>r)return;const i=Array.from(new Array(t),(e,t)=>t);yield i.map(t=>e[t]);const n=Array.from(new Array(t),(e,r)=>t-r-1);for(;;){let s=t-1,o=!1;for(s of n)if(i[s]!==s+r-t){o=!0;break}if(!o)return;i[s]+=1;for(const e of Array.from(new Array(t-s-1),(e,t)=>s+t+1))i[e]=i[e-1]+1;yield i.map(t=>e[t])}}}Class.register(ArrayUtils);class Assert{static that(e,t="Assertion failed"){if(!e)throw new Error(t)}}Class.register(Assert);class BufferUtils{static toAscii(e){const t=BufferUtils._toUint8View(e);let r="";for(let i=0;i<t.length;i+=8192)r+=String.fromCharCode.apply(null,t.subarray(i,i+8192));return r}static fromAscii(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}static _codePointTextDecoder(e){if("undefined"==typeof TextDecoder)throw new Error("TextDecoder not supported");if(null===BufferUtils._ISO_8859_15_DECODER)throw new Error("TextDecoder does not support iso-8859-15");if(BufferUtils._ISO_8859_15_DECODER===undefined)try{BufferUtils._ISO_8859_15_DECODER=new TextDecoder("iso-8859-15")}catch(r){BufferUtils._ISO_8859_15_DECODER=null;throw new Error("TextDecoder does not support iso-8859-15")}const t=BufferUtils._toUint8View(e);return BufferUtils._ISO_8859_15_DECODER.decode(t).replace(/\u20ac/g,"¤").replace(/\u0160/g,"¦").replace(/\u0161/g,"¨").replace(/\u017d/g,"´").replace(/\u017e/g,"¸").replace(/\u0152/g,"¼").replace(/\u0153/g,"½").replace(/\u0178/g,"¾")}static _tripletToBase64(e){return BufferUtils._BASE64_LOOKUP[e>>18&63]+BufferUtils._BASE64_LOOKUP[e>>12&63]+BufferUtils._BASE64_LOOKUP[e>>6&63]+BufferUtils._BASE64_LOOKUP[63&e]}static _base64encodeChunk(e,t,r){let i;const n=[];for(let s=t;s<r;s+=3){i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]);n.push(BufferUtils._tripletToBase64(i))}return n.join("")}static _base64fromByteArray(e){let t;const r=e.length,i=r%3;let n="";const s=[];for(let o=0,a=r-i;o<a;o+=16383)s.push(BufferUtils._base64encodeChunk(e,o,o+16383>a?a:o+16383));if(1===i){t=e[r-1];n+=BufferUtils._BASE64_LOOKUP[t>>2];n+=BufferUtils._BASE64_LOOKUP[t<<4&63];n+="=="}else if(2===i){t=(e[r-2]<<8)+e[r-1];n+=BufferUtils._BASE64_LOOKUP[t>>10];n+=BufferUtils._BASE64_LOOKUP[t>>4&63];n+=BufferUtils._BASE64_LOOKUP[t<<2&63];n+="="}s.push(n);return s.join("")}static toBase64(e){if(PlatformUtils.isNodeJs())return Buffer.from(e).toString("base64");if("undefined"!=typeof TextDecoder&&null!==BufferUtils._ISO_8859_15_DECODER)try{return btoa(BufferUtils._codePointTextDecoder(e))}catch(t){}return BufferUtils._base64fromByteArray(BufferUtils._toUint8View(e))}static fromBase64(e,t){const r=new Uint8Array(atob(e).split("").map(e=>e.charCodeAt(0)));if(t!==undefined&&r.length!==t)throw new Error("Decoded length does not match expected length");return new SerialBuffer(r)}static toBase64Url(e){return BufferUtils.toBase64(e).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,".")}static fromBase64Url(e,t){return BufferUtils.fromBase64(e.replace(/_/g,"/").replace(/-/g,"+").replace(/\./g,"="),t)}static toBase32(e,t=BufferUtils.BASE32_ALPHABET.KRYPTON){let r,i,n,s=3,o=0,a="";for(n=0;n<e.length;n++){a+=t[31&(i=o|(r=e[n])>>s)];s>5&&(a+=t[31&(i=r>>(s-=5))]);o=r<<(s=5-s);s=8-s}3!==s&&(a+=t[31&o]);for(;a.length%8!=0&&33===t.length;)a+=t[32];return a}static fromBase32(e,t=BufferUtils.BASE32_ALPHABET.KRYPTON){const r=[];t.toUpperCase().split("").forEach((e,t)=>{e in r||(r[e]=t)});let i,n=8,s=0,o=[];e.toUpperCase().split("").forEach(e=>{if(33!==t.length||e!==t[32]){i=255&r[e];if((n-=5)>0)s|=i<<n;else if(n<0){o.push(s|i>>-n);s=i<<(n+=8)&255}else{o.push(s|i);n=8;s=0}}});8!==n&&0!==s&&o.push(s);return new Uint8Array(o)}static toHex(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=BufferUtils.HEX_ALPHABET[i>>>4];t+=BufferUtils.HEX_ALPHABET[15&i]}return t}static fromHex(e,t){e=e.trim();if(!StringUtils.isHexBytes(e,t))throw new Error("String is not an hex string (of matching length)");return new SerialBuffer(new Uint8Array((e.match(/.{2}/g)||[]).map(e=>parseInt(e,16))))}static toBinary(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=StringUtils.lpad(i.toString(2),"0",8)}return t}static _strToUint8Array(e){const t=[];let r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n<128)t[r++]=n;else if(n<2048){t[r++]=n>>6|192;t[r++]=63&n|128}else if(55296==(64512&n)&&i+1<e.length&&56320==(64512&e.charCodeAt(i+1))){n=65536+((1023&n)<<10)+(1023&e.charCodeAt(++i));t[r++]=n>>18|240;t[r++]=n>>12&63|128;t[r++]=n>>6&63|128;t[r++]=63&n|128}else{t[r++]=n>>12|224;t[r++]=n>>6&63|128;t[r++]=63&n|128}}return new Uint8Array(t)}static _utf8TextEncoder(e){if("undefined"==typeof TextEncoder)throw new Error("TextEncoder not supported");if(null===BufferUtils._UTF8_ENCODER)throw new Error("TextEncoder does not support utf8");if(BufferUtils._UTF8_ENCODER===undefined)try{BufferUtils._UTF8_ENCODER=new TextEncoder}catch(t){BufferUtils._UTF8_ENCODER=null;throw new Error("TextEncoder does not support utf8")}return BufferUtils._UTF8_ENCODER.encode(e)}static fromUtf8(e){if(PlatformUtils.isNodeJs())return Buffer.from(e);if("undefined"!=typeof TextEncoder&&null!==BufferUtils._UTF8_ENCODER)try{return BufferUtils._utf8TextEncoder(e)}catch(t){}return BufferUtils._strToUint8Array(e)}static fromAny(e,t){if(""===e)return SerialBuffer.EMPTY;if(!e)throw new Error("Invalid buffer format");if(e instanceof Uint8Array)return new SerialBuffer(e);try{return BufferUtils.fromHex(e,t)}catch(r){}try{return BufferUtils.fromBase64(e,t)}catch(r){}throw new Error("Invalid buffer format")}static concatTypedArrays(e,t){const r=new e.constructor(e.length+t.length);r.set(e,0);r.set(t,e.length);return r}static equals(e,t){const r=BufferUtils._toUint8View(e),i=BufferUtils._toUint8View(t);if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!==i[n])return!1;return!0}static compare(e,t){if(e.length<t.length)return-1;if(e.length>t.length)return 1;for(let r=0;r<e.length;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}static xor(e,t){const r=new Uint8Array(e.byteLength);for(let i=0;i<e.byteLength;++i)r[i]=e[i]^t[i];return r}static _toUint8View(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e.buffer instanceof ArrayBuffer)return new Uint8Array(e.buffer);throw new Error("TypedArray or ArrayBuffer required")}static toBase58(e,t=BufferUtils.BASE58_ALPHABET){let r,i=[],n="",s=0;for(;s<e.length&&!e[s];s++)n+=t[0];for(;s<e.length;s++){let t=e[s];r=0;for(;r in i||t;){let e=i[r]?(i[r]<<8)+t:t;t=e/58|0;i[r]=e%58;r++}}for(;r--;)n+=t[i[r]];return n}static fromBase58(e,t=BufferUtils.BASE58_ALPHABET){let r,i=[],n=[],s=0;for(;s<e.length&&!t.indexOf(e[s]);s++)i.push(0);for(;s<e.length;s++){let i=t.indexOf(e[s]);if(i<0)return"";r=0;for(;r in n||i;){let e=n[r]?58*n[r]+i:i;i=e>>8;n[r]=e%256;r++}}for(;r--;)i.push(n[r]);return new Uint8Array(i)}static toBase58Check(e,t=128,r,i=BufferUtils.BASE58_ALPHABET){let n;n=new SerialBuffer(r?[255&t,...e,255&r]:[255&t,...e]);const s=Hash.computeSha256(Hash.computeSha256(n)).subarray(0,4),o=new SerialBuffer([...n,...s]);return BufferUtils.toBase58(o,i)}static fromBase58Check(e,t=!1,r=BufferUtils.BASE58_ALPHABET){const i=BufferUtils.fromBase58(e,r),n=t?-5:-4;return new Uint8Array(i.slice(1,n))}}BufferUtils.BASE64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";BufferUtils.BASE32_ALPHABET={RFC4648:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",RFC4648_HEX:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",KRYPTON:"0123456789ABCDEFGHJKLMNPQRSTUVXY"};BufferUtils.HEX_ALPHABET="0123456789abcdef";BufferUtils._BASE64_LOOKUP=[];for(let r=0,i=BufferUtils.BASE64_ALPHABET.length;r<i;++r)BufferUtils._BASE64_LOOKUP[r]=BufferUtils.BASE64_ALPHABET[r];BufferUtils.BASE58_ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";Class.register(BufferUtils);class SerialBuffer extends Uint8Array{constructor(e){super(e);this._view=new DataView(this.buffer);this._readPos=0;this._writePos=0}subarray(e,t){return ArrayUtils.subarray(this,e,t)}get readPos(){return this._readPos}set readPos(e){if(e<0||e>this.byteLength)throw`Invalid readPos ${e}`;this._readPos=e}get writePos(){return this._writePos}set writePos(e){if(e<0||e>this.byteLength)throw`Invalid writePos ${e}`;this._writePos=e}reset(){this._readPos=0;this._writePos=0}read(e){const t=this.subarray(this._readPos,this._readPos+e);this._readPos+=e;return new Uint8Array(t)}write(e){this.set(e,this._writePos);this._writePos+=e.byteLength}readUint8(){return this._view.getUint8(this._readPos++)}writeUint8(e){this._view.setUint8(this._writePos++,e)}readUint16(){const e=this._view.getUint16(this._readPos);this._readPos+=2;return e}writeUint16(e){this._view.setUint16(this._writePos,e);this._writePos+=2}readUint32(){const e=this._view.getUint32(this._readPos);this._readPos+=4;return e}writeUint32(e){this._view.setUint32(this._writePos,e);this._writePos+=4}readUint64(){const e=this._view.getUint32(this._readPos)*Math.pow(2,32)+this._view.getUint32(this._readPos+4);if(!NumberUtils.isUint64(e))throw new Error("Malformed value");this._readPos+=8;return e}writeUint64(e){if(!NumberUtils.isUint64(e))throw new Error("Malformed value");this._view.setUint32(this._writePos,Math.floor(e/Math.pow(2,32)));this._view.setUint32(this._writePos+4,e);this._writePos+=8}readUint128(){const e=new t("1000000000000000000000000",16),r=new t("10000000000000000",16),i=new t("100000000",16),n=this._view.getUint32(this._readPos),s=this._view.getUint32(this._readPos+4),o=this._view.getUint32(this._readPos+8),a=this._view.getUint32(this._readPos+12),l=e.times(n).plus(r.times(s)).plus(i.times(o)).plus(a);if(!NumberUtils.isUint128(l))throw new Error("Malformed value");this._readPos+=16;return l}writeUint128(e){if(!NumberUtils.isUint128(e))throw new Error("Malformed value");const r=new t("1000000000000000000000000",16),i=new t("10000000000000000",16),n=new t("100000000",16),s=e.idiv(r),o=e.mod(r).idiv(i),a=e.mod(i).idiv(n),l=e.mod(n);this._view.setUint32(this._writePos,s.toNumber());this._view.setUint32(this._writePos+4,o.toNumber());this._view.setUint32(this._writePos+8,a.toNumber());this._view.setUint32(this._writePos+12,l.toNumber());this._writePos+=16}readVarUint(){const e=this.readUint8();return e<253?e:253===e?this.readUint16():254===e?this.readUint32():this.readUint64()}writeVarUint(e){if(!NumberUtils.isUint64(e))throw new Error("Malformed value");if(e<253)this.writeUint8(e);else if(e<=65535){this.writeUint8(253);this.writeUint16(e)}else if(e<=4294967295){this.writeUint8(254);this.writeUint32(e)}else{this.writeUint8(255);this.writeUint64(e)}}static varUintSize(e){if(!NumberUtils.isUint64(e))throw new Error("Malformed value");return e<253?1:e<=65535?3:e<=4294967295?5:9}readFloat64(){const e=this._view.getFloat64(this._readPos);this._readPos+=8;return e}writeFloat64(e){this._view.setFloat64(this._writePos,e);this._writePos+=8}readString(e){const t=this.read(e);return BufferUtils.toAscii(t)}writeString(e,t){if(StringUtils.isMultibyte(e)||e.length!==t)throw new Error("Malformed value/length");const r=BufferUtils.fromAscii(e);this.write(r)}readPaddedString(e){const t=this.read(e);let r=0;for(;r<e&&0!==t[r];)r++;const i=new Uint8Array(t.buffer,t.byteOffset,r);return BufferUtils.toAscii(i)}writePaddedString(e,t){if(StringUtils.isMultibyte(e)||e.length>t)throw new Error("Malformed value/length");const r=BufferUtils.fromAscii(e);this.write(r);const i=t-r.byteLength;this.write(new Uint8Array(i))}readVarLengthString(){const e=this.readUint8();if(this._readPos+e>this.length)throw new Error("Malformed length");const t=this.read(e);return BufferUtils.toAscii(t)}writeVarLengthString(e){if(StringUtils.isMultibyte(e)||!NumberUtils.isUint8(e.length))throw new Error("Malformed value");const t=BufferUtils.fromAscii(e);this.writeUint8(t.byteLength);this.write(t)}static varLengthStringSize(e){if(StringUtils.isMultibyte(e)||!NumberUtils.isUint8(e.length))throw new Error("Malformed value");return 1+e.length}static concat(e){const t=e.reduce((e,t)=>e+t.length,0),r=new SerialBuffer(t);if(!e.length)return r;let i=0;for(let n of e){r.set(n,i);i+=n.length}return r}}SerialBuffer.EMPTY=new SerialBuffer(0);Class.register(SerialBuffer);class CRC8{static _createTable(){const e=[];for(let t=0;t<256;++t){let r=t;for(let e=0;e<8;++e)r=0!=(128&r)?(r<<1^151)%256:(r<<1)%256;e[t]=r}return e}static compute(e){CRC8._table||(CRC8._table=CRC8._createTable());let t=0;for(let r=0;r<e.length;r++)t=CRC8._table[(t^e[r])%256];return t}}CRC8._table=null;Class.register(CRC8);!function(e){"use strict";var t,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,n=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",a=1e14,l=14,c=9007199254740991,u=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,f=1e9;function bitFloor(e){var t=0|e;return e>0||e===t?t:t-1}function coeffToString(e){for(var t,r,i=1,n=e.length,s=e[0]+"";i<n;){t=e[i++]+"";r=l-t.length;for(;r--;t="0"+t);s+=t}for(n=s.length;48===s.charCodeAt(--n););return s.slice(0,n+1||1)}function compare(e,t){var r,i,n=e.c,s=t.c,o=e.s,a=t.s,l=e.e,c=t.e;if(!o||!a)return null;r=n&&!n[0];i=s&&!s[0];if(r||i)return r?i?0:-a:o;if(o!=a)return o;r=o<0;i=l==c;if(!n||!s)return i?0:!n^r?1:-1;if(!i)return l>c^r?1:-1;a=(l=n.length)<(c=s.length)?l:c;for(o=0;o<a;o++)if(n[o]!=s[o])return n[o]>s[o]^r?1:-1;return l==c?0:l>c^r?1:-1}function intCheck(e,t,r,o){if(e<t||e>r||e!==(e<0?i(e):n(e)))throw Error(s+(o||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+e)}function isArray(e){return"[object Array]"==Object.prototype.toString.call(e)}function isOdd(e){var t=e.c.length-1;return bitFloor(e.e/l)==t&&e.c[t]%2!=0}function toExponential(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function toFixedPoint(e,t,r){var i,n;if(t<0){for(n=r+".";++t;n+=r);e=n+e}else if(++t>(i=e.length)){for(n=r,t-=i;--t;n+=r);e+=n}else t<i&&(e=e.slice(0,t)+"."+e.slice(t));return e}(t=function clone(e){var t,d,g,m,y,p,_,w,A,E=BigNumber.prototype={constructor:BigNumber,toString:null,valueOf:null},S=new BigNumber(1),b=20,P=4,I=-7,U=21,v=-1e7,T=1e7,k=!1,C=1,N=0,L={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0},B="0123456789abcdefghijklmnopqrstuvwxyz";function BigNumber(e,t){var i,s,a,u,h,f,m,y=this;if(!(y instanceof BigNumber))return new BigNumber(e,t);if(null==t){if(e instanceof BigNumber){y.s=e.s;y.e=e.e;y.c=(e=e.c)?e.slice():e;return}if((h="number"==typeof e)&&0*e==0){y.s=1/e<0?(e=-e,-1):1;if(e===~~e){for(a=0,u=e;u>=10;u/=10,a++);y.e=a;y.c=[e];return}m=e+""}else{if(!r.test(m=e+""))return g(y,m,h);y.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}}else{intCheck(t,2,B.length,"Base");m=e+"";if(10==t)return round(y=new BigNumber(e instanceof BigNumber?e:m),b+y.e+1,P);if(h="number"==typeof e){if(0*e!=0)return g(y,m,h,t);y.s=1/e<0?(m=m.slice(1),-1):1;if(BigNumber.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(o+e);h=!1}else{y.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;t>10&&t<37&&(m=m.toLowerCase())}i=B.slice(0,t);a=u=0;for(f=m.length;u<f;u++)if(i.indexOf(s=m.charAt(u))<0){if("."==s&&u>a){a=f;continue}return g(y,e+"",h,t)}m=d(m,t,10,y.s)}(a=m.indexOf("."))>-1&&(m=m.replace(".",""));if((u=m.search(/e/i))>0){a<0&&(a=u);a+=+m.slice(u+1);m=m.substring(0,u)}else a<0&&(a=m.length);for(u=0;48===m.charCodeAt(u);u++);for(f=m.length;48===m.charCodeAt(--f););if(m=m.slice(u,++f)){f-=u;if(h&&BigNumber.DEBUG&&f>15&&(e>c||e!==n(e)))throw Error(o+y.s*e);if((a=a-u-1)>T)y.c=y.e=null;else if(a<v)y.c=[y.e=0];else{y.e=a;y.c=[];u=(a+1)%l;a<0&&(u+=l);if(u<f){u&&y.c.push(+m.slice(0,u));for(f-=l;u<f;)y.c.push(+m.slice(u,u+=l));m=m.slice(u);u=l-m.length}else u-=f;for(;u--;m+="0");y.c.push(+m)}}else y.c=[y.e=0]}BigNumber.clone=clone;BigNumber.ROUND_UP=0;BigNumber.ROUND_DOWN=1;BigNumber.ROUND_CEIL=2;BigNumber.ROUND_FLOOR=3;BigNumber.ROUND_HALF_UP=4;BigNumber.ROUND_HALF_DOWN=5;BigNumber.ROUND_HALF_EVEN=6;BigNumber.ROUND_HALF_CEIL=7;BigNumber.ROUND_HALF_FLOOR=8;BigNumber.EUCLID=9;BigNumber.config=BigNumber.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(s+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")){intCheck(r=e[t],0,f,t);b=r}if(e.hasOwnProperty(t="ROUNDING_MODE")){intCheck(r=e[t],0,8,t);P=r}if(e.hasOwnProperty(t="EXPONENTIAL_AT"))if(isArray(r=e[t])){intCheck(r[0],-f,0,t);intCheck(r[1],0,f,t);I=r[0];U=r[1]}else{intCheck(r,-f,f,t);I=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="RANGE"))if(isArray(r=e[t])){intCheck(r[0],-f,-1,t);intCheck(r[1],1,f,t);v=r[0];T=r[1]}else{intCheck(r,-f,f,t);if(!r)throw Error(s+t+" cannot be zero: "+r);v=-(T=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(s+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes){k=!r;throw Error(s+"crypto unavailable")}k=r}else k=r}if(e.hasOwnProperty(t="MODULO_MODE")){intCheck(r=e[t],0,9,t);C=r}if(e.hasOwnProperty(t="POW_PRECISION")){intCheck(r=e[t],0,f,t);N=r}if(e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(s+t+" not an object: "+r);L=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.$|\.|(.).*\1/.test(r))throw Error(s+t+" invalid: "+r);B=r}}return{DECIMAL_PLACES:b,ROUNDING_MODE:P,EXPONENTIAL_AT:[I,U],RANGE:[v,T],CRYPTO:k,MODULO_MODE:C,POW_PRECISION:N,FORMAT:L,ALPHABET:B}};BigNumber.isBigNumber=function(e){return e instanceof BigNumber||e&&!0===e._isBigNumber||!1};BigNumber.maximum=BigNumber.max=function(){return maxOrMin(arguments,E.lt)};BigNumber.minimum=BigNumber.min=function(){return maxOrMin(arguments,E.gt)};BigNumber.random=(m=9007199254740992*Math.random()&2097151?function(){return n(9007199254740992*Math.random())}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,o,a,c,h=0,d=[],g=new BigNumber(S);null==e?e=b:intCheck(e,0,f);a=i(e/l);if(k)if(crypto.getRandomValues){t=crypto.getRandomValues(new Uint32Array(a*=2));for(;h<a;)if((c=131072*t[h]+(t[h+1]>>>11))>=9e15){r=crypto.getRandomValues(new Uint32Array(2));t[h]=r[0];t[h+1]=r[1]}else{d.push(c%1e14);h+=2}h=a/2}else{if(!crypto.randomBytes){k=!1;throw Error(s+"crypto unavailable")}t=crypto.randomBytes(a*=7);for(;h<a;)if((c=281474976710656*(31&t[h])+1099511627776*t[h+1]+4294967296*t[h+2]+16777216*t[h+3]+(t[h+4]<<16)+(t[h+5]<<8)+t[h+6])>=9e15)crypto.randomBytes(7).copy(t,h);else{d.push(c%1e14);h+=7}h=a/7}if(!k)for(;h<a;)(c=m())<9e15&&(d[h++]=c%1e14);a=d[--h];e%=l;if(a&&e){c=u[l-e];d[h]=n(a/c)*c}for(;0===d[h];d.pop(),h--);if(h<0)d=[o=0];else{for(o=-1;0===d[0];d.splice(0,1),o-=l);for(h=1,c=d[0];c>=10;c/=10,h++);h<l&&(o-=l-h)}g.e=o;g.c=d;return g});d=function(){function toBaseOut(e,t,r,i){for(var n,s,o=[0],a=0,l=e.length;a<l;){for(s=o.length;s--;o[s]*=t);o[0]+=i.indexOf(e.charAt(a++));for(n=0;n<o.length;n++)if(o[n]>r-1){null==o[n+1]&&(o[n+1]=0);o[n+1]+=o[n]/r|0;o[n]%=r}}return o.reverse()}return function(e,r,i,n,s){var o,a,l,c,u,h,f,d,g=e.indexOf("."),m=b,y=P;if(g>=0){c=N;N=0;e=e.replace(".","");h=(d=new BigNumber(r)).pow(e.length-g);N=c;d.c=toBaseOut(toFixedPoint(coeffToString(h.c),h.e,"0"),10,i,"0123456789");d.e=d.c.length}l=c=(f=toBaseOut(e,r,i,s?(o=B,"0123456789"):(o="0123456789",B))).length;for(;0==f[--c];f.pop());if(!f[0])return o.charAt(0);if(g<0)--l;else{h.c=f;h.e=l;h.s=n;f=(h=t(h,d,m,y,i)).c;u=h.r;l=h.e}g=f[a=l+m+1];c=i/2;u=u||a<0||null!=f[a+1];u=y<4?(null!=g||u)&&(0==y||y==(h.s<0?3:2)):g>c||g==c&&(4==y||u||6==y&&1&f[a-1]||y==(h.s<0?8:7));if(a<1||!f[0])e=u?toFixedPoint(o.charAt(1),-m,o.charAt(0)):o.charAt(0);else{f.length=a;if(u)for(--i;++f[--a]>i;){f[a]=0;if(!a){++l;f=[1].concat(f)}}for(c=f.length;!f[--c];);for(g=0,e="";g<=c;e+=o.charAt(f[g++]));e=toFixedPoint(e,l,o.charAt(0))}return e}}();t=function(){function multiply(e,t,r){var i,n,s,o,a=0,l=e.length,c=t%h,u=t/h|0;for(e=e.slice();l--;){a=((n=c*(s=e[l]%h)+(i=u*s+(o=e[l]/h|0)*c)%h*h+a)/r|0)+(i/h|0)+u*o;e[l]=n%r}a&&(e=[a].concat(e));return e}function compare(e,t,r,i){var n,s;if(r!=i)s=r>i?1:-1;else for(n=s=0;n<r;n++)if(e[n]!=t[n]){s=e[n]>t[n]?1:-1;break}return s}function subtract(e,t,r,i){for(var n=0;r--;){e[r]-=n;n=e[r]<t[r]?1:0;e[r]=n*i+e[r]-t[r]}for(;!e[0]&&e.length>1;e.splice(0,1));}return function(e,t,r,i,s){var o,c,u,h,f,d,g,m,y,p,_,w,A,E,S,b,P,I=e.s==t.s?1:-1,U=e.c,v=t.c;if(!(U&&U[0]&&v&&v[0]))return new BigNumber(e.s&&t.s&&(U?!v||U[0]!=v[0]:v)?U&&0==U[0]||!v?0*I:I/0:NaN);y=(m=new BigNumber(I)).c=[];I=r+(c=e.e-t.e)+1;if(!s){s=a;c=bitFloor(e.e/l)-bitFloor(t.e/l);I=I/l|0}for(u=0;v[u]==(U[u]||0);u++);v[u]>(U[u]||0)&&c--;if(I<0){y.push(1);h=!0}else{E=U.length;b=v.length;u=0;I+=2;if((f=n(s/(v[0]+1)))>1){v=multiply(v,f,s);U=multiply(U,f,s);b=v.length;E=U.length}A=b;_=(p=U.slice(0,b)).length;for(;_<b;p[_++]=0);P=v.slice();P=[0].concat(P);S=v[0];v[1]>=s/2&&S++;do{f=0;if((o=compare(v,p,b,_))<0){w=p[0];b!=_&&(w=w*s+(p[1]||0));if((f=n(w/S))>1){f>=s&&(f=s-1);g=(d=multiply(v,f,s)).length;_=p.length;for(;1==compare(d,p,g,_);){f--;subtract(d,b<g?P:v,g,s);g=d.length;o=1}}else{0==f&&(o=f=1);g=(d=v.slice()).length}g<_&&(d=[0].concat(d));subtract(p,d,_,s);_=p.length;if(-1==o)for(;compare(v,p,b,_)<1;){f++;subtract(p,b<_?P:v,_,s);_=p.length}}else if(0===o){f++;p=[0]}y[u++]=f;if(p[0])p[_++]=U[A]||0;else{p=[U[A]];_=1}}while((A++<E||null!=p[0])&&I--);h=null!=p[0];y[0]||y.splice(0,1)}if(s==a){for(u=1,I=y[0];I>=10;I/=10,u++);round(m,r+(m.e=u+c*l-1)+1,i,h)}else{m.e=c;m.r=+h}return m}}();function format(e,t,r,i){var n,s,o,a,l;null==r?r=P:intCheck(r,0,8);if(!e.c)return e.toString();n=e.c[0];o=e.e;if(null==t){l=coeffToString(e.c);l=1==i||2==i&&o<=I?toExponential(l,o):toFixedPoint(l,o,"0")}else{s=(e=round(new BigNumber(e),t,r)).e;a=(l=coeffToString(e.c)).length;if(1==i||2==i&&(t<=s||s<=I)){for(;a<t;l+="0",a++);l=toExponential(l,s)}else{t-=o;l=toFixedPoint(l,s,"0");if(s+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=s-a)>0){s+1==a&&(l+=".");for(;t--;l+="0");}}}return e.s<0&&n?"-"+l:l}function maxOrMin(e,t){var r,i,n=0;isArray(e[0])&&(e=e[0]);r=new BigNumber(e[0]);for(;++n<e.length;){if(!(i=new BigNumber(e[n])).s){r=i;break}t.call(r,i)&&(r=i)}return r}function normalise(e,t,r){for(var i=1,n=t.length;!t[--n];t.pop());for(n=t[0];n>=10;n/=10,i++);if((r=i+r*l-1)>T)e.c=e.e=null;else if(r<v)e.c=[e.e=0];else{e.e=r;e.c=t}return e}g=(y=/^(-?)0([xbo])(?=\w[\w.]*$)/i,p=/^([^.]+)\.$/,_=/^\.([^.]+)$/,w=/^-?(Infinity|NaN)$/,A=/^\s*\+(?=[\w.])|^\s+|\s+$/g,function(e,t,r,i){var n,o=r?t:t.replace(A,"");if(w.test(o)){e.s=isNaN(o)?null:o<0?-1:1;e.c=e.e=null}else{if(!r){o=o.replace(y,function(e,t,r){n="x"==(r=r.toLowerCase())?16:"b"==r?2:8;return i&&i!=n?e:t});if(i){n=i;o=o.replace(p,"$1").replace(_,"0.$1")}if(t!=o)return new BigNumber(o,n)}if(BigNumber.DEBUG)throw Error(s+"Not a"+(i?" base "+i:"")+" number: "+t);e.c=e.e=e.s=null}});function round(e,t,r,s){var o,c,h,f,d,g,m,y=e.c,p=u;if(y){e:{for(o=1,f=y[0];f>=10;f/=10,o++);if((c=t-o)<0){c+=l;h=t;m=(d=y[g=0])/p[o-h-1]%10|0}else if((g=i((c+1)/l))>=y.length){if(!s)break e;for(;y.length<=g;y.push(0));d=m=0;o=1;h=(c%=l)-l+1}else{d=f=y[g];for(o=1;f>=10;f/=10,o++);m=(h=(c%=l)-l+o)<0?0:d/p[o-h-1]%10|0}s=s||t<0||null!=y[g+1]||(h<0?d:d%p[o-h-1]);s=r<4?(m||s)&&(0==r||r==(e.s<0?3:2)):m>5||5==m&&(4==r||s||6==r&&(c>0?h>0?d/p[o-h]:0:y[g-1])%10&1||r==(e.s<0?8:7));if(t<1||!y[0]){y.length=0;if(s){t-=e.e+1;y[0]=p[(l-t%l)%l];e.e=-t||0}else y[0]=e.e=0;return e}if(0==c){y.length=g;f=1;g--}else{y.length=g+1;f=p[l-c];y[g]=h>0?n(d/p[o-h]%p[h])*f:0}if(s)for(;;){if(0==g){for(c=1,h=y[0];h>=10;h/=10,c++);h=y[0]+=f;for(f=1;h>=10;h/=10,f++);if(c!=f){e.e++;y[0]==a&&(y[0]=1)}break}y[g]+=f;if(y[g]!=a)break;y[g--]=0;f=1}for(c=y.length;0===y[--c];y.pop());}e.e>T?e.c=e.e=null:e.e<v&&(e.c=[e.e=0])}return e}E.absoluteValue=E.abs=function(){var e=new BigNumber(this);e.s<0&&(e.s=1);return e};E.comparedTo=function(e,t){return compare(this,new BigNumber(e,t))};E.decimalPlaces=E.dp=function(e,t){var r,i,n,s=this;if(null!=e){intCheck(e,0,f);null==t?t=P:intCheck(t,0,8);return round(new BigNumber(s),e+s.e+1,t)}if(!(r=s.c))return null;i=((n=r.length-1)-bitFloor(this.e/l))*l;if(n=r[n])for(;n%10==0;n/=10,i--);i<0&&(i=0);return i};E.dividedBy=E.div=function(e,r){return t(this,new BigNumber(e,r),b,P)};E.dividedToIntegerBy=E.idiv=function(e,r){return t(this,new BigNumber(e,r),0,1)};E.exponentiatedBy=E.pow=function(e,t){var r,o,a,c,u,h,f,d=this;if((e=new BigNumber(e)).c&&!e.isInteger())throw Error(s+"Exponent not an integer: "+e);null!=t&&(t=new BigNumber(t));c=e.e>14;if(!d.c||!d.c[0]||1==d.c[0]&&!d.e&&1==d.c.length||!e.c||!e.c[0]){f=new BigNumber(Math.pow(+d.valueOf(),c?2-isOdd(e):+e));return t?f.mod(t):f}u=e.s<0;if(t){if(t.c?!t.c[0]:!t.s)return new BigNumber(NaN);(o=!u&&d.isInteger()&&t.isInteger())&&(d=d.mod(t))}else{if(e.e>9&&(d.e>0||d.e<-1||(0==d.e?d.c[0]>1||c&&d.c[1]>=24e7:d.c[0]<8e13||c&&d.c[0]<=9999975e7))){a=d.s<0&&isOdd(e)?-0:0;d.e>-1&&(a=1/a);return new BigNumber(u?1/a:a)}N&&(a=i(N/l+2))}if(c){r=new BigNumber(.5);h=isOdd(e)}else h=e%2;u&&(e.s=1);f=new BigNumber(S);for(;;){if(h){if(!(f=f.times(d)).c)break;a?f.c.length>a&&(f.c.length=a):o&&(f=f.mod(t))}if(c){round(e=e.times(r),e.e+1,1);if(!e.c[0])break;c=e.e>14;h=isOdd(e)}else{if(!(e=n(e/2)))break;h=e%2}d=d.times(d);a?d.c&&d.c.length>a&&(d.c.length=a):o&&(d=d.mod(t))}if(o)return f;u&&(f=S.div(f));return t?f.mod(t):a?round(f,N,P,void 0):f};E.integerValue=function(e){var t=new BigNumber(this);null==e?e=P:intCheck(e,0,8);return round(t,t.e+1,e)};E.isEqualTo=E.eq=E.equals=function(e,t){return 0===compare(this,new BigNumber(e,t))};E.isFinite=function(){return!!this.c};E.isGreaterThan=E.gt=function(e,t){return compare(this,new BigNumber(e,t))>0};E.isGreaterThanOrEqualTo=E.gte=function(e,t){return 1===(t=compare(this,new BigNumber(e,t)))||0===t};E.isInteger=function(){return!!this.c&&bitFloor(this.e/l)>this.c.length-2};E.isLessThan=E.lt=function(e,t){return compare(this,new BigNumber(e,t))<0};E.isLessThanOrEqualTo=E.lte=function(e,t){return-1===(t=compare(this,new BigNumber(e,t)))||0===t};E.isNaN=function(){return!this.s};E.isNegative=function(){return this.s<0};E.isPositive=function(){return this.s>0};E.isZero=function(){return!!this.c&&0==this.c[0]};E.minus=function(e,t){var r,i,n,s,o=this,c=o.s;t=(e=new BigNumber(e,t)).s;if(!c||!t)return new BigNumber(NaN);if(c!=t){e.s=-t;return o.plus(e)}var u=o.e/l,h=e.e/l,f=o.c,d=e.c;if(!u||!h){if(!f||!d)return f?(e.s=-t,e):new BigNumber(d?o:NaN);if(!f[0]||!d[0])return d[0]?(e.s=-t,e):new BigNumber(f[0]?o:3==P?-0:0)}u=bitFloor(u);h=bitFloor(h);f=f.slice();if(c=u-h){if(s=c<0){c=-c;n=f}else{h=u;n=d}n.reverse();for(t=c;t--;n.push(0));n.reverse()}else{i=(s=(c=f.length)<(t=d.length))?c:t;for(c=t=0;t<i;t++)if(f[t]!=d[t]){s=f[t]<d[t];break}}s&&(n=f,f=d,d=n,e.s=-e.s);if((t=(i=d.length)-(r=f.length))>0)for(;t--;f[r++]=0);t=a-1;for(;i>c;){if(f[--i]<d[i]){for(r=i;r&&!f[--r];f[r]=t);--f[r];f[i]+=a}f[i]-=d[i]}for(;0==f[0];f.splice(0,1),--h);if(!f[0]){e.s=3==P?-1:1;e.c=[e.e=0];return e}return normalise(e,f,h)};E.modulo=E.mod=function(e,r){var i,n,s=this;e=new BigNumber(e,r);if(!s.c||!e.s||e.c&&!e.c[0])return new BigNumber(NaN);if(!e.c||s.c&&!s.c[0])return new BigNumber(s);if(9==C){n=e.s;e.s=1;i=t(s,e,0,3);e.s=n;i.s*=n}else i=t(s,e,0,C);(e=s.minus(i.times(e))).c[0]||1!=C||(e.s=s.s);return e};E.multipliedBy=E.times=function(e,t){var r,i,n,s,o,c,u,f,d,g,m,y,p,_,w,A=this,E=A.c,S=(e=new BigNumber(e,t)).c;if(!(E&&S&&E[0]&&S[0])){if(!A.s||!e.s||E&&!E[0]&&!S||S&&!S[0]&&!E)e.c=e.e=e.s=null;else{e.s*=A.s;if(E&&S){e.c=[0];e.e=0}else e.c=e.e=null}return e}i=bitFloor(A.e/l)+bitFloor(e.e/l);e.s*=A.s;(u=E.length)<(g=S.length)&&(p=E,E=S,S=p,n=u,u=g,g=n);for(n=u+g,p=[];n--;p.push(0));_=a;w=h;for(n=g;--n>=0;){r=0;m=S[n]%w;y=S[n]/w|0;for(s=n+(o=u);s>n;){r=((f=m*(f=E[--o]%w)+(c=y*f+(d=E[o]/w|0)*m)%w*w+p[s]+r)/_|0)+(c/w|0)+y*d;p[s--]=f%_}p[s]=r}r?++i:p.splice(0,1);return normalise(e,p,i)};E.negated=function(){var e=new BigNumber(this);e.s=-e.s||null;return e};E.plus=function(e,t){var r,i=this,n=i.s;t=(e=new BigNumber(e,t)).s;if(!n||!t)return new BigNumber(NaN);if(n!=t){e.s=-t;return i.minus(e)}var s=i.e/l,o=e.e/l,c=i.c,u=e.c;if(!s||!o){if(!c||!u)return new BigNumber(n/0);if(!c[0]||!u[0])return u[0]?e:new BigNumber(c[0]?i:0*n)}s=bitFloor(s);o=bitFloor(o);c=c.slice();if(n=s-o){if(n>0){o=s;r=u}else{n=-n;r=c}r.reverse();for(;n--;r.push(0));r.reverse()}(n=c.length)-(t=u.length)<0&&(r=u,u=c,c=r,t=n);for(n=0;t;){n=(c[--t]=c[t]+u[t]+n)/a|0;c[t]=a===c[t]?0:c[t]%a}if(n){c=[n].concat(c);++o}return normalise(e,c,o)};E.precision=E.sd=function(e,t){var r,i,n,s=this;if(null!=e&&e!==!!e){intCheck(e,1,f);null==t?t=P:intCheck(t,0,8);return round(new BigNumber(s),e,t)}if(!(r=s.c))return null;i=(n=r.length-1)*l+1;if(n=r[n]){for(;n%10==0;n/=10,i--);for(n=r[0];n>=10;n/=10,i++);}e&&s.e+1>i&&(i=s.e+1);return i};E.shiftedBy=function(e){intCheck(e,-c,c);return this.times("1e"+e)};E.squareRoot=E.sqrt=function(){var e,r,i,n,s,o=this,a=o.c,l=o.s,c=o.e,u=b+4,h=new BigNumber("0.5");if(1!==l||!a||!a[0])return new BigNumber(!l||l<0&&(!a||a[0])?NaN:a?o:1/0);if(0==(l=Math.sqrt(+o))||l==1/0){((r=coeffToString(a)).length+c)%2==0&&(r+="0");l=Math.sqrt(r);c=bitFloor((c+1)/2)-(c<0||c%2);i=new BigNumber(r=l==1/0?"1e"+c:(r=l.toExponential()).slice(0,r.indexOf("e")+1)+c)}else i=new BigNumber(l+"");if(i.c[0]){(l=(c=i.e)+u)<3&&(l=0);for(;;){s=i;i=h.times(s.plus(t(o,s,u,1)));if(coeffToString(s.c).slice(0,l)===(r=coeffToString(i.c)).slice(0,l)){i.e<c&&--l;if("9999"!=(r=r.slice(l-3,l+1))&&(n||"4999"!=r)){if(!+r||!+r.slice(1)&&"5"==r.charAt(0)){round(i,i.e+b+2,1);e=!i.times(i).eq(o)}break}if(!n){round(s,s.e+b+2,0);if(s.times(s).eq(o)){i=s;break}}u+=4;l+=4;n=1}}}return round(i,i.e+b+1,P,e)};E.toExponential=function(e,t){if(null!=e){intCheck(e,0,f);e++}return format(this,e,t,1)};E.toFixed=function(e,t){if(null!=e){intCheck(e,0,f);e=e+this.e+1}return format(this,e,t)};E.toFormat=function(e,t){var r=this.toFixed(e,t);if(this.c){var i,n=r.split("."),s=+L.groupSize,o=+L.secondaryGroupSize,a=L.groupSeparator,l=n[0],c=n[1],u=this.s<0,h=u?l.slice(1):l,f=h.length;o&&(i=s,s=o,o=i,f-=i);if(s>0&&f>0){i=f%s||s;l=h.substr(0,i);for(;i<f;i+=s)l+=a+h.substr(i,s);o>0&&(l+=a+h.slice(i));u&&(l="-"+l)}r=c?l+L.decimalSeparator+((o=+L.fractionGroupSize)?c.replace(new RegExp("\\d{"+o+"}\\B","g"),"$&"+L.fractionGroupSeparator):c):l}return r};E.toFraction=function(e){var r,i,n,o,a,c,h,f,d,g,m,y,p=this,_=p.c;if(null!=e&&(!(f=new BigNumber(e)).isInteger()&&(f.c||1!==f.s)||f.lt(S)))throw Error(s+"Argument "+(f.isInteger()?"out of range: ":"not an integer: ")+e);if(!_)return p.toString();i=new BigNumber(S);g=n=new BigNumber(S);o=d=new BigNumber(S);y=coeffToString(_);c=i.e=y.length-p.e-1;i.c[0]=u[(h=c%l)<0?l+h:h];e=!e||f.comparedTo(i)>0?c>0?i:g:f;h=T;T=1/0;f=new BigNumber(y);d.c[0]=0;for(;;){m=t(f,i,0,1);if(1==(a=n.plus(m.times(o))).comparedTo(e))break;n=o;o=a;g=d.plus(m.times(a=g));d=a;i=f.minus(m.times(a=i));f=a}a=t(e.minus(n),o,0,1);d=d.plus(a.times(g));n=n.plus(a.times(o));d.s=g.s=p.s;r=t(g,o,c*=2,P).minus(p).abs().comparedTo(t(d,n,c,P).minus(p).abs())<1?[g.toString(),o.toString()]:[d.toString(),n.toString()];T=h;return r};E.toNumber=function(){return+this};E.toPrecision=function(e,t){null!=e&&intCheck(e,1,f);return format(this,e,t,2)};E.toString=function(e){var t,r=this,i=r.s,n=r.e;if(null===n)if(i){t="Infinity";i<0&&(t="-"+t)}else t="NaN";else{t=coeffToString(r.c);if(null==e)t=n<=I||n>=U?toExponential(t,n):toFixedPoint(t,n,"0");else{intCheck(e,2,B.length,"Base");t=d(toFixedPoint(t,n,"0"),10,e,i,!0)}i<0&&r.c[0]&&(t="-"+t)}return t};E.valueOf=E.toJSON=function(){var e,t=this,r=t.e;if(null===r)return t.toString();e=coeffToString(t.c);e=r<=I||r>=U?toExponential(e,r):toFixedPoint(e,r,"0");return t.s<0?"-"+e:e};E._isBigNumber=!0;null!=e&&BigNumber.set(e);return BigNumber}())["default"]=t.BigNumber=t;e.BigNumber=t}(Class.scope);const t=Class.scope.BigNumber;t.config({DECIMAL_PLACES:11});class NumberUtils{static isUint8(e){return Number.isInteger(e)&&e>=0&&e<=NumberUtils.UINT8_MAX}static isUint16(e){return Number.isInteger(e)&&e>=0&&e<=NumberUtils.UINT16_MAX}static isUint32(e){return Number.isInteger(e)&&e>=0&&e<=NumberUtils.UINT32_MAX}static isUint64(e){return Number.isInteger(e)&&e>=0&&e<=NumberUtils.UINT64_MAX}static isUint128(e){return e.isInteger()&&e.gte(0)&&e.lte(NumberUtils.UINT128_MAX)}static randomUint32(){return Math.floor(Math.random()*(NumberUtils.UINT32_MAX+1))}static randomUint64(){return Math.floor(Math.random()*(NumberUtils.UINT64_MAX+1))}static fromBinary(e){return parseInt(e,2)}}NumberUtils.UINT8_MAX=255;NumberUtils.UINT16_MAX=65535;NumberUtils.UINT32_MAX=4294967295;NumberUtils.UINT64_MAX=Number.MAX_SAFE_INTEGER;NumberUtils.UINT128_MAX=new t("ffffffffffffffffffffffffffffffff",16);Class.register(NumberUtils);class MerkleTree{static computeRoot(e,t=MerkleTree._hash){return MerkleTree._computeRoot(e,t)}static _computeRoot(e,t){const r=e.length;if(0===r)return Hash.light(new Uint8Array(0));if(1===r)return t(e[0]);const i=Math.round(r/2),n=e.slice(0,i),s=e.slice(i),o=MerkleTree._computeRoot(n,t),a=MerkleTree._computeRoot(s,t);return Hash.light(BufferUtils.concatTypedArrays(o.serialize(),a.serialize()))}static _hash(e){if(e instanceof Hash)return e;if("function"==typeof e.hash)return e.hash();if("function"==typeof e.serialize)return Hash.light(e.serialize());if(e instanceof Uint8Array)return Hash.light(e);throw new Error("MerkleTree objects must be Uint8Array or have a .hash()/.serialize() method")}}Class.register(MerkleTree);class MerklePath{constructor(e){if(!Array.isArray(e)||!NumberUtils.isUint8(e.length)||e.some(e=>!(e instanceof MerklePathNode)))throw new Error("Malformed nodes");this._nodes=e}static compute(e,t,r=MerkleTree._hash){const i=r(t),n=[];MerklePath._compute(e,i,n,r);return new MerklePath(n)}static _compute(e,t,r,i){const n=e.length;let s;if(0===n)return{containsLeaf:!1,inner:s=Hash.light(new Uint8Array(0))};if(1===n)return{containsLeaf:(s=i(e[0])).equals(t),inner:s};const o=Math.round(n/2),a=e.slice(0,o),l=e.slice(o),{containsLeaf:c,inner:u}=MerklePath._compute(a,t,r,i),{containsLeaf:h,inner:f}=MerklePath._compute(l,t,r,i);s=Hash.light(BufferUtils.concatTypedArrays(u.serialize(),f.serialize()));if(c){r.push(new MerklePathNode(f,!1));return{containsLeaf:!0,inner:s}}if(h){r.push(new MerklePathNode(u,!0));return{containsLeaf:!0,inner:s}}return{containsLeaf:!1,inner:s}}computeRoot(e,t=MerkleTree._hash){let r=t(e);for(const i of this._nodes){const e=i.left,t=i.hash,n=new SerialBuffer(2*t.serializedSize);e&&t.serialize(n);r.serialize(n);e||t.serialize(n);r=Hash.light(n)}return r}static _compress(e){const t=e.length,r=Math.ceil(t/8),i=new Uint8Array(r);for(let n=0;n<t;n++)e[n].left&&(i[Math.floor(n/8)]|=128>>>n%8);return i}static unserialize(e){const t=e.readUint8(),r=Math.ceil(t/8),i=e.read(r),n=[];for(let s=0;s<t;s++){const t=0!=(i[Math.floor(s/8)]&128>>>s%8),r=e.readUint8(),o=Hash.unserialize(e,r);n.push(new MerklePathNode(o,t))}return new MerklePath(n)}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).writeUint8(this._nodes.length);e.write(MerklePath._compress(this._nodes));for(const t of this._nodes){e.writeUint8(t.hash.algorithm);t.hash.serialize(e)}return e}get serializedSize(){return 1+Math.ceil(this._nodes.length/8)+this._nodes.reduce((e,t)=>e+1+t.hash.serializedSize,0)}equals(e){return e instanceof MerklePath&&this._nodes.length===e._nodes.length&&this._nodes.every((t,r)=>t.equals(e._nodes[r]))}get nodes(){return this._nodes}}Class.register(MerklePath);class MerklePathNode{constructor(e,t){this._hash=e;this._left=t}get hash(){return this._hash}get left(){return this._left}equals(e){return e instanceof MerklePathNode&&this._hash.equals(e.hash)&&this._left===e.left}}Class.register(MerklePathNode);class MnemonicUtils{static _crcChecksum(e){const t=8*e.length/32,r=CRC8.compute(e);return BufferUtils.toBinary([r]).slice(0,t)}static _sha256Checksum(e){const t=8*e.length/32,r=Hash.computeSha256(e);return BufferUtils.toBinary(r).slice(0,t)}static _entropyToBits(e){if(e.length<16)throw new Error("Invalid key, length < 16");if(e.length>32)throw new Error("Invalid key, length > 32");if(e.length%4!=0)throw new Error("Invalid key, length % 4 != 0");return BufferUtils.toBinary(e)}static _normalizeEntropy(e){"string"==typeof e&&(e=BufferUtils.fromHex(e));e instanceof Entropy&&(e=e.serialize());e instanceof ArrayBuffer&&(e=new Uint8Array(e));return e}static _bitsToMnemonic(e,t){return e.match(/(.{11})/g).map(e=>{const r=NumberUtils.fromBinary(e);return t[r]})}static _mnemonicToBits(e,t){const r=e;if(r.length<12)throw new Error("Invalid mnemonic, less than 12 words");if(r.length>24)throw new Error("Invalid mnemonic, more than 24 words");if(r.length%3!=0)throw new Error("Invalid mnemonic, words % 3 != 0");return r.map(function(e){const r=t.indexOf(e.toLowerCase());if(-1===r)throw new Error(`Invalid mnemonic, word >${e}< is not in wordlist`);return StringUtils.lpad(r.toString(2),"0",11)}).join("")}static _bitsToEntropy(e,t=!1){const r=e.length-(e.length%8||8),i=e.slice(0,r),n=e.slice(r),s=i.match(/(.{8})/g).map(NumberUtils.fromBinary);if(s.length<16)throw new Error("Invalid generated key, length < 16");if(s.length>32)throw new Error("Invalid generated key, length > 32");if(s.length%4!=0)throw new Error("Invalid generated key, length % 4 != 0");const o=new Uint8Array(s);if((t?MnemonicUtils._crcChecksum(o):MnemonicUtils._sha256Checksum(o))!==n)throw new Error("Invalid checksum");return o}static entropyToMnemonic(e,t){t=t||MnemonicUtils.DEFAULT_WORDLIST;e=MnemonicUtils._normalizeEntropy(e);const r=MnemonicUtils._entropyToBits(e)+MnemonicUtils._sha256Checksum(e);return MnemonicUtils._bitsToMnemonic(r,t)}static entropyToLegacyMnemonic(e,t){t=t||MnemonicUtils.DEFAULT_WORDLIST;e=MnemonicUtils._normalizeEntropy(e);const r=MnemonicUtils._entropyToBits(e)+MnemonicUtils._crcChecksum(e);return MnemonicUtils._bitsToMnemonic(r,t)}static mnemonicToEntropy(e,t){Array.isArray(e)||(e=e.trim().split(/\s+/g));t=t||MnemonicUtils.DEFAULT_WORDLIST;const r=MnemonicUtils._mnemonicToBits(e,t);return new Entropy(MnemonicUtils._bitsToEntropy(r,!1))}static legacyMnemonicToEntropy(e,t){Array.isArray(e)||(e=e.trim().split(/\s+/g));t=t||MnemonicUtils.DEFAULT_WORDLIST;const r=MnemonicUtils._mnemonicToBits(e,t);return new Entropy(MnemonicUtils._bitsToEntropy(r,!0))}static _salt(e){return`mnemonic${e||""}`}static mnemonicToSeed(e,t){Array.isArray(e)&&(e=e.join(" "));const r=BufferUtils.fromAscii(e),i=BufferUtils.fromAscii(MnemonicUtils._salt(t));return CryptoUtils.computePBKDF2sha512(r,i,2048,64)}static mnemonicToExtendedPrivateKey(e,t){const r=MnemonicUtils.mnemonicToSeed(e,t);return ExtendedPrivateKey.generateMasterKey(r)}static isCollidingChecksum(e){const t=MnemonicUtils._normalizeEntropy(e);return MnemonicUtils._crcChecksum(t)===MnemonicUtils._sha256Checksum(t)}static getMnemonicType(e,t){Array.isArray(e)||(e=e.trim().split(/\s+/g));t=t||MnemonicUtils.DEFAULT_WORDLIST;const r=MnemonicUtils._mnemonicToBits(e,t);let i=!0;try{MnemonicUtils._bitsToEntropy(r,!1)}catch(s){i=!1}let n=!0;try{MnemonicUtils._bitsToEntropy(r,!0)}catch(s){n=!1}if(i&&n)return MnemonicUtils.MnemonicType.UNKNOWN;if(!i&&!n)throw new Error("Invalid checksum");return i?MnemonicUtils.MnemonicType.BIP39:MnemonicUtils.MnemonicType.LEGACY}}MnemonicUtils.ENGLISH_WORDLIST=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];MnemonicUtils.DEFAULT_WORDLIST=MnemonicUtils.ENGLISH_WORDLIST;MnemonicUtils.MnemonicType={UNKNOWN:-1,LEGACY:0,BIP39:1};Object.freeze(MnemonicUtils);Class.register(MnemonicUtils);class StringUtils{static isMultibyte(e){return/[\uD800-\uDFFF]/.test(e)}static isHex(e){return/^[0-9A-Fa-f]*$/.test(e)}static isHexBytes(e,t){return!!StringUtils.isHex(e)&&(e.length%2==0&&("number"!=typeof t||e.length/2===t))}static commonPrefix(e,t){let r=0;for(;r<e.length&&e[r]===t[r];++r);return e.substr(0,r)}static lpad(e,t,r){for(;e.length<r;)e=t+e;return e}}Class.register(StringUtils);class Policy{static coinsToSatoshis(e){return new t(e).times(Policy.SATOSHIS_PER_COIN).integerValue()}static satoshisToCoins(e){return new t(e).div(Policy.SATOSHIS_PER_COIN)}static blockRewardAt(e){if(e<=0)return new t(0);const r=Math.min(Math.floor((e-1)/Policy.HALVING_INTERVAL),Policy.HALVING_TARGET_MAX-1);return new t(Policy.INITIAL_BLOCK_REWARD).idiv(Math.pow(2,r))}static blockTime(e){return e<=Policy.BLOCK_TIME_MILESTONE?Policy.INITIAL_BLOCK_TIME:e>Policy.HALVING_INTERVAL*Policy.HALVING_TARGET_MAX?Policy.INITIAL_BLOCK_TIME:Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-Math.floor((e-1)/Policy.HALVING_INTERVAL))}static targetedTime(e){if(e<=Policy.BLOCK_TIME_MILESTONE)return(e-1)*Policy.INITIAL_BLOCK_TIME;const t=Policy.BLOCK_TIME_MILESTONE*Policy.INITIAL_BLOCK_TIME,r=Policy.BLOCK_TIME_MULTIPLE*Policy.HALVING_TARGET_MAX;if(e<=Policy.HALVING_INTERVAL)return t+(e-Policy.BLOCK_TIME_MILESTONE-1)*r;let i=t+(Policy.HALVING_INTERVAL-Policy.BLOCK_TIME_MILESTONE)*r,n=e-Policy.HALVING_INTERVAL,s=1;for(;n>Policy.HALVING_INTERVAL&&s<Policy.HALVING_TARGET_MAX;){i+=Policy.HALVING_INTERVAL*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-s);n-=Policy.HALVING_INTERVAL;s+=1}s>=Policy.HALVING_TARGET_MAX?i+=(n-1)*Policy.INITIAL_BLOCK_TIME:i+=(n-1)*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-s);return i}static targetedTimeBlockRange(e,t){const r=e>1?e:1,i=t>1?t:1;if(r>=i)return 0;const n=Policy.HALVING_INTERVAL*Policy.HALVING_TARGET_MAX;let s=i-r;if(i<=Policy.BLOCK_TIME_MILESTONE||r>n)return s*Policy.INITIAL_BLOCK_TIME;const o=Policy.BLOCK_TIME_MULTIPLE*Policy.HALVING_TARGET_MAX;if(i<=Policy.HALVING_INTERVAL)return r<=Policy.BLOCK_TIME_MILESTONE?(Policy.BLOCK_TIME_MILESTONE-r+1)*Policy.INITIAL_BLOCK_TIME+(i-Policy.BLOCK_TIME_MILESTONE-1)*o:s*o;const a=Math.floor((r-1)/Policy.HALVING_INTERVAL);let l,c=Math.floor((i-1)/Policy.HALVING_INTERVAL);if(a===c)return s*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-a);let u,h=0;if(r<=Policy.BLOCK_TIME_MILESTONE)l=(Policy.BLOCK_TIME_MILESTONE-r+1)*Policy.INITIAL_BLOCK_TIME+(Policy.HALVING_INTERVAL-Policy.BLOCK_TIME_MILESTONE)*o;else{l=((a+1)*Policy.HALVING_INTERVAL-r+1)*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-a)}if(i>n){c=Policy.HALVING_TARGET_MAX;u=(i-n-1)*Policy.INITIAL_BLOCK_TIME}else{u=(i-c*Policy.HALVING_INTERVAL-1)*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-c)}for(let f=a+1;f<c;f++)h+=Policy.HALVING_INTERVAL*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-f);return l+h+u}static txFee(e){if(e<=1)return new t(0);const r=Math.floor((e-1)/Policy.TX_FEE_CHANGING_INTERVAL);return r<Policy.TX_FEE_CHANGING_TOTAL_NUMBER?new t(Policy.INITIAL_TX_FEE).div(Math.pow(10,r)):new t(1)}static blockSize(e){return e<Policy.FORKING_FOR_BLOCK_DIFFICULTY_BLOCK_SIZE?Policy.INITIAL_BLOCK_SIZE:Policy.BASE_BLOCK_SIZE+Policy.BLOCK_SIZE_FACTOR*Math.floor(e/Policy.BLOCK_SIZE_CHANGING_INTERVAL)}static difficultyBlockWindow(e){if(e>=Policy.SECOND_FORKING_FOR_BLOCK_DIFFICULTY||e<Policy.FORKING_FOR_BLOCK_DIFFICULTY_BLOCK_SIZE)return Policy.DIFFICULTY_BLOCK_WINDOW;const t=Policy.blockTime(e);return Math.floor(360/t)}}Policy.INITIAL_BLOCK_TIME=3;Policy.BLOCK_TIME_MULTIPLE=3;Policy.BLOCK_TIME_MILESTONE=11e5;Policy.INITIAL_BLOCK_SIZE=1e5;Policy.BASE_BLOCK_SIZE=21e5;Policy.BLOCK_SIZE_FACTOR=2100;Policy.BLOCK_SIZE_CHANGING_INTERVAL=21e5;Policy.BLOCK_TARGET_MAX=new t(2).pow(240);Policy.DIFFICULTY_BLOCK_WINDOW=120;Policy.FORKING_FOR_BLOCK_DIFFICULTY_BLOCK_SIZE=1124816;Policy.DIFFICULTY_MAX_ADJUSTMENT_FACTOR=2;Policy.NEW_DIFFICULTY_MAX_ADJUSTMENT_FACTOR=1.3;Policy.NEW_DIFFICULTY_MIN_ADJUSTMENT_FACTOR=.7;Policy.SECOND_FORKING_FOR_BLOCK_DIFFICULTY=1132333;Policy.SECOND_DIFFICULTY_MAX_ADJUSTMENT_FACTOR=1.5;Policy.SECOND_DIFFICULTY_MIN_ADJUSTMENT_FACTOR=.5;Policy.TRANSACTION_VALIDITY_WINDOW=120;Policy.SATOSHIS_PER_COIN=1e11;Policy.INITIAL_SUPPLY=0;Policy.INITIAL_BLOCK_REWARD=5e11;Policy.HALVING_TARGET_MAX=21;Policy.HALVING_INTERVAL=21e5;Policy.M=240;Policy.K=120;Policy.DELTA=.15;Policy.NUM_BLOCKS_VERIFICATION=250;Policy.NUM_SNAPSHOTS_MAX=20;Policy.INITIAL_TX_FEE=1e6;Policy.TX_FEE_CHANGING_INTERVAL=63e5;Policy.TX_FEE_CHANGING_TOTAL_NUMBER=6;Class.register(Policy);class Serializable{equals(e){return e instanceof Serializable&&BufferUtils.equals(this.serialize(),e.serialize())}compare(e){return BufferUtils.compare(this.serialize(),e.serialize())}hashCode(){return this.toBase64()}serialize(e){}toString(){return this.toBase64()}toBase64(){return BufferUtils.toBase64(this.serialize())}toHex(){return BufferUtils.toHex(this.serialize())}toBase58(){return BufferUtils.toBase58(this.serialize())}toBase58Check(e=128,t){return BufferUtils.toBase58Check(this.serialize(),e,t)}}Class.register(Serializable);class Hash extends Serializable{constructor(e,t=Hash.Algorithm.BLAKE2B){if(null===e)e=new Uint8Array(Hash.getSize(t));else{if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==Hash.getSize(t))throw new Error("Primitive: Invalid length")}super();this._obj=e;this._algorithm=t}static light(e){return Hash.blake2b(e)}static blake2b(e){return new Hash(Hash.computeBlake2b(e),Hash.Algorithm.BLAKE2B)}static hard(e){return Hash.argon2d(e)}static async argon2d(e){return new Hash(await(await CryptoWorker.getInstanceAsync()).computeArgon2d(e),Hash.Algorithm.ARGON2D)}static sha256(e){return new Hash(Hash.computeSha256(e),Hash.Algorithm.SHA256)}static sha512(e){return new Hash(Hash.computeSha512(e),Hash.Algorithm.SHA512)}static ripemd160(e){return new Hash(Hash.computeRipemd160(e),Hash.Algorithm.RIPEMD160)}static doubleHash(e){return Hash.ripemd160(Hash.computeSha256(e))}static keccak256(e){return new Hash(Hash.computeKeccak256(e),Hash.Algorithm.KECCAK256)}static compute(e,t){switch(t){case Hash.Algorithm.BLAKE2B:return Hash.blake2b(e);case Hash.Algorithm.SHA256:return Hash.sha256(e);default:throw new Error("Invalid hash algorithm")}}static unserialize(e,t=Hash.Algorithm.BLAKE2B){return new Hash(e.read(Hash.getSize(t)),t)}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}subarray(e,t){return this._obj.subarray(e,t)}get serializedSize(){return Hash.SIZE.get(this._algorithm)}get array(){return this._obj}get algorithm(){return this._algorithm}equals(e){return e instanceof Hash&&e._algorithm===this._algorithm&&super.equals(e)}static fromAny(e,t=Hash.Algorithm.BLAKE2B){if(e instanceof Hash)return e;try{return new Hash(BufferUtils.fromAny(e,Hash.SIZE.get(t)),t)}catch(r){throw new Error("Invalid hash format")}}toPlain(){return this.toHex()}static fromBase64(e){return new Hash(BufferUtils.fromBase64(e))}static fromHex(e){return new Hash(BufferUtils.fromHex(e))}static fromPlain(e){return Hash.fromString(e)}static fromString(e){try{return Hash.fromHex(e)}catch(t){}try{return Hash.fromBase64(e)}catch(t){}throw new Error("Invalid hash format")}static isHash(e){return e instanceof Hash}static getSize(e){const t=Hash.SIZE.get(e);if("number"!=typeof t)throw new Error("Invalid hash algorithm");return t}static computeBlake2b(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.BLAKE2B));NodeNative.node_blake2(t,new Uint8Array(e));return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.BLAKE2B),n=Module.stackAlloc(i),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);const o=Module._krypton_blake2(n,s,e.length);if(0!==o)throw o;const a=new Uint8Array(i);a.set(new Uint8Array(Module.HEAPU8.buffer,n,i));return a}catch(t){Log.w(Hash,t);throw t}finally{r!==undefined&&Module.stackRestore(r)}}}static computeSha256(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA256));NodeNative.node_sha256(t,new Uint8Array(e));return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.SHA256),n=Module.stackAlloc(i),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);Module._krypton_sha256(n,s,e.length);const o=new Uint8Array(i);o.set(new Uint8Array(Module.HEAPU8.buffer,n,i));return o}catch(t){Log.w(Hash,t);throw t}finally{r!==undefined&&Module.stackRestore(r)}}}static computeSha512(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA512));NodeNative.node_sha512(t,new Uint8Array(e));return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.SHA512),n=Module.stackAlloc(i),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);Module._krypton_sha512(n,s,e.length);const o=new Uint8Array(i);o.set(new Uint8Array(Module.HEAPU8.buffer,n,i));return o}catch(t){Log.w(Hash,t);throw t}finally{r!==undefined&&Module.stackRestore(r)}}}static computeRipemd160(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.RIPEMD160));NodeNative.node_ripemd160(t,new Uint8Array(e));return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.RIPEMD160),n=Module.stackAlloc(i),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);Module._ripemd160(s,e.length,n);const o=new Uint8Array(i);o.set(new Uint8Array(Module.HEAPU8.buffer,n,i));return o}catch(t){Log.w(Hash,t);throw t}finally{r!==undefined&&Module.stackRestore(r)}}}static computeKeccak256(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.KECCAK256));NodeNative.node_keccak256(t,new Uint8Array(e));return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.KECCAK256),n=Module.stackAlloc(i),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);Module._keccak256(s,e.length,n);const o=new Uint8Array(i);o.set(new Uint8Array(Module.HEAPU8.buffer,n,i));return o}catch(t){Log.w(Hash,t);throw t}finally{r!==undefined&&Module.stackRestore(r)}}}}Hash.Algorithm={BLAKE2B:1,ARGON2D:2,SHA256:3,SHA512:4,RIPEMD160:5,KECCAK256:6};Hash.Algorithm.toString=function(e){switch(e){case Hash.Algorithm.BLAKE2B:return"blake2b";case Hash.Algorithm.ARGON2D:return"argon2d";case Hash.Algorithm.SHA256:return"sha256";case Hash.Algorithm.SHA512:return"sha512";case Hash.Algorithm.RIPEMD160:return"ripemd160";case Hash.Algorithm.KECCAK256:return"keccak256"}throw new Error("Invalid hash algorithm")};Hash.Algorithm.fromAny=function(e){if("number"==typeof e)return e;switch(e){case"blake2b":return Hash.Algorithm.BLAKE2B;case"argon2d":return Hash.Algorithm.ARGON2D;case"sha256":return Hash.Algorithm.SHA256;case"sha512":return Hash.Algorithm.SHA512;case"ripemd160":return Hash.Algorithm.RIPEMD160;case"keccak256":return Hash.Algorithm.KECCAK256}throw new Error("Invalid hash algorithm")};Hash.SIZE=new Map;Hash.SIZE.set(Hash.Algorithm.BLAKE2B,32);Hash.SIZE.set(Hash.Algorithm.ARGON2D,32);Hash.SIZE.set(Hash.Algorithm.SHA256,32);Hash.SIZE.set(Hash.Algorithm.SHA512,64);Hash.SIZE.set(Hash.Algorithm.RIPEMD160,20);Hash.SIZE.set(Hash.Algorithm.KECCAK256,32);Hash.NULL=new Hash(new Uint8Array(32));Class.register(Hash);class Secret extends Serializable{constructor(e,t){super();this._type=e;this._purposeId=t}static fromEncrypted(e,t){const r=e.readUint8(),i=e.readUint8();if(i>32)throw new Error("Rounds out-of-bounds");const n=Math.pow(2,i);switch(r){case 1:return Secret._decryptV1(e,t,n);case 2:return Secret._decryptV2(e,t,n);case 3:return Secret._decryptV3(e,t,n);default:throw new Error("Unsupported version")}}static async _decryptV1(e,t,r){const i=e.read(Secret.SIZE),n=e.read(Secret.ENCRYPTION_SALT_SIZE),s=e.read(Secret.ENCRYPTION_CHECKSUM_SIZE),o=await CryptoUtils.otpKdfLegacy(i,t,n,r),a=new PrivateKey(o),l=PublicKey.derive(a).hash().subarray(0,Secret.ENCRYPTION_CHECKSUM_SIZE);if(!BufferUtils.equals(s,l))throw new Error("Invalid key");return a}static async _decryptV2(e,t,r){const i=e.read(Secret.SIZE),n=e.read(Secret.ENCRYPTION_SALT_SIZE),s=e.read(Secret.ENCRYPTION_CHECKSUM_SIZE),o=await CryptoUtils.otpKdfLegacy(i,t,n,r),a=Hash.computeBlake2b(o).subarray(0,Secret.ENCRYPTION_CHECKSUM_SIZE);if(!BufferUtils.equals(s,a))throw new Error("Invalid key");return new PrivateKey(o)}static async _decryptV3(e,t,r){const i=e.read(Secret.ENCRYPTION_SALT_SIZE),n=e.read(Secret.ENCRYPTION_CHECKSUM_SIZE_V3+4+Secret.SIZE),s=await CryptoUtils.otpKdf(n,t,i,r),o=s.subarray(0,Secret.ENCRYPTION_CHECKSUM_SIZE_V3),a=s.subarray(Secret.ENCRYPTION_CHECKSUM_SIZE_V3),l=Hash.computeBlake2b(a).subarray(0,Secret.ENCRYPTION_CHECKSUM_SIZE_V3);if(!BufferUtils.equals(o,l))throw new Error("Invalid key");const c=a[0]<<24|a[1]<<16|a[2]<<8|a[3],u=a.subarray(4);switch(c){case PrivateKey.PURPOSE_ID:return new PrivateKey(u);case Entropy.PURPOSE_ID:default:return new Entropy(u)}}async exportEncrypted(e){const t=new Uint8Array(Secret.ENCRYPTION_SALT_SIZE);CryptoWorker.lib.getRandomValues(t);const r=new SerialBuffer(4+Secret.SIZE);r.writeUint32(this._purposeId);r.write(this.serialize());const i=Hash.computeBlake2b(r).subarray(0,Secret.ENCRYPTION_CHECKSUM_SIZE_V3),n=new SerialBuffer(i.byteLength+r.byteLength);n.write(i);n.write(r);const s=await CryptoUtils.otpKdf(n,e,t,Secret.ENCRYPTION_KDF_ROUNDS),o=new SerialBuffer(2+t.byteLength+s.byteLength);o.writeUint8(3);o.writeUint8(Math.log2(Secret.ENCRYPTION_KDF_ROUNDS));o.write(t);o.write(s);return o}get encryptedSize(){return 2+Secret.ENCRYPTION_SALT_SIZE+Secret.ENCRYPTION_CHECKSUM_SIZE_V3+4+Secret.SIZE}get type(){return this._type}}Secret.Type={PRIVATE_KEY:1,ENTROPY:2};Secret.SIZE=32;Secret.ENCRYPTION_SALT_SIZE=16;Secret.ENCRYPTION_KDF_ROUNDS=256;Secret.ENCRYPTION_CHECKSUM_SIZE=4;Secret.ENCRYPTION_CHECKSUM_SIZE_V3=2;Class.register(Secret);class PrivateKey extends Secret{constructor(e){super(Secret.Type.PRIVATE_KEY,PrivateKey.PURPOSE_ID);if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==PrivateKey.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static generate(){const e=new Uint8Array(PrivateKey.SIZE);CryptoWorker.lib.getRandomValues(e);return new PrivateKey(e)}static unserialize(e){return new PrivateKey(e.read(PrivateKey.SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return PrivateKey.SIZE}overwrite(e){this._obj.set(e._obj)}equals(e){return e instanceof PrivateKey&&super.equals(e)}static _privateKeyDelinearize(e,t,r){if(e.byteLength!==PrivateKey.SIZE||t.byteLength!==PublicKey.SIZE||r.byteLength!==Hash.getSize(Hash.Algorithm.SHA256))throw Error("Wrong buffer size.");if(PlatformUtils.isNodeJs()){const i=new Uint8Array(PublicKey.SIZE);NodeNative.node_secp256k1_derive_delinearized_seckey(i,new Uint8Array(r),new Uint8Array(t),new Uint8Array(e));return i}{let n;try{n=Module.stackSave();const s=Module.stackAlloc(PublicKey.SIZE),o=Module.stackAlloc(e.length),a=Module.stackAlloc(t.length),l=Module.stackAlloc(r.length);new Uint8Array(Module.HEAPU8.buffer,o,e.length).set(e);new Uint8Array(Module.HEAPU8.buffer,a,t.length).set(t);new Uint8Array(Module.HEAPU8.buffer,l,r.length).set(r);Module._secp256k1_derive_delinearized_seckey(s,l,a,o);const c=new Uint8Array(PrivateKey.SIZE);c.set(new Uint8Array(Module.HEAPU8.buffer,s,PrivateKey.SIZE));return c}catch(i){Log.w(CryptoWorkerImpl,i);throw i}finally{n!==undefined&&Module.stackRestore(n)}}}}PrivateKey.SIZE=Secret.SIZE;PrivateKey.PURPOSE_ID=1107296257;Class.register(PrivateKey);class PublicKey extends Serializable{static copy(e){return e?new PublicKey(new Uint8Array(e._obj)):e}constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==PublicKey.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static derive(e){return new PublicKey(PublicKey._publicKeyDerive(e._obj))}compress(){return PublicKey._compressPublicKey(this._obj)}static sum(e){(e=e.slice()).sort((e,t)=>e.compare(t));return PublicKey._delinearizeAndAggregatePublicKeys(e)}static unserialize(e){return new PublicKey(e.read(PublicKey.SIZE))}static fromAny(e){if(!e)throw new Error("Invalid public key format");if(e instanceof PublicKey)return e;try{return new PublicKey(BufferUtils.fromAny(e,PublicKey.SIZE))}catch(t){throw new Error("Invalid public key format")}}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return PublicKey.SIZE}equals(e){return e instanceof PublicKey&&super.equals(e)}hash(){return Hash.keccak256(this.serialize().slice(1))}compare(e){return BufferUtils.compare(this._obj,e._obj)}toAddress(){return Address.fromHash(this.hash())}toPeerId(){return new PeerId(this.hash().subarray(0,16))}static _delinearizeAndAggregatePublicKeys(e){const t=e.map(e=>e.serialize()),r=PublicKey._publicKeysHash(t),i=PublicKey._publicKeysDelinearizeAndAggregate(t,r);return new PublicKey(i)}static _compressPublicKey(e){if(e.byteLength!==PublicKey.SIZE)throw Error("Wrong buffer size.");const t=new Uint8Array(32);CryptoWorker.lib.getRandomValues(t);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(t);const r=new Uint8Array(PublicKey.COMPRESSED_SIZE);NodeNative.node_secp256k1_pubkey_compress(r,new Uint8Array(e));NodeNative.node_secp256k1_ctx_release();return r}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,n,32).set(t);Module._secp256k1_ctx_init(n);const s=Module.stackAlloc(PublicKey.COMPRESSED_SIZE),o=new Uint8Array(Module.HEAP8.buffer,s,PublicKey.COMPRESSED_SIZE),a=Module.stackAlloc(PublicKey.SIZE);new Uint8Array(Module.HEAP8.buffer,a,PublicKey.SIZE).set(e);Module._secp256k1_pubkey_compress(s,a);const l=new Uint8Array(PublicKey.COMPRESSED_SIZE);l.set(o);return l}catch(r){Log.w(PublicKey,r);throw r}finally{Module._secp256k1_ctx_release();i!==undefined&&Module.stackRestore(i)}}}static _publicKeyDerive(e){if(e.byteLength!==PrivateKey.SIZE)throw Error("Wrong buffer size.");const t=new Uint8Array(32);CryptoWorker.lib.getRandomValues(t);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(t);const r=new Uint8Array(PublicKey.SIZE);NodeNative.node_secp256k1_pubkey_create(r,new Uint8Array(e));NodeNative.node_secp256k1_ctx_release();return r}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,n,32).set(t);Module._secp256k1_ctx_init(n);const s=Module.stackAlloc(PublicKey.SIZE),o=new Uint8Array(Module.HEAP8.buffer,s,PublicKey.SIZE),a=Module.stackAlloc(e.length),l=new Uint8Array(Module.HEAP8.buffer,a,PrivateKey.SIZE);l.set(e);Module._secp256k1_pubkey_create(s,PublicKey.SIZE,a);l.fill(0);const c=new Uint8Array(PublicKey.SIZE);c.set(o);return c}catch(r){Log.w(PublicKey,r);throw r}finally{Module._secp256k1_ctx_release();i!==undefined&&Module.stackRestore(i)}}}static _publicKeysHash(e){if(e.some(e=>e.byteLength!==PublicKey.SIZE))throw Error("Wrong buffer size.");const t=new Uint8Array(e.length*PublicKey.SIZE);for(let i=0;i<e.length;++i)t.set(e[i],i*PublicKey.SIZE);if(PlatformUtils.isNodeJs()){const r=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA256));NodeNative.node_secp256k1_hash_pubkeys(r,t,e.length,PublicKey.SIZE);return r}{let i;try{i=Module.stackSave();const n=Hash.getSize(Hash.Algorithm.SHA256),s=Module.stackAlloc(n),o=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,o,t.length).set(t);Module._secp256k1_hash_pubkeys(s,o,e.length,PublicKey.SIZE);const a=new Uint8Array(n);a.set(new Uint8Array(Module.HEAPU8.buffer,s,n));return a}catch(r){Log.w(PublicKey,r);throw r}finally{i!==undefined&&Module.stackRestore(i)}}}static _publicKeyDelinearize(e,t){if(e.byteLength!==PublicKey.SIZE||t.byteLength!==Hash.getSize(Hash.Algorithm.SHA256))throw Error("Wrong buffer size.");if(PlatformUtils.isNodeJs()){const r=new Uint8Array(PublicKey.SIZE);NodeNative.node_secp256k1_delinearize_pubkey(r,new Uint8Array(t),new Uint8Array(e));return r}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(PublicKey.SIZE),s=Module.stackAlloc(e.length),o=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);new Uint8Array(Module.HEAPU8.buffer,o,t.length).set(t);Module._secp256k1_delinearize_pubkey(n,o,s);const a=new Uint8Array(PublicKey.SIZE);a.set(new Uint8Array(Module.HEAPU8.buffer,n,PublicKey.SIZE));return a}catch(r){Log.w(PublicKey,r);throw r}finally{i!==undefined&&Module.stackRestore(i)}}}static _publicKeysDelinearizeAndAggregate(e,t){if(e.some(e=>e.byteLength!==PublicKey.SIZE)||t.byteLength!==Hash.getSize(Hash.Algorithm.SHA256))throw Error("Wrong buffer size.");const r=new Uint8Array(e.length*PublicKey.SIZE);for(let n=0;n<e.length;++n)r.set(e[n],n*PublicKey.SIZE);if(PlatformUtils.isNodeJs()){const i=new Uint8Array(PublicKey.SIZE);NodeNative.node_secp256k1_aggregate_delinearized_publkeys(i,new Uint8Array(t),r,e.length,PublicKey.SIZE);return i}{let n;try{n=Module.stackSave();const s=Module.stackAlloc(PublicKey.SIZE),o=Module.stackAlloc(r.length),a=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,o,r.length).set(r);new Uint8Array(Module.HEAPU8.buffer,a,t.length).set(t);Module._secp256k1_aggregate_delinearized_publkeys(s,a,o,e.length,PublicKey.SIZE);const l=new Uint8Array(PublicKey.SIZE);l.set(new Uint8Array(Module.HEAPU8.buffer,s,PublicKey.SIZE));return l}catch(i){Log.w(PublicKey,i);throw i}finally{n!==undefined&&Module.stackRestore(n)}}}}PublicKey.COMPRESSED_SIZE=33;PublicKey.SIZE=65;Class.register(PublicKey);class KeyPair extends Serializable{constructor(e,t,r=!1,i=null){if(!(e instanceof Object))throw new Error("Primitive: Invalid type");if(!(t instanceof Object))throw new Error("Primitive: Invalid type");super();this._locked=r;this._lockedInternally=r;this._lockSalt=i;this._publicKey=t;this._internalPrivateKey=new PrivateKey(e.serialize())}static generate(){const e=PrivateKey.generate();return new KeyPair(e,PublicKey.derive(e))}static derive(e){return new KeyPair(e,PublicKey.derive(e))}static fromHex(e){return KeyPair.unserialize(BufferUtils.fromHex(e))}static unserialize(e){const t=PrivateKey.unserialize(e),r=PublicKey.unserialize(e);let i=!1,n=null;if(e.readPos<e.byteLength){if(1===e.readUint8()){i=!0;n=e.read(32)}}return new KeyPair(t,r,i,n)}serialize(e){e=e||new SerialBuffer(this.serializedSize);this._privateKey.serialize(e);this.publicKey.serialize(e);if(this._locked){e.writeUint8(1);e.write(this._lockSalt)}else e.writeUint8(0);return e}get privateKey(){if(this.isLocked)throw new Error("KeyPair is locked");return this._privateKey}get _privateKey(){return this._unlockedPrivateKey||this._internalPrivateKey}get publicKey(){return this._publicKey||(this._publicKey=new PublicKey(this._obj.publicKey))}get serializedSize(){return this._privateKey.serializedSize+this.publicKey.serializedSize+(this._locked?this._lockSalt.byteLength+1:1)}async lock(e,t){if(this._locked)throw new Error("KeyPair already locked");t&&(this._lockSalt=t);if(!this._lockSalt||0===this._lockSalt.length){this._lockSalt=new Uint8Array(32);CryptoWorker.lib.getRandomValues(this._lockSalt)}this._internalPrivateKey.overwrite(await this._otpPrivateKey(e));this._clearUnlockedPrivateKey();this._locked=!0;this._lockedInternally=!0}async unlock(e){if(!this._locked)throw new Error("KeyPair not locked");const t=await this._otpPrivateKey(e);if(!PublicKey.derive(t).equals(this.publicKey))throw new Error("Invalid key");this._unlockedPrivateKey=t;this._locked=!1}relock(){if(this._locked)throw new Error("KeyPair already locked");if(!this._lockedInternally)throw new Error("KeyPair was never locked");this._clearUnlockedPrivateKey();this._locked=!0}_clearUnlockedPrivateKey(){if(this._lockedInternally&&!this._locked){this._unlockedPrivateKey.overwrite(PrivateKey.unserialize(new SerialBuffer(this._unlockedPrivateKey.serializedSize)));this._unlockedPrivateKey=null}}async _otpPrivateKey(e){return new PrivateKey(await CryptoUtils.otpKdfLegacy(this._privateKey.serialize(),e,this._lockSalt,KeyPair.LOCK_KDF_ROUNDS))}get isLocked(){return this._locked}static async fromEncrypted(e,t){const r=await Secret.fromEncrypted(e,t);if(r.type!==Secret.Type.PRIVATE_KEY)throw new Error("Expected privateKey, got Entropy");return KeyPair.derive(r)}exportEncrypted(e){return this._privateKey.exportEncrypted(e)}get encryptedSize(){return this._privateKey.encryptedSize}equals(e){return e instanceof KeyPair&&super.equals(e)}}KeyPair.LOCK_KDF_ROUNDS=256;Class.register(KeyPair);class Entropy extends Secret{constructor(e){super(Secret.Type.ENTROPY,Entropy.PURPOSE_ID);if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==Entropy.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static generate(){const e=new Uint8Array(Entropy.SIZE);CryptoWorker.lib.getRandomValues(e);return new Entropy(e)}toExtendedPrivateKey(e,t){return MnemonicUtils.mnemonicToExtendedPrivateKey(this.toMnemonic(t),e)}toMnemonic(e){return MnemonicUtils.entropyToMnemonic(this,e)}static unserialize(e){return new Entropy(e.read(Entropy.SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return Entropy.SIZE}overwrite(e){this._obj.set(e._obj)}equals(e){return e instanceof Entropy&&super.equals(e)}}Entropy.SIZE=Secret.SIZE;Entropy.PURPOSE_ID=1107296258;Class.register(Entropy);class ExtendedPrivateKey extends Serializable{constructor(e,t){super();if(!(e instanceof PrivateKey))throw new Error("ExtendedPrivateKey: Invalid key");if(!(t instanceof Uint8Array))throw new Error("ExtendedPrivateKey: Invalid chainCode");if(t.length!==ExtendedPrivateKey.CHAIN_CODE_SIZE)throw new Error("ExtendedPrivateKey: Invalid chainCode length");this._key=e;this._chainCode=t}static generateMasterKey(e){const t=BufferUtils.fromAscii("secp256k1 seed"),r=CryptoUtils.computeHmacSha512(t,e);return new ExtendedPrivateKey(new PrivateKey(r.slice(0,32)),r.slice(32))}derive(e){e<2147483648&&(e+=2147483648);const t=new SerialBuffer(1+PrivateKey.SIZE+4);t.writeUint8(0);this._key.serialize(t);t.writeUint32(e);const r=CryptoUtils.computeHmacSha512(this._chainCode,t);return new ExtendedPrivateKey(new PrivateKey(r.slice(0,32)),r.slice(32))}static isValidPath(e){if(null===e.match(/^m(\/[0-9]+')*$/))return!1;const t=e.split("/");for(let r=1;r<t.length;r++)if(!NumberUtils.isUint32(parseInt(t[r])))return!1;return!0}derivePath(e){if(!ExtendedPrivateKey.isValidPath(e))throw new Error("Invalid path");let t=this;const r=e.split("/");for(let i=1;i<r.length;i++){const e=parseInt(r[i]);t=t.derive(e)}return t}static derivePathFromSeed(e,t){return ExtendedPrivateKey.generateMasterKey(t).derivePath(e)}static unserialize(e){const t=PrivateKey.unserialize(e),r=e.read(ExtendedPrivateKey.CHAIN_CODE_SIZE);return new ExtendedPrivateKey(t,r)}serialize(e){e=e||new SerialBuffer(this.serializedSize);this._key.serialize(e);e.write(this._chainCode);return e}get serializedSize(){return this._key.serializedSize+ExtendedPrivateKey.CHAIN_CODE_SIZE}equals(e){return e instanceof ExtendedPrivateKey&&super.equals(e)}get privateKey(){return this._key}toAddress(){return PublicKey.derive(this._key).toAddress()}}ExtendedPrivateKey.CHAIN_CODE_SIZE=32;Class.register(ExtendedPrivateKey);class RandomSecret extends Serializable{constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==RandomSecret.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static unserialize(e){return new RandomSecret(e.read(RandomSecret.SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return RandomSecret.SIZE}equals(e){return e instanceof RandomSecret&&super.equals(e)}}RandomSecret.SIZE=32;Class.register(RandomSecret);class Signature extends Serializable{static copy(e){if(!e)return e;const t=new Uint8Array(e._obj);return new Signature(t)}constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==Signature.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static create(e,t,r){return new Signature(Signature._signatureCreate(e._obj,t.compress(),r))}static fromPartialSignatures(e,t){const r=Signature._combinePartialSignatures(e.serialize(),t.map(e=>e.serialize()));return new Signature(r)}static unserialize(e){return new Signature(e.read(Signature.SIZE))}static fromAny(e){if(!e)throw new Error("Invalid signature format");if(e instanceof Signature)return e;try{return new Signature(BufferUtils.fromAny(e,Signature.SIZE))}catch(t){throw new Error("Invalid signature format")}}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return Signature.SIZE}verify(e,t){return Signature._signatureVerify(e.compress(),t,this._obj)}equals(e){return e instanceof Signature&&super.equals(e)}static _combinePartialSignatures(e,t){return Signature._aggregatePartialSignatures(t)}static _aggregatePartialSignatures(e){return e.reduce((e,t)=>{if(!e)return t;const r=e.slice(0,PartialSignature.HALF_SIZE),i=e.slice(PartialSignature.HALF_SIZE),n=t.slice(PartialSignature.HALF_SIZE),s=Signature._scalarsAdd(i,n);return BufferUtils.concatTypedArrays(r,s)})}static _scalarsAdd(e,t){if(e.byteLength!==PartialSignature.HALF_SIZE||t.byteLength!==PartialSignature.HALF_SIZE)throw Error("Wrong buffer size.");if(PlatformUtils.isNodeJs()){const r=new Uint8Array(PartialSignature.HALF_SIZE);NodeNative.node_secp256k1_add_scalars(r,new Uint8Array(e),new Uint8Array(t));return r}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(PartialSignature.HALF_SIZE),s=Module.stackAlloc(e.length),o=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);new Uint8Array(Module.HEAPU8.buffer,o,t.length).set(t);Module._secp256k1_add_scalars(n,s,o);const a=new Uint8Array(PartialSignature.HALF_SIZE);a.set(new Uint8Array(Module.HEAPU8.buffer,n,PartialSignature.HALF_SIZE));return a}catch(r){Log.w(Signature,r);throw r}finally{i!==undefined&&Module.stackRestore(i)}}}static _signatureCreate(e,t,r){if(e.byteLength!==PrivateKey.SIZE||t.byteLength!=PublicKey.COMPRESSED_SIZE)throw Error("Wrong buffer size.");const i=new Uint8Array(32);CryptoWorker.lib.getRandomValues(i);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(i);const n=new Uint8Array(Signature.SIZE);NodeNative.node_secp256k1_schnorr_sign(n,new Uint8Array(r),new Uint8Array(t),new Uint8Array(e));NodeNative.node_secp256k1_ctx_release();return n}{let s;try{s=Module.stackSave();const o=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,o,32).set(i);Module._secp256k1_ctx_init(o);const a=Module.stackAlloc(Signature.SIZE),l=new Uint8Array(Module.HEAP8.buffer,a,Signature.SIZE),c=Module.stackAlloc(r.length);new Uint8Array(Module.HEAP8.buffer,c,r.length).set(r);const u=Module.stackAlloc(t.length);new Uint8Array(Module.HEAP8.buffer,u,t.length).set(t);const h=Module.stackAlloc(e.length),f=new Uint8Array(Module.HEAP8.buffer,h,e.length);f.set(e);Module._secp256k1_schnorr_sign(a,c,r.byteLength,u,h);f.fill(0);const d=new Uint8Array(Signature.SIZE);d.set(l);return d}catch(n){Log.w(Signature,n);throw n}finally{Module._secp256k1_ctx_release();s!==undefined&&Module.stackRestore(s)}}}static _signatureVerify(e,t,r){const i=new Uint8Array(32);CryptoWorker.lib.getRandomValues(i);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(i);const n=!!NodeNative.node_secp256k1_schnorr_verify(new Uint8Array(r),new Uint8Array(t),new Uint8Array(e));NodeNative.node_secp256k1_ctx_release();return n}{let s;try{s=Module.stackSave();const o=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,o,32).set(i);Module._secp256k1_ctx_init(o);const a=Module.stackAlloc(e.length);new Uint8Array(Module.HEAP8.buffer,a,e.length).set(e);const l=Module.stackAlloc(t.length);new Uint8Array(Module.HEAP8.buffer,l,t.length).set(t);const c=Module.stackAlloc(r.length);new Uint8Array(Module.HEAP8.buffer,c,r.length).set(r);return!!Module._secp256k1_schnorr_verify(c,l,t.byteLength,a)}catch(n){Log.w(Signature,n);throw n}finally{Module._secp256k1_ctx_release();s!==undefined&&Module.stackRestore(s)}}}}Signature.SIZE=64;Class.register(Signature);class Commitment extends Serializable{static copy(e){return e?new Commitment(new Uint8Array(e._obj)):e}static sum(e){return new Commitment(Commitment._commitmentsAggregate(e.map(e=>e._obj)))}constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==Commitment.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}compress(){return PublicKey._compressPublicKey(this._obj)}static unserialize(e){return new Commitment(e.read(Commitment.SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return Commitment.SIZE}equals(e){return e instanceof Commitment&&super.equals(e)}static _commitmentsAggregate(e){if(e.some(e=>e.byteLength!==Commitment.SIZE))throw Error("Wrong buffer size.");const t=new Uint8Array(e.length*Commitment.SIZE);for(let i=0;i<e.length;++i)t.set(e[i],i*Commitment.SIZE);if(PlatformUtils.isNodeJs()){const r=new Uint8Array(Commitment.SIZE);NodeNative.node_secp256k1_aggregate_commitments(r,t,e.length,Commitment.SIZE);return r}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(Commitment.SIZE),s=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,s,t.length).set(t);Module._secp256k1_aggregate_commitments(n,s,e.length,Commitment.SIZE);const o=new Uint8Array(Commitment.SIZE);o.set(new Uint8Array(Module.HEAPU8.buffer,n,Commitment.SIZE));return o}catch(r){Log.w(CryptoWorkerImpl,r);throw r}finally{i!==undefined&&Module.stackRestore(i)}}}}Commitment.COMPRESSED_SIZE=33;Commitment.SIZE=65;Class.register(Commitment);class CommitmentPair extends Serializable{constructor(e,t){super();if(!(e instanceof RandomSecret))throw new Error("Primitive: Invalid type");if(!(t instanceof Commitment))throw new Error("Primitive: Invalid type");this._secret=e;this._commitment=t}static generate(){const e=new Uint8Array(CommitmentPair.RANDOMNESS_SIZE);CryptoWorker.lib.getRandomValues(e);const t=CommitmentPair._commitmentCreate(e);return new CommitmentPair(new RandomSecret(t.secret),new Commitment(t.commitment))}static unserialize(e){const t=RandomSecret.unserialize(e),r=Commitment.unserialize(e);return new CommitmentPair(t,r)}static fromHex(e){return this.unserialize(BufferUtils.fromHex(e))}serialize(e){e=e||new SerialBuffer(this.serializedSize);this.secret.serialize(e);this.commitment.serialize(e);return e}get secret(){return this._secret}get commitment(){return this._commitment}get serializedSize(){return this.secret.serializedSize+this.commitment.serializedSize}equals(e){return e instanceof CommitmentPair&&super.equals(e)}static _commitmentCreate(e){const t=new Uint8Array(32);CryptoWorker.lib.getRandomValues(t);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(t);const r=new Uint8Array(Commitment.SIZE),i=new Uint8Array(PrivateKey.SIZE);NodeNative.node_secp256k1_create_commitment(i,r,e);NodeNative.node_secp256k1_ctx_release();return{commitment:r,secret:i}}{let i;try{i=Module.stackSave();const n=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,n,32).set(t);Module._secp256k1_ctx_init(n);const s=Module.stackAlloc(Commitment.SIZE),o=Module.stackAlloc(PrivateKey.SIZE),a=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,a,e.length).set(e);const l=Module._secp256k1_create_commitment(o,s,Commitment.SIZE,a);if(1!==l)throw new Error(`Secret must not be 0 or 1: ${l}`);const c=new Uint8Array(Commitment.SIZE),u=new Uint8Array(PrivateKey.SIZE);c.set(new Uint8Array(Module.HEAPU8.buffer,s,Commitment.SIZE));u.set(new Uint8Array(Module.HEAPU8.buffer,o,PrivateKey.SIZE));return{commitment:c,secret:u}}catch(r){Log.w(CommitmentPair,r);throw r}finally{Module._secp256k1_ctx_release();i!==undefined&&Module.stackRestore(i)}}}}CommitmentPair.SERIALIZED_SIZE=RandomSecret.SIZE+Signature.SIZE;CommitmentPair.RANDOMNESS_SIZE=32;Class.register(CommitmentPair);class PartialSignature extends Serializable{constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==PartialSignature.SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static create(e,t,r,i,n,s){const o=PartialSignature._delinearizedPartialSignatureCreate(r.map(e=>e.compress()),e._obj,t.compress(),i._obj,n.compress(),s);return new PartialSignature(o)}static unserialize(e){return new PartialSignature(e.read(PartialSignature.SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}get serializedSize(){return PartialSignature.SIZE}equals(e){return e instanceof PartialSignature&&super.equals(e)}static _delinearizedPartialSignatureCreate(e,t,r,i,n,s){if(e.some(e=>e.byteLength!==PublicKey.COMPRESSED_SIZE)||t.byteLength!==PrivateKey.SIZE||r.byteLength!==PublicKey.COMPRESSED_SIZE||i.byteLength!==RandomSecret.SIZE||n.byteLength!==Commitment.COMPRESSED_SIZE)throw Error("Wrong buffer size.");const o=new Uint8Array(32);CryptoWorker.lib.getRandomValues(o);const a=new Uint8Array(e.length*PublicKey.COMPRESSED_SIZE);for(let c=0;c<e.length;++c)a.set(e[c],c*PublicKey.COMPRESSED_SIZE);if(PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(o);const l=new Uint8Array(PartialSignature.SIZE);NodeNative.node_secp256k1_partial_sign(l,new Uint8Array(s),new Uint8Array(n),new Uint8Array(i),new Uint8Array(a),e.length,new Uint8Array(r),new Uint8Array(t));NodeNative.node_secp256k1_ctx_release();return l}{let c;try{c=Module.stackSave();const u=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,u,32).set(o);Module._secp256k1_ctx_init(u);const h=Module.stackAlloc(PartialSignature.SIZE),f=Module.stackAlloc(a.length),d=Module.stackAlloc(t.length),g=Module.stackAlloc(r.length),m=Module.stackAlloc(i.length),y=Module.stackAlloc(n.length),p=Module.stackAlloc(s.length);new Uint8Array(Module.HEAPU8.buffer,f,a.length).set(a);new Uint8Array(Module.HEAPU8.buffer,d,t.length).set(t);new Uint8Array(Module.HEAPU8.buffer,g,r.length).set(r);new Uint8Array(Module.HEAPU8.buffer,m,i.length).set(i);new Uint8Array(Module.HEAPU8.buffer,y,n.length).set(n);new Uint8Array(Module.HEAPU8.buffer,p,s.length).set(s);Module._secp256k1_partial_sign(h,p,s.length,y,m,f,e.length,g,d);const _=new Uint8Array(PartialSignature.SIZE);_.set(new Uint8Array(Module.HEAPU8.buffer,h,PartialSignature.SIZE));return _}catch(l){Log.w(CryptoWorkerImpl,l);throw l}finally{Module._secp256k1_ctx_release();c!==undefined&&Module.stackRestore(c)}}}}PartialSignature.HALF_SIZE=32;PartialSignature.SIZE=64;Class.register(PartialSignature);class Address extends Serializable{static copy(e){if(!e)return e;const t=new Uint8Array(e._obj);return new Address(t)}static fromHash(e){return new Address(e.subarray(-Address.SERIALIZED_SIZE))}constructor(e){super();if(!(e instanceof Uint8Array))throw new Error("Primitive: Invalid type");if(e.length!==Address.SERIALIZED_SIZE)throw new Error("Primitive: Invalid length");this._obj=e}static unserialize(e){return new Address(e.read(Address.SERIALIZED_SIZE))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).write(this._obj);return e}subarray(e,t){return this._obj.subarray(e,t)}get serializedSize(){return Address.SERIALIZED_SIZE}equals(e){return e instanceof Address&&super.equals(e)}static fromAny(e){if(e instanceof Address)return e;if("string"==typeof e)return Address.fromString(e);throw new Error("Invalid address format")}toPlain(){return this.toUserFriendlyAddress()}static fromString(e){try{return Address.fromUserFriendlyAddress(e)}catch(t){}try{return Address.fromHex(e)}catch(t){}try{return Address.fromBase64(e)}catch(t){}throw new Error("Invalid address format")}static fromBase64(e){return new Address(BufferUtils.fromBase64(e))}static fromHex(e){return new Address(BufferUtils.fromHex(e))}static fromBech32(e){if(!this.isBech32Address(e))throw new Error("Invalid Bech32 Address");return new Address(Bech32.fromBech32(e))}static fromUserFriendlyAddress(e){return Address.fromHex(e)}toBech32(){return Bech32.toBech32(this.serialize())}toUserFriendlyAddress(e=!0){return this.toHex()}static isBech32Address(e){return Bech32.isBech32Address(e)}}Address.SERIALIZED_SIZE=20;Address.HEX_SIZE=40;Address.NULL=new Address(new Uint8Array(Address.SERIALIZED_SIZE));Address.CONTRACT_CREATION=new Address(new Uint8Array(Address.SERIALIZED_SIZE));Class.register(Address);class Bech32{static polymod(e){let t=1;for(let r=0;r<e.length;++r){const i=t>>25;t=(33554431&t)<<5^e[r];for(let e=0;e<5;++e)i>>e&1&&(t^=Bech32.GENERATOR[e])}return t}static hrpExpand(e){const t=[];let r;for(r=0;r<e.length;++r)t.push(e.charCodeAt(r)>>5);t.push(0);for(r=0;r<e.length;++r)t.push(31&e.charCodeAt(r));return SerialBuffer.from(t)}static verifyChecksum(e,t){return Bech32.polymod(SerialBuffer.concat([Bech32.hrpExpand(e),t]))===Bech32.ENCODING}static createChecksum(e,t){const r=SerialBuffer.concat([Bech32.hrpExpand(e),t,SerialBuffer.from([0,0,0,0,0,0])]),i=Bech32.polymod(r)^Bech32.ENCODING,n=[];for(let s=0;s<6;++s)n.push(i>>5*(5-s)&31);return SerialBuffer.from(n)}static bech32Encode(e,t){const r=SerialBuffer.concat([t,Bech32.createChecksum(e,t)]);let i=e+"1";for(let n=0;n<r.length;++n)i+=Bech32.CHARSET.charAt(r[n]);return i}static bech32Decode(e){let t,r=!1,i=!1;for(t=0;t<e.length;++t){if(e.charCodeAt(t)<33||e.charCodeAt(t)>126)return null;e.charCodeAt(t)>=97&&e.charCodeAt(t)<=122&&(r=!0);e.charCodeAt(t)>=65&&e.charCodeAt(t)<=90&&(i=!0)}if(r&&i)return null;const n=(e=e.toLowerCase()).lastIndexOf("1");if(n<1||n+7>e.length||e.length>90)return null;const s=e.substring(0,n),o=[];for(t=n+1;t<e.length;++t){const r=Bech32.CHARSET.indexOf(e.charAt(t));if(-1===r)return null;o.push(r)}return Bech32.verifyChecksum(s,SerialBuffer.from(o))?{hrp:s,data:SerialBuffer.from(o.slice(0,o.length-6))}:null}static convertBits(e,t,r,i=!0){let n=0,s=0;const o=[],a=(1<<r)-1;for(let l=0;l<e.length;++l){const i=e[l];if(i<0||i>>t!=0)return null;n=n<<t|i;s+=t;for(;s>=r;){s-=r;o.push(n>>s&a)}}if(i)s>0&&o.push(n<<r-s&a);else if(s>=t||n<<r-s&a)return null;return SerialBuffer.from(o)}static toBech32(e,t=Bech32.HRP){const r=Bech32.convertBits(SerialBuffer.from(e),8,5);if(null===r)throw new Error("Could not convert byte Buffer to 5-bit Buffer");return Bech32.bech32Encode(t,SerialBuffer.concat([SerialBuffer.from([0]),r]))}static fromBech32(e,t=Bech32.HRP){const r=Bech32.bech32Decode(e);if(null===r)throw new Error("Invalid bech32 address");const{hrp:i,data:n}=r;if(i!==t)throw new Error(`Expected hrp to be ${t} but got ${i}`);const s=Bech32.convertBits(n.slice(1),5,8,!1);if(null===s)throw new Error("Could not convert buffer to bytes");return new SerialBuffer(s)}static isBech32Address(e){return!!e.match(/^bc1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{39}/)}}Bech32.ENCODING=1;Bech32.HRP="bc";Bech32.CHARSET="qpzry9x8gf2tvdw0s3jn54khce6mua7l";Bech32.GENERATOR=[996825010,642813549,513874426,1027748829,705979059];Class.register(Bech32);class Account{constructor(e,r){const i=new t(r);if(!NumberUtils.isUint8(e))throw new Error("Malformed type");if(!NumberUtils.isUint128(i))throw new Error("Malformed balance");this._type=e;this._balance=i}static unserialize(e){const t=e.readUint8();e.readPos--;if(!Account.TYPE_MAP.has(t))throw new Error("Unknown account type");return Account.TYPE_MAP.get(t).unserialize(e)}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).writeUint8(this._type);e.writeUint128(this._balance);return e}get serializedSize(){return 17}equals(e){return BufferUtils.equals(this.serialize(),e.serialize())}toString(){return`Account{type=${this._type}, balance=${this._balance.toString()}`}static fromAny(e){return e instanceof Account?e:Account.fromPlain(e)}static fromPlain(e){if(!e||e.type===undefined)throw new Error("Invalid account");const t=Account.Type.fromAny(e.type);return Account.TYPE_MAP.get(t).fromPlain(e)}toPlain(){return{type:Account.Type.toString(this.type),balance:this.balance.toString()}}get balance(){return this._balance}get type(){return this._type}withBalance(e){throw new Error("Not yet implemented.")}withOutgoingTransaction(e,t,r,i=!1){if(i){if(t<e.validityStartHeight||t>=e.validityStartHeight+Policy.TRANSACTION_VALIDITY_WINDOW)throw new Account.ValidityError;return this.withBalance(this._balance.plus(e.value).plus(e.fee))}{const i=this._balance.minus(e.value).minus(e.fee);if(i.lt(0))throw new Account.BalanceError;if(t<e.validityStartHeight||t>=e.validityStartHeight+Policy.TRANSACTION_VALIDITY_WINDOW)throw new Account.ValidityError;if(r.containsTransaction(e))throw new Account.DoubleTransactionError;return this.withBalance(i)}}withIncomingTransaction(e,t,r=!1){if(r){const t=this._balance.minus(e.value);if(t.lt(0))throw new Account.BalanceError;return this.withBalance(t)}return this.withBalance(this._balance.plus(e.value))}withContractCommand(e,t,r=!1){throw new Error("Not yet implemented")}isInitial(){return this===Account.INITIAL}isToBePruned(){return this._balance.eq(0)&&!this.isInitial()}static dataToPlain(e){return{}}static proofToPlain(e){return{}}}Account.Type={BASIC:0,VESTING:1,HTLC:2};Account.Type.toString=function(e){switch(e){case Account.Type.BASIC:return"basic";case Account.Type.VESTING:return"vesting";case Account.Type.HTLC:return"htlc"}throw new Error("Invalid account type")};Account.Type.fromAny=function(e){if("number"==typeof e)return e;switch(e){case"basic":return Account.Type.BASIC;case"vesting":return Account.Type.VESTING;case"htlc":return Account.Type.HTLC}throw new Error("Invalid account type")};Account.TYPE_MAP=new Map;Account.BalanceError=class extends Error{constructor(){super("Balance Error!")}};Account.DoubleTransactionError=class extends Error{constructor(){super("Double Transaction Error!")}};Account.ProofError=class extends Error{constructor(){super("Proof Error!")}};Account.ValidityError=class extends Error{constructor(){super("Validity Error!")}};Class.register(Account);class BasicAccount extends Account{static copy(e){return e?new BasicAccount(e._balance):e}constructor(e=0){super(Account.Type.BASIC,e)}static unserialize(e){if(e.readUint8()!==Account.Type.BASIC)throw new Error("Invalid account type");const t=e.readUint128();return new BasicAccount(t)}static fromPlain(e){if(!e)throw new Error("Invalid account");return new BasicAccount(e.balance)}equals(e){return e instanceof BasicAccount&&this._type===e._type&&this._balance.eq(e._balance)}toString(){return`BasicAccount{balance=${this._balance.toString()}}`}static verifyOutgoingTransaction(e){return SignatureProof.verifyTransaction(e)}static verifyIncomingTransaction(e){return!(e.data.byteLength>64)}withBalance(e){return new BasicAccount(e)}withIncomingTransaction(e,t,r=!1){if(!r){if(e.hasFlag(Transaction.Flag.CONTRACT_CREATION)!==(e.recipientType!==this._type))throw new Error("Data Error!")}return super.withIncomingTransaction(e,t,r)}withContractCommand(e,t,r=!1){return!r&&e.recipientType!==this._type&&e.hasFlag(Transaction.Flag.CONTRACT_CREATION)?Account.TYPE_MAP.get(e.recipientType).create(this._balance,t,e):this}isInitial(){return this._balance&&this._balance.eq(0)}static dataToPlain(e){return Account.dataToPlain(e)}static proofToPlain(e){try{const r=SignatureProof.unserialize(new SerialBuffer(e));return{signature:r.signature.toHex(),publicKey:r.publicKey.toHex(),signer:r.publicKey.toAddress().toPlain(),pathLength:r.merklePath.nodes.length}}catch(t){return Account.proofToPlain(e)}}}Account.INITIAL=new BasicAccount(0);Account.TYPE_MAP.set(Account.Type.BASIC,BasicAccount);Class.register(BasicAccount);class Contract extends Account{constructor(e,t){super(e,t)}static verifyIncomingTransaction(e){return!!e.recipient.equals(e.getContractCreationAddress())}withIncomingTransaction(e,t,r=!1){if(!r&&e.hasFlag(Transaction.Flag.CONTRACT_CREATION))throw new Error("Data error");return super.withIncomingTransaction(e,t,r)}withContractCommand(e,t,r=!1){return r&&e.hasFlag(Transaction.Flag.CONTRACT_CREATION)?new BasicAccount(this.balance):this}}Class.register(Contract);class HashedTimeLockedContract extends Contract{constructor(e=0,r=Address.NULL,i=Address.NULL,n=Hash.NULL,s=1,o=0,a=e){super(Account.Type.HTLC,e);const l=new t(a);if(!(r instanceof Address))throw new Error("Malformed sender address");if(!(i instanceof Address))throw new Error("Malformed recipient address");if(!(n instanceof Hash))throw new Error("Malformed hashRoot");if(!NumberUtils.isUint8(s)||0===s)throw new Error("Malformed hashCount");if(!NumberUtils.isUint32(o))throw new Error("Malformed timeout");if(!NumberUtils.isUint128(l))throw new Error("Malformed totalAmount");this._sender=r;this._recipient=i;this._hashRoot=n;this._hashCount=s;this._timeout=o;this._totalAmount=l}static create(e,t,r){const i=new SerialBuffer(r.data),n=Address.unserialize(i),s=Address.unserialize(i),o=i.readUint8(),a=Hash.unserialize(i,o),l=i.readUint8(),c=i.readUint32();return new HashedTimeLockedContract(e,n,s,a,l,c)}static unserialize(e){if(e.readUint8()!==Account.Type.HTLC)throw new Error("Invalid account type");const t=e.readUint128(),r=Address.unserialize(e),i=Address.unserialize(e),n=e.readUint8(),s=Hash.unserialize(e,n),o=e.readUint8(),a=e.readUint32(),l=e.readUint128();return new HashedTimeLockedContract(t,r,i,s,o,a,l)}static fromPlain(e){if(!e)throw new Error("Invalid account");return new HashedTimeLockedContract(e.balance,Address.fromAny(e.sender),Address.fromAny(e.recipient),Hash.fromAny(e.hashRoot,Hash.Algorithm.fromAny(e.hashAlgorithm)),e.hashCount,e.timeout,e.totalAmount)}serialize(e){e=e||new SerialBuffer(this.serializedSize);super.serialize(e);this._sender.serialize(e);this._recipient.serialize(e);e.writeUint8(this._hashRoot.algorithm);this._hashRoot.serialize(e);e.writeUint8(this._hashCount);e.writeUint32(this._timeout);e.writeUint128(this._totalAmount);return e}get serializedSize(){return super.serializedSize+this._sender.serializedSize+this._recipient.serializedSize+1+this._hashRoot.serializedSize+1+4+16}get sender(){return this._sender}get recipient(){return this._recipient}get hashAlgorithm(){return this._hashRoot.algorithm}get hashRoot(){return this._hashRoot}get hashCount(){return this._hashCount}get timeout(){return this._timeout}get totalAmount(){return this._totalAmount}toString(){return`HashedTimeLockedContract{balance=${this._balance.toString()}, sender=${this._sender.toUserFriendlyAddress(!1)}, recipient=${this._sender.toUserFriendlyAddress(!1)}, amount=${this._totalAmount.toString()}/${this._hashCount}, timeout=${this._timeout}}`}toPlain(){const e=super.toPlain();e.sender=this.sender.toPlain();e.recipient=this.recipient.toPlain();e.hashAlgorithm=Hash.Algorithm.toString(this.hashRoot.algorithm);e.hashRoot=this.hashRoot.toPlain();e.hashCount=this.hashCount;e.timeout=this.timeout;e.totalAmount=this.totalAmount.toString();return e}equals(e){return e instanceof HashedTimeLockedContract&&this._type===e._type&&this._balance.eq(e._balance)&&this._sender.equals(e._sender)&&this._recipient.equals(e._recipient)&&this._hashRoot.equals(e._hashRoot)&&this._hashCount===e._hashCount&&this._timeout===e._timeout&&this._totalAmount.eq(e._totalAmount)}static verifyOutgoingTransaction(e){try{const r=new SerialBuffer(e.proof);switch(r.readUint8()){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{const t=r.readUint8(),i=r.readUint8(),n=Hash.unserialize(r,t);let s=Hash.unserialize(r,t);for(let e=0;e<i;++e)s=Hash.compute(s.array,t);if(!n.equals(s))return!1;if(!SignatureProof.unserialize(r).verify(null,e.serializeContent()))return!1;break}case HashedTimeLockedContract.ProofType.EARLY_RESOLVE:if(!SignatureProof.unserialize(r).verify(null,e.serializeContent()))return!1;if(!SignatureProof.unserialize(r).verify(null,e.serializeContent()))return!1;break;case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:if(!SignatureProof.unserialize(r).verify(null,e.serializeContent()))return!1;break;default:return!1}return r.readPos===r.byteLength}catch(t){return!1}}static verifyIncomingTransaction(e){try{const r=new SerialBuffer(e.data);Address.unserialize(r);Address.unserialize(r);const i=r.readUint8();Hash.unserialize(r,i);const n=r.readUint8();r.readUint32();return 0!==n&&(i!==Hash.Algorithm.ARGON2D&&(r.readPos===r.byteLength&&Contract.verifyIncomingTransaction(e)))}catch(t){return!1}}withBalance(e){return new HashedTimeLockedContract(e,this._sender,this._recipient,this._hashRoot,this._hashCount,this._timeout,this._totalAmount)}withOutgoingTransaction(e,r,i,n=!1){const s=new SerialBuffer(e.proof);let o=0;switch(s.readUint8()){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{if(this._timeout<r)throw new Account.ProofError;const e=s.readUint8(),i=s.readUint8();if(!Hash.unserialize(s,e).equals(this._hashRoot))throw new Account.ProofError;Hash.unserialize(s,e);if(!SignatureProof.unserialize(s).isSignedBy(this._recipient))throw new Account.ProofError;o=t.max(0,this._totalAmount.times(1-i/this._hashCount).idiv(1));break}case HashedTimeLockedContract.ProofType.EARLY_RESOLVE:if(!SignatureProof.unserialize(s).isSignedBy(this._recipient))throw new Account.ProofError;if(!SignatureProof.unserialize(s).isSignedBy(this._sender))throw new Account.ProofError;break;case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:if(this._timeout>=r)throw new Account.ProofError;if(!SignatureProof.unserialize(s).isSignedBy(this._sender))throw new Account.ProofError;break;default:throw new Account.ProofError}if(!n){if(this._balance.minus(e.value).minus(e.fee).lt(o))throw new Account.BalanceError}return super.withOutgoingTransaction(e,r,i,n)}withIncomingTransaction(e,t,r=!1){throw new Error("Illegal incoming transaction")}static dataToPlain(e){try{const r=new SerialBuffer(e),i=Address.unserialize(r),n=Address.unserialize(r),s=r.readUint8(),o=Hash.unserialize(r,s),a=r.readUint8(),l=r.readUint32();return{sender:i.toPlain(),recipient:n.toPlain(),hashAlgorithm:Hash.Algorithm.toString(s),hashRoot:o.toPlain(),hashCount:a,timeout:l}}catch(t){return Account.dataToPlain(e)}}static proofToPlain(e){try{const r=new SerialBuffer(e),i=r.readUint8();switch(i){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{const e=r.readUint8(),t=r.readUint8(),n=Hash.unserialize(r,e),s=Hash.unserialize(r,e),o=SignatureProof.unserialize(r);return{type:HashedTimeLockedContract.ProofType.toString(i),hashAlgorithm:Hash.Algorithm.toString(e),hashDepth:t,hashRoot:n.toPlain(),preImage:s.toPlain(),signer:o.publicKey.toAddress().toPlain(),signature:o.signature.toHex(),publicKey:o.publicKey.toHex(),pathLength:o.merklePath.nodes.length}}case HashedTimeLockedContract.ProofType.EARLY_RESOLVE:{const e=SignatureProof.unserialize(r),t=SignatureProof.unserialize(r);return{type:HashedTimeLockedContract.ProofType.toString(i),signer:e.publicKey.toAddress().toPlain(),signature:e.signature.toHex(),publicKey:e.publicKey.toHex(),pathLength:e.merklePath.nodes.length,creator:t.publicKey.toAddress().toPlain(),creatorSignature:t.signature.toHex(),creatorPublicKey:t.publicKey.toHex(),creatorPathLength:t.merklePath.nodes.length}}case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:{const e=SignatureProof.unserialize(r);return{type:HashedTimeLockedContract.ProofType.toString(i),creator:e.publicKey.toAddress().toPlain(),creatorSignature:e.signature.toHex(),creatorPublicKey:e.publicKey.toHex(),creatorPathLength:e.merklePath.nodes.length}}default:return!1}}catch(t){return Account.proofToPlain(e)}}}HashedTimeLockedContract.ProofType={REGULAR_TRANSFER:1,EARLY_RESOLVE:2,TIMEOUT_RESOLVE:3};HashedTimeLockedContract.ProofType.toString=function(e){switch(e){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:return"regular-transfer";case HashedTimeLockedContract.ProofType.EARLY_RESOLVE:return"early-resolve";case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:return"timeout-resolve"}throw new Error("Invalid proof type")};Account.TYPE_MAP.set(Account.Type.HTLC,HashedTimeLockedContract);Class.register(HashedTimeLockedContract);class VestingContract extends Contract{constructor(e=0,r=Address.NULL,i=0,n=0,s=e,o=e){super(Account.Type.VESTING,e);const a=new t(s),l=new t(o);if(!(r instanceof Address))throw new Error("Malformed owner address");if(!NumberUtils.isUint32(i))throw new Error("Malformed vestingStart");if(!NumberUtils.isUint32(n))throw new Error("Malformed vestingStepBlocks");if(!NumberUtils.isUint128(a))throw new Error("Malformed vestingStepAmount");if(!NumberUtils.isUint128(l))throw new Error("Malformed vestingTotalAmount");this._owner=r;this._vestingStart=i;this._vestingStepBlocks=n;this._vestingStepAmount=a;this._vestingTotalAmount=l}static create(e,t,r){let i,n,s,o;const a=new SerialBuffer(r.data),l=Address.unserialize(a);o=r.value;switch(r.data.length){case Address.SERIALIZED_SIZE+4:i=0;n=a.readUint32();s=o;break;case Address.SERIALIZED_SIZE+24:i=a.readUint32();n=a.readUint32();s=a.readUint128();break;case Address.SERIALIZED_SIZE+40:i=a.readUint32();n=a.readUint32();s=a.readUint128();o=a.readUint128();break;default:throw new Error("Invalid transaction data")}return new VestingContract(e,l,i,n,s,o)}static unserialize(e){if(e.readUint8()!==Account.Type.VESTING)throw new Error("Invalid account type");const t=e.readUint128(),r=Address.unserialize(e),i=e.readUint32(),n=e.readUint32(),s=e.readUint128(),o=e.readUint128();return new VestingContract(t,r,i,n,s,o)}static fromPlain(e){if(!e)throw new Error("Invalid account");return new VestingContract(e.balance,Address.fromAny(e.owner),e.vestingStart,e.vestingStepBlocks,e.vestingStepAmount,e.vestingTotalAmount)}serialize(e){e=e||new SerialBuffer(this.serializedSize);super.serialize(e);this._owner.serialize(e);e.writeUint32(this._vestingStart);e.writeUint32(this._vestingStepBlocks);e.writeUint128(this._vestingStepAmount);e.writeUint128(this._vestingTotalAmount);return e}get serializedSize(){return super.serializedSize+this._owner.serializedSize+4+4+16+16}get owner(){return this._owner}get vestingStart(){return this._vestingStart}get vestingStepBlocks(){return this._vestingStepBlocks}get vestingStepAmount(){return this._vestingStepAmount}get vestingTotalAmount(){return this._vestingTotalAmount}toString(){return`VestingAccount{balance=${this._balance.toString()}, owner=${this._owner.toUserFriendlyAddress()}`}toPlain(){const e=super.toPlain();e.owner=this.owner.toPlain();e.vestingStart=this.vestingStart;e.vestingStepBlocks=this.vestingStepBlocks;e.vestingStepAmount=this.vestingStepAmount.toString();e.vestingTotalAmount=this.vestingTotalAmount.toString();return e}equals(e){return e instanceof VestingContract&&this._type===e._type&&this._balance.eq(e._balance)&&this._owner.equals(e._owner)&&this._vestingStart===e._vestingStart&&this._vestingStepBlocks===e._vestingStepBlocks&&this._vestingStepAmount.eq(e._vestingStepAmount)&&this._vestingTotalAmount.eq(e._vestingTotalAmount)}static verifyOutgoingTransaction(e){const t=new SerialBuffer(e.proof);return!!SignatureProof.unserialize(t).verify(null,e.serializeContent())&&t.readPos===t.byteLength}static verifyIncomingTransaction(e){switch(e.data.length){case Address.SERIALIZED_SIZE+4:case Address.SERIALIZED_SIZE+24:case Address.SERIALIZED_SIZE+40:return Contract.verifyIncomingTransaction(e);default:return!1}}withBalance(e){return new VestingContract(e,this._owner,this._vestingStart,this._vestingStepBlocks,this._vestingStepAmount,this._vestingTotalAmount)}withOutgoingTransaction(e,t,r,i=!1){if(!i){const r=this.getMinCap(t);if(this._balance.minus(e.value).minus(e.fee).lt(r))throw new Account.BalanceError;const i=new SerialBuffer(e.proof);if(!SignatureProof.unserialize(i).isSignedBy(this._owner))throw new Account.ProofError}return super.withOutgoingTransaction(e,t,r,i)}withIncomingTransaction(e,t,r=!1){throw new Error("Illegal incoming transaction")}getMinCap(e){return this._vestingStepBlocks&&this._vestingStepAmount.gt(0)?t.max(0,this._vestingTotalAmount.minus(this._vestingStepAmount.times(Math.floor((e-this._vestingStart)/this._vestingStepBlocks)))):new t(0)}static dataToPlain(e){try{let r,i,n,s;const o=new SerialBuffer(e),a=Address.unserialize(o);switch(e.length){case Address.SERIALIZED_SIZE+4:r=0;i=o.readUint32();break;case Address.SERIALIZED_SIZE+24:r=o.readUint32();i=o.readUint32();n=o.readUint128().toString();break;case Address.SERIALIZED_SIZE+40:r=o.readUint32();i=o.readUint32();n=o.readUint128().toString();s=o.readUint128().toString();break;default:throw new Error("Invalid transaction data")}return{owner:a.toPlain(),vestingStart:r,vestingStepBlocks:i,vestingStepAmount:n,vestingTotalAmount:s}}catch(t){return Account.dataToPlain(e)}}static proofToPlain(e){try{const r=SignatureProof.unserialize(new SerialBuffer(e));return{signature:r.signature.toHex(),publicKey:r.publicKey.toHex(),signer:r.publicKey.toAddress().toPlain(),pathLength:r.merklePath.nodes.length}}catch(t){return Account.proofToPlain(e)}}}Account.TYPE_MAP.set(Account.Type.VESTING,VestingContract);Class.register(VestingContract);class Transaction{constructor(e,r,i,n,s,o,a,l,c,u,h=GenesisConfig.NETWORK_ID){const f=new t(o);if(!(r instanceof Address))throw new Error("Malformed sender");if(!NumberUtils.isUint8(i))throw new Error("Malformed sender type");if(!(n instanceof Address))throw new Error("Malformed recipient");if(!NumberUtils.isUint8(s))throw new Error("Malformed recipient type");if(!NumberUtils.isUint128(f)||f.eq(0))throw new Error("Malformed value");if(!NumberUtils.isUint32(a))throw new Error("Malformed validityStartHeight");if(!NumberUtils.isUint8(l)&&(l&~Transaction.Flag.ALL)>0)throw new Error("Malformed flags");if(!(c instanceof Uint8Array&&NumberUtils.isUint16(c.byteLength)))throw new Error("Malformed data");if(u&&(!(u instanceof Uint8Array)||!NumberUtils.isUint16(u.byteLength)))throw new Error("Malformed proof");if(!NumberUtils.isUint8(h))throw new Error("Malformed networkId");this._format=e;this._sender=r;this._senderType=i;this._recipient=n;this._recipientType=s;this._value=f;this._fee=Policy.txFee(a);this._networkId=h;this._validityStartHeight=a;this._flags=l;this._data=c;this._proof=u;this._recipient===Address.CONTRACT_CREATION&&(this._recipient=this.getContractCreationAddress())}static unserialize(e){const t=e.readUint8();e.readPos--;if(!Transaction.FORMAT_MAP.has(t))throw new Error("Invalid transaction type");return Transaction.FORMAT_MAP.get(t).unserialize(e)}serializeContent(e){(e=e||new SerialBuffer(this.serializedContentSize)).writeUint16(this._data.byteLength);e.write(this._data);this._sender.serialize(e);e.writeUint8(this._senderType);this._recipient.serialize(e);e.writeUint8(this._recipientType);e.writeUint128(this._value);e.writeUint128(this._fee);e.writeUint32(this._validityStartHeight);e.writeUint8(this._networkId);e.writeUint8(this._flags);return e}get serializedContentSize(){return 2+this._data.byteLength+this._sender.serializedSize+1+this._recipient.serializedSize+1+16+16+4+1+1}verify(e){this._valid===undefined&&(this._valid=this._verify(e));return this._valid}_verify(e=GenesisConfig.NETWORK_ID){if(this._networkId!==e){Log.w(Transaction,"Transaction is not valid in this network",this);return!1}if(this._recipient.equals(this._sender)){Log.w(Transaction,"Sender and recipient must not match",this);return!1}if(!Account.TYPE_MAP.has(this._senderType)||!Account.TYPE_MAP.has(this._recipientType)){Log.w(Transaction,"Invalid account type",this);return!1}if(!Account.TYPE_MAP.get(this._senderType).verifyOutgoingTransaction(this)){Log.w(Transaction,"Invalid for sender",this);return!1}if(!Account.TYPE_MAP.get(this._recipientType).verifyIncomingTransaction(this)){Log.w(Transaction,"Invalid for recipient",this);return!1}if(!this._fee.eq(Policy.txFee(this._validityStartHeight))){Log.w(Transaction,"Invalid for tx fee",this);return!1}return!0}get serializedSize(){throw new Error("Getter needs to be overwritten by subclasses")}serialize(e){throw new Error("Method needs to be overwritten by subclasses")}hash(){this._hash=this._hash||Hash.light(this.serializeContent());return this._hash}compare(e){return this.fee.div(this.serializedSize).gt(e.fee.div(e.serializedSize))?-1:this.fee.div(this.serializedSize).lt(e.fee.div(e.serializedSize))?1:this.serializedSize>e.serializedSize?-1:this.serializedSize<e.serializedSize?1:this.fee.gt(e.fee)?-1:this.fee.lt(e.fee)?1:this.value.gt(e.value)?-1:this.value.lt(e.value)?1:this.compareBlockOrder(e)}compareBlockOrder(e){const t=this._recipient.compare(e._recipient);if(0!==t)return t;if(this._validityStartHeight<e._validityStartHeight)return-1;if(this._validityStartHeight>e._validityStartHeight)return 1;if(this._fee.gt(e._fee))return-1;if(this._fee.lt(e._fee))return 1;if(this._value.gt(e._value))return-1;if(this._value.lt(e._value))return 1;const r=this._sender.compare(e._sender);return 0!==r?r:this._recipientType<e._recipientType?-1:this._recipientType>e._recipientType?1:this._senderType<e._senderType?-1:this._senderType>e._senderType?1:this._flags<e._flags?-1:this._flags>e._flags?1:BufferUtils.compare(this._data,e._data)}equals(e){return e instanceof Transaction&&this._sender.equals(e._sender)&&this._senderType===e._senderType&&this._recipient.equals(e._recipient)&&this._recipientType===e._recipientType&&this._value.eq(e._value)&&this._fee.eq(e._fee)&&this._validityStartHeight===e._validityStartHeight&&this._networkId===e._networkId&&this._flags===e._flags&&BufferUtils.equals(this._data,e._data)}toString(){return"Transaction{"+`sender=${this._sender.toHex()}, `+`recipient=${this._recipient.toHex()}, `+`value=${this._value.toString()}, `+`fee=${this._fee.toString()}, `+`validityStartHeight=${this._validityStartHeight}, `+`networkId=${this._networkId}`+"}"}toPlain(){const e=Account.TYPE_MAP.get(this.recipientType).dataToPlain(this.data);e.raw=BufferUtils.toHex(this.data);const t=Account.TYPE_MAP.get(this.senderType).proofToPlain(this.proof);t.raw=BufferUtils.toHex(this.proof);return{transactionHash:this.hash().toPlain(),format:Transaction.Format.toString(this._format),sender:this.sender.toPlain(),senderType:Account.Type.toString(this.senderType),recipient:this.recipient.toPlain(),recipientType:Account.Type.toString(this.recipientType),value:this.value.toString(),fee:this.fee.toString(),feePerByte:this.feePerByte.toString(),validityStartHeight:this.validityStartHeight,network:GenesisConfig.networkIdToNetworkName(this.networkId),flags:this.flags,data:e,proof:t,size:this.serializedSize,valid:this.verify()}}static fromPlain(e){if(!e)throw new Error("Invalid transaction format");const t=Transaction.Format.fromAny(e.format);if(!Transaction.FORMAT_MAP.has(t))throw new Error("Invalid transaction type");return Transaction.FORMAT_MAP.get(t).fromPlain(e)}static fromAny(e){if(e instanceof Transaction)return e;if("object"==typeof e)return Transaction.fromPlain(e);if("string"==typeof e)return Transaction.unserialize(new SerialBuffer(BufferUtils.fromHex(e)));throw new Error("Invalid transaction format")}getContractCreationAddress(){const e=Transaction.unserialize(this.serialize());e._recipient=Address.NULL;e._hash=null;return Address.fromHash(e.hash())}get format(){return this._format}get sender(){return this._sender}get senderType(){return this._senderType}get recipient(){return this._recipient}get recipientType(){return this._recipientType}get value(){return this._value}get fee(){return this._fee}get feePerByte(){return this._fee.div(this.serializedSize)}get networkId(){return this._networkId}get validityStartHeight(){return this._validityStartHeight}get flags(){return this._flags}hasFlag(e){return(this._flags&e)>0}get data(){return this._data}get proof(){return this._proof}set proof(e){this._proof=e}}Transaction.Format={BASIC:0,EXTENDED:1};Transaction.Format.toString=function(e){switch(e){case Transaction.Format.BASIC:return"basic";case Transaction.Format.EXTENDED:return"extended"}throw new Error("Invalid transaction format")};Transaction.Format.fromAny=function(e){if("number"==typeof e)return e;switch(e){case"basic":return Transaction.Format.BASIC;case"extended":return Transaction.Format.EXTENDED}throw new Error("Invalid transaction format")};Transaction.Flag={NONE:0,CONTRACT_CREATION:1,ALL:1};Transaction.FORMAT_MAP=new Map;Class.register(Transaction);class SignatureProof{static verifyTransaction(e){try{const r=new SerialBuffer(e.proof),i=SignatureProof.unserialize(r);if(r.readPos!==r.byteLength){Log.w(SignatureProof,"Invalid SignatureProof - overlong");return!1}return i.verify(e.sender,e.serializeContent())}catch(t){Log.w(SignatureProof,`Failed to verify transaction: ${t.message||t}`);return!1}}static singleSig(e,t){return new SignatureProof(e,new MerklePath([]),t)}static multiSig(e,t,r){const i=MerklePath.compute(t,e);return new SignatureProof(e,i,r)}constructor(e,t,r){if(!(e instanceof PublicKey))throw new Error("Malformed publickKey");if(!(t instanceof MerklePath))throw new Error("Malformed merklePath");if(r&&!(r instanceof Signature))throw new Error("Malformed signature");this._publicKey=e;this._merklePath=t;this._signature=r}static unserialize(e){const t=PublicKey.unserialize(e),r=MerklePath.unserialize(e),i=Signature.unserialize(e);return new SignatureProof(t,r,i)}serialize(e){e=e||new SerialBuffer(this.serializedSize);this._publicKey.serialize(e);this._merklePath.serialize(e);this._signature&&this._signature.serialize(e);return e}get serializedSize(){return this._publicKey.serializedSize+this._merklePath.serializedSize+(this._signature?this._signature.serializedSize:0)}static get SINGLE_SIG_SIZE(){return PublicKey.SIZE+new MerklePath([]).serializedSize+Signature.SIZE}equals(e){return e instanceof SignatureProof&&this._publicKey.equals(e._publicKey)&&this._merklePath.equals(e._merklePath)&&(this._signature?this._signature.equals(e._signature):this._signature===e._signature)}verify(e,t){if(null!==e&&!this.isSignedBy(e)){Log.w(SignatureProof,"Invalid SignatureProof - signer does not match sender address");return!1}if(!this._signature){Log.w(SignatureProof,"Invalid SignatureProof - signature is missing");return!1}if(!this._signature.verify(this._publicKey,t)){Log.w(SignatureProof,"Invalid SignatureProof - signature is invalid");return!1}return!0}isSignedBy(e){const t=this._merklePath.computeRoot(this._publicKey);return Address.fromHash(t).equals(e)}get publicKey(){return this._publicKey}get merklePath(){return this._merklePath}get signature(){return this._signature}set signature(e){this._signature=e}}Class.register(SignatureProof);class BasicTransaction extends Transaction{constructor(e,t,r,i,n,s){if(!(e instanceof PublicKey))throw new Error("Malformed senderPubKey");if(n!==undefined&&!(n instanceof Signature))throw new Error("Malformed signature");const o=SignatureProof.singleSig(e,n);super(Transaction.Format.BASIC,e.toAddress(),Account.Type.BASIC,t,Account.Type.BASIC,r,i,Transaction.Flag.NONE,new Uint8Array(0),o.serialize(),s);this._signatureProof=o}static unserialize(e){const t=e.readUint8();Assert.that(t===Transaction.Format.BASIC);const r=PublicKey.unserialize(e),i=Address.unserialize(e),n=e.readUint128(),s=(e.readUint128(),e.readUint32()),o=e.readUint8(),a=Signature.unserialize(e);return new BasicTransaction(r,i,n,s,a,o)}static fromPlain(e){if(!e)throw new Error("Invalid transaction format");return new BasicTransaction(PublicKey.fromAny(e.proof.publicKey||e.senderPubKey),Address.fromAny(e.recipient),e.value,e.validityStartHeight,Signature.fromAny(e.proof.signature||e.signature),GenesisConfig.networkIdFromAny(e.network||e.networkId))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).writeUint8(Transaction.Format.BASIC);this.senderPubKey.serialize(e);this._recipient.serialize(e);e.writeUint128(this._value);e.writeUint128(this._fee);e.writeUint32(this._validityStartHeight);e.writeUint8(this._networkId);this.signature.serialize(e);return e}get serializedSize(){return 1+this.senderPubKey.serializedSize+this._recipient.serializedSize+16+16+4+1+this.signature.serializedSize}get senderPubKey(){return this._signatureProof.publicKey}get signature(){return this._signatureProof.signature}set signature(e){this._signatureProof.signature=e;this._proof=this._signatureProof.serialize()}}Transaction.FORMAT_MAP.set(Transaction.Format.BASIC,BasicTransaction);Class.register(BasicTransaction);class ExtendedTransaction extends Transaction{constructor(e,t,r,i,n,s,o,a,l=new Uint8Array(0),c){super(Transaction.Format.EXTENDED,e,t,r,i,n,s,o,a,l,c)}static unserialize(e){const t=e.readUint8();Assert.that(t===Transaction.Format.EXTENDED);const r=e.readUint16(),i=e.read(r),n=Address.unserialize(e),s=e.readUint8(),o=Address.unserialize(e),a=e.readUint8(),l=e.readUint128(),c=(e.readUint128(),e.readUint32()),u=e.readUint8(),h=e.readUint8(),f=e.readUint16(),d=e.read(f);return new ExtendedTransaction(n,s,o,a,l,c,h,i,d,u)}static fromPlain(e){if(!e)throw new Error("Invalid transaction format");return new ExtendedTransaction(Address.fromAny(e.sender),Account.Type.fromAny(e.senderType),Address.fromAny(e.recipient),Account.Type.fromAny(e.recipientType),e.value,e.validityStartHeight,e.flags,BufferUtils.fromAny(e.data.raw===undefined?e.data:e.data.raw),BufferUtils.fromAny(e.proof.raw===undefined?e.proof:e.proof.raw),GenesisConfig.networkIdFromAny(e.network||e.networkId))}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).writeUint8(Transaction.Format.EXTENDED);this.serializeContent(e);e.writeUint16(this._proof.byteLength);e.write(this._proof);return e}get serializedSize(){return 1+this.serializedContentSize+2+this._proof.byteLength}}Transaction.FORMAT_MAP.set(Transaction.Format.EXTENDED,ExtendedTransaction);Class.register(ExtendedTransaction);class IWorker{static async createProxy(e,t,r){return new(IWorker.Proxy(e))(r,t)}static async startWorkerForProxy(e,t,r){if(IWorker._workersSupported){r||(r=`${Krypton._path}worker.js`);return IWorker.createProxy(e,t,new Worker(URL.createObjectURL(new Blob([`Krypton = {_path: '${Krypton._path}'}; importScripts('${r.replace(/'/g,"")}');`]))))}await IWorker._workerImplementation[e.name].init(t);return IWorker._workerImplementation[e.name]}static async startWorkerPoolForProxy(e,t,r,i){return new(IWorker.Pool(e))(t=>IWorker.startWorkerForProxy(e,t,i),t,r).start()}static async stubBaseOnMessage(e){try{if("init"===e.data.command)if(IWorker._workerImplementation[e.data.args[0]]){const t=await IWorker._workerImplementation[e.data.args[0]].init(e.data.args[1]);self.postMessage({status:"OK",result:t,id:e.data.id})}else self.postMessage({status:"error",result:"Unknown worker!",id:e.data.id});else self.postMessage({status:"error",result:"Worker not yet initialized!",id:e.data.id})}catch(t){self.postMessage({status:"error",result:t,id:e.data.id})}}static get _workersSupported(){return"undefined"!=typeof Worker}static get areWorkersAsync(){return IWorker._workersSupported}static get _insideWebWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}static get _global(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:null}static prepareForWorkerUse(e,t){IWorker._insideWebWorker&&(self.onmessage=IWorker.stubBaseOnMessage);IWorker._workerImplementation=IWorker._workerImplementation||{};IWorker._workerImplementation[e.name]=t}static _loadBrowserScript(e,t){const r=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript";i.src=e;const n=()=>setTimeout(t,100);i.onreadystatechange=n;i.onload=n;r.appendChild(i)}static Proxy(e){const t=class extends e{constructor(t,r){super();this._name=r;this._messageId=0;this._worker=t;this._worker.onmessage=this._receive.bind(this);this._waiting=new Map;return this._invoke("init",[e.name,r]).then(()=>this)}_receive(e){const t=this._waiting.get(e.data.id);if(t){this._waiting["delete"](e.data.id);"OK"===e.data.status?t.resolve(e.data.result):"error"===e.data.status&&t.error(e.data.result)}else Log.w(WorkerProxy,"Unknown reply",e)}_invoke(e,t=[]){return new Promise((r,i)=>{const n={command:e,args:t,id:this._messageId++};this._waiting.set(n.id,{resolve:r,error:i});this._worker.postMessage(n)})}destroy(){return this._invoke("destroy")}};for(const r of Object.getOwnPropertyNames(e.prototype))"function"==typeof e.prototype[r]&&"constructor"!==r&&(t.prototype[r]=function(...e){return this._invoke(r,e)});return t}static Stub(e){const t=class extends e{constructor(){super()}_result(e,t,r){self.postMessage({status:t,result:r,id:e.data.id})}_onmessage(e){try{const r=this._invoke(e.data.command,e.data.args);r instanceof Promise?r.then(t=>{this._result(e,"OK",t)}):this._result(e,"OK",r)}catch(t){this._result(e,"error",t.message||t)}}init(e){this._name=e;if(IWorker._insideWebWorker){self.name=e;self.onmessage=(e=>this._onmessage(e))}}_invoke(e,t){return this[e].apply(this,t)}destroy(){IWorker._insideWebWorker&&self.close()}};for(const r of Object.getOwnPropertyNames(e.prototype))"function"==typeof e.prototype[r]&&"constructor"!==r&&(t.prototype[r]=function(){throw`Not implemented in IWorker Stub: ${r}`});return t}static Pool(e){const t=class extends e{constructor(e,t="pool",r=1){super();this._proxyInitializer=e;this._name=t;this._poolSize=r;this._workers=[];this._freeWorkers=[];this._waitingCalls=[]}async start(){await this._updateToSize();return this}get poolSize(){return this._poolSize}set poolSize(e){this._poolSize=e;this._updateToSize()["catch"](Log.w.tag(IWorker))}destroy(){this._poolSize=0;return this._updateToSize()}_invoke(e,t){return IWorker._workersSupported?new Promise((r,i)=>{this._waitingCalls.push({name:e,args:t,resolve:r,error:i});const n=this._freeWorkers.shift();n&&this._step(n)["catch"](Log.w.tag(IWorker))}):this._workers[0][e].apply(this._workers[0],t)}async _step(e){let t=this._waitingCalls.shift();for(;t;){try{t.resolve(await e[t.name].apply(e,t.args))}catch(r){t.error(r)}if(-1===this._workers.indexOf(e)){e.destroy();return}t=this._waitingCalls.shift()}this._freeWorkers.push(e)}async _updateToSize(){if("undefined"==typeof Worker&&this._poolSize>1){Log.d(IWorker,"Pool of size larger than 1 requires WebWorker support.");this._poolSize=1}const e=[];for(;this._workers.length+e.length<this._poolSize;)e.push(this._proxyInitializer(`${this._name}#${this._workers.length+e.length}`));const t=await Promise.all(e);for(const r of t){this._workers.push(r);this._step(r)["catch"](Log.w.tag(IWorker))}for(;this._workers.length>this._poolSize;){const e=this._freeWorkers.shift()||this._workers.pop(),t=this._workers.indexOf(e);if(t>=0){this._workers.splice(t,1);e.destroy()}}return this}};for(const r of Object.getOwnPropertyNames(e.prototype))"function"==typeof e.prototype[r]&&"constructor"!==r&&(t.prototype[r]=function(...e){return this._invoke(r,e)});return t}}IWorker._moduleLoadedCallbacks={};IWorker._workerImplementation={};Class.register(IWorker);class CryptoWorker{static get lib(){return CryptoLib.instance}static async getInstanceAsync(){CryptoWorker._workerAsync||(CryptoWorker._workerAsync=await IWorker.startWorkerPoolForProxy(CryptoWorker,"crypto",4));return CryptoWorker._workerAsync}async computeArgon2d(e){}async computeArgon2dBatch(e){}async kdfLegacy(e,t,r,i){}async kdf(e,t,r,i){}async blockVerify(e,t,r,i,n){}}CryptoWorker._workerAsync=null;Class.register(CryptoWorker);class CryptoUtils{static computeHmacSha512(e,t){e.length>CryptoUtils.SHA512_BLOCK_SIZE&&(e=new SerialBuffer(Hash.computeSha512(e)));const r=new SerialBuffer(CryptoUtils.SHA512_BLOCK_SIZE),i=new SerialBuffer(CryptoUtils.SHA512_BLOCK_SIZE);for(let s=0;s<CryptoUtils.SHA512_BLOCK_SIZE;++s){const t=e[s]||0;r[s]=54^t;i[s]=92^t}const n=Hash.computeSha512(BufferUtils.concatTypedArrays(r,t));return Hash.computeSha512(BufferUtils.concatTypedArrays(i,n))}static computePBKDF2sha512(e,t,r,i){const n=Hash.SIZE.get(Hash.Algorithm.SHA512);if(i>(Math.pow(2,32)-1)*n)throw new Error("Derived key too long");const s=Math.ceil(i/n),o=i-(s-1)*n,a=new SerialBuffer(i);for(let l=1;l<=s;l++){let i=new SerialBuffer(t.length+4);i.write(t);i.writeUint32(l);const n=i=CryptoUtils.computeHmacSha512(e,i);for(let t=1;t<r;t++){i=CryptoUtils.computeHmacSha512(e,i);for(let e=0;e<n.length;e++)n[e]^=i[e]}l<s?a.write(n):a.write(n.slice(0,o))}return a}static async otpKdfLegacy(e,t,r,i){const n=await CryptoWorker.getInstanceAsync(),s=await n.kdfLegacy(t,r,i,e.byteLength);return BufferUtils.xor(e,s)}static async otpKdf(e,t,r,i){const n=await CryptoWorker.getInstanceAsync(),s=await n.kdf(t,r,i,e.byteLength);return BufferUtils.xor(e,s)}}CryptoUtils.SHA512_BLOCK_SIZE=128;Class.register(CryptoUtils);class GenesisConfig{static main(){GenesisConfig.init(GenesisConfig.CONFIGS.main)}static test(){GenesisConfig.init(GenesisConfig.CONFIGS.test)}static dev(){GenesisConfig.init(GenesisConfig.CONFIGS.dev)}static init(e){if(GenesisConfig._config)throw new Error("GenesisConfig already initialized");if(!e.NETWORK_ID)throw new Error("Config is missing network id");if(!e.NETWORK_NAME)throw new Error("Config is missing network name");GenesisConfig._config=e}static get NETWORK_ID(){if(!GenesisConfig._config)throw new Error("GenesisConfig not initialized");return GenesisConfig._config.NETWORK_ID}static get NETWORK_NAME(){if(!GenesisConfig._config)throw new Error("GenesisConfig not initialized");return GenesisConfig._config.NETWORK_NAME}static networkIdToNetworkName(e){for(const t of Object.keys(GenesisConfig.CONFIGS)){const r=GenesisConfig.CONFIGS[t];if(e===r.NETWORK_ID)return r.NETWORK_NAME}throw new Error(`Unable to find networkName for networkId ${e}`)}static networkIdFromAny(e){if("number"==typeof e)return e;if(GenesisConfig.CONFIGS[e])return GenesisConfig.CONFIGS[e].NETWORK_ID;throw new Error(`Unable to find networkId for ${e}`)}}Class.register(GenesisConfig);GenesisConfig.CONFIGS={main:{NETWORK_ID:12,NETWORK_NAME:"main"},test:{NETWORK_ID:1,NETWORK_NAME:"test"},dev:{NETWORK_ID:2,NETWORK_NAME:"dev"}};e._loaded=!0;"function"==typeof e._onload&&e._onload()}(Krypton);
|
2
|
+
//# sourceMappingURL=web-offline.js.map
|