@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/worker-js.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
var Module=function(){var _scriptDir=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:undefined;if(typeof __filename!=="undefined")_scriptDir=_scriptDir||__filename;return function(Module){Module=Module||{};var Module;if(!Module)Module=typeof Module!=="undefined"?Module:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=Number(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function==="function"){var typeNames={i:"i32",j:"i64",f:"f32",d:"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i<sig.length;++i){type.parameters.push(typeNames[sig[i]])}return new WebAssembly.Function(type,func)}var typeSection=[1,0,1,96];var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={i:127,j:126,f:125,d:124};typeSection.push(sigParam.length);for(var i=0;i<sigParam.length;++i){typeSection.push(typeCodes[sigParam[i]])}if(sigRet=="v"){typeSection.push(0)}else{typeSection=typeSection.concat([1,typeCodes[sigRet]])}typeSection[1]=typeSection.length-2;var bytes=new Uint8Array([0,97,115,109,1,0,0,0].concat(typeSection,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0]));var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc}var freeTableIndexes=[];var functionsInTableMap;function getEmptyTableSlot(){if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1}function addFunctionWasm(func,sig){if(!functionsInTableMap){functionsInTableMap=new WeakMap;for(var i=0;i<wasmTable.length;i++){var item=wasmTable.get(i);if(item){functionsInTableMap.set(item,i)}}}if(functionsInTableMap.has(func)){return functionsInTableMap.get(func)}var ret=getEmptyTableSlot();try{wasmTable.set(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);wasmTable.set(ret,wrapped)}functionsInTableMap.set(func,ret);return ret}function removeFunction(index){functionsInTableMap.delete(wasmTable.get(index));freeTableIndexes.push(index)}function addFunction(func,sig){return addFunctionWasm(func,sig)}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}function getValue(ptr,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":return HEAP8[ptr>>0];case"i8":return HEAP8[ptr>>0];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP32[ptr>>2];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];default:abort("invalid type for getValue: "+type)}return null}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={string:function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},array:function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);ret=convertReturnValue(ret);if(stack!==0)stackRestore(stack);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type==="number"});var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var ALLOC_NORMAL=0;var ALLOC_STACK=1;function allocate(slab,allocator){var ret;if(allocator==ALLOC_STACK){ret=stackAlloc(slab.length)}else{ret=_malloc(slab.length)}if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function AsciiToString(ptr){var str="";while(1){var ch=HEAPU8[ptr++>>0];if(!ch)return str;str+=String.fromCharCode(ch)}}function stringToAscii(str,outPtr){return writeAsciiToMemory(str,outPtr,false)}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343)++i;len+=4}return len}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}function writeStringToMemory(string,buffer,dontAddNull){warnOnce("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!");var lastChar,end;if(dontAddNull){end=buffer+lengthBytesUTF8(string);lastChar=HEAP8[end]}stringToUTF8(string,buffer,Infinity);if(dontAddNull)HEAP8[end]=lastChar}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var HEAP,buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var TOTAL_STACK=5242880;var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPreMain(cb){__ATMAIN__.unshift(cb)}function addOnExit(cb){}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile="worker-js.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={env:asmLibraryArg,wasi_snapshot_preview1:asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["memory"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["__indirect_function_table"];addOnInit(Module["asm"]["__wasm_call_ctors"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var ASM_CONSTS={};function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function jsStackTrace(){var error=new Error;if(!error.stack){try{throw new Error}catch(e){error=e}if(!error.stack){return"(no stack trace available)"}}return error.stack.toString()}var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}function ___assert_fail(condition,filename,line,func){abort("Assertion failed: "+UTF8ToString(condition)+", at: "+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function abortOnCannotGrowMemory(requestedSize){abort("OOM")}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;abortOnCannotGrowMemory(requestedSize)}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function flush_NO_FILESYSTEM(){if(typeof _fflush!=="undefined")_fflush(0);var buffers=SYSCALLS.buffers;if(buffers[1].length)SYSCALLS.printChar(1,10);if(buffers[2].length)SYSCALLS.printChar(2,10)}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j<len;j++){SYSCALLS.printChar(fd,HEAPU8[ptr+j])}num+=len}HEAP32[pnum>>2]=num;return 0}function _setTempRet0(val){setTempRet0(val)}var ASSERTIONS=false;function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){if(ASSERTIONS){assert(false,"Character code "+chr+" ("+String.fromCharCode(chr)+") at offset "+i+" not in 0x00-0xFF.")}chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")}var asmLibraryArg={__assert_fail:___assert_fail,abort:_abort,emscripten_memcpy_big:_emscripten_memcpy_big,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,setTempRet0:_setTempRet0};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["__wasm_call_ctors"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["malloc"]).apply(null,arguments)};var _krypton_blake2=Module["_krypton_blake2"]=function(){return(_krypton_blake2=Module["_krypton_blake2"]=Module["asm"]["krypton_blake2"]).apply(null,arguments)};var _krypton_sha256=Module["_krypton_sha256"]=function(){return(_krypton_sha256=Module["_krypton_sha256"]=Module["asm"]["krypton_sha256"]).apply(null,arguments)};var _krypton_sha512=Module["_krypton_sha512"]=function(){return(_krypton_sha512=Module["_krypton_sha512"]=Module["asm"]["krypton_sha512"]).apply(null,arguments)};var _krypton_argon2=Module["_krypton_argon2"]=function(){return(_krypton_argon2=Module["_krypton_argon2"]=Module["asm"]["krypton_argon2"]).apply(null,arguments)};var _krypton_argon2_no_wipe=Module["_krypton_argon2_no_wipe"]=function(){return(_krypton_argon2_no_wipe=Module["_krypton_argon2_no_wipe"]=Module["asm"]["krypton_argon2_no_wipe"]).apply(null,arguments)};var _krypton_kdf_legacy=Module["_krypton_kdf_legacy"]=function(){return(_krypton_kdf_legacy=Module["_krypton_kdf_legacy"]=Module["asm"]["krypton_kdf_legacy"]).apply(null,arguments)};var _krypton_kdf=Module["_krypton_kdf"]=function(){return(_krypton_kdf=Module["_krypton_kdf"]=Module["asm"]["krypton_kdf"]).apply(null,arguments)};var _krypton_argon2_target=Module["_krypton_argon2_target"]=function(){return(_krypton_argon2_target=Module["_krypton_argon2_target"]=Module["asm"]["krypton_argon2_target"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["free"]).apply(null,arguments)};var _krypton_argon2_verify=Module["_krypton_argon2_verify"]=function(){return(_krypton_argon2_verify=Module["_krypton_argon2_verify"]=Module["asm"]["krypton_argon2_verify"]).apply(null,arguments)};var _ed25519_hash_public_keys=Module["_ed25519_hash_public_keys"]=function(){return(_ed25519_hash_public_keys=Module["_ed25519_hash_public_keys"]=Module["asm"]["ed25519_hash_public_keys"]).apply(null,arguments)};var _ed25519_derive_delinearized_private_key=Module["_ed25519_derive_delinearized_private_key"]=function(){return(_ed25519_derive_delinearized_private_key=Module["_ed25519_derive_delinearized_private_key"]=Module["asm"]["ed25519_derive_delinearized_private_key"]).apply(null,arguments)};var _ed25519_aggregate_delinearized_public_keys=Module["_ed25519_aggregate_delinearized_public_keys"]=function(){return(_ed25519_aggregate_delinearized_public_keys=Module["_ed25519_aggregate_delinearized_public_keys"]=Module["asm"]["ed25519_aggregate_delinearized_public_keys"]).apply(null,arguments)};var _ed25519_delinearize_public_key=Module["_ed25519_delinearize_public_key"]=function(){return(_ed25519_delinearize_public_key=Module["_ed25519_delinearize_public_key"]=Module["asm"]["ed25519_delinearize_public_key"]).apply(null,arguments)};var _ed25519_aggregate_commitments=Module["_ed25519_aggregate_commitments"]=function(){return(_ed25519_aggregate_commitments=Module["_ed25519_aggregate_commitments"]=Module["asm"]["ed25519_aggregate_commitments"]).apply(null,arguments)};var _ed25519_add_scalars=Module["_ed25519_add_scalars"]=function(){return(_ed25519_add_scalars=Module["_ed25519_add_scalars"]=Module["asm"]["ed25519_add_scalars"]).apply(null,arguments)};var _ed25519_create_commitment=Module["_ed25519_create_commitment"]=function(){return(_ed25519_create_commitment=Module["_ed25519_create_commitment"]=Module["asm"]["ed25519_create_commitment"]).apply(null,arguments)};var _ed25519_public_key_derive=Module["_ed25519_public_key_derive"]=function(){return(_ed25519_public_key_derive=Module["_ed25519_public_key_derive"]=Module["asm"]["ed25519_public_key_derive"]).apply(null,arguments)};var _get_static_memory_start=Module["_get_static_memory_start"]=function(){return(_get_static_memory_start=Module["_get_static_memory_start"]=Module["asm"]["get_static_memory_start"]).apply(null,arguments)};var _get_static_memory_size=Module["_get_static_memory_size"]=function(){return(_get_static_memory_size=Module["_get_static_memory_size"]=Module["asm"]["get_static_memory_size"]).apply(null,arguments)};var _ripemd160=Module["_ripemd160"]=function(){return(_ripemd160=Module["_ripemd160"]=Module["asm"]["ripemd160"]).apply(null,arguments)};var _keccak256=Module["_keccak256"]=function(){return(_keccak256=Module["_keccak256"]=Module["asm"]["keccak256"]).apply(null,arguments)};var _ed25519_delinearized_partial_sign=Module["_ed25519_delinearized_partial_sign"]=function(){return(_ed25519_delinearized_partial_sign=Module["_ed25519_delinearized_partial_sign"]=Module["asm"]["ed25519_delinearized_partial_sign"]).apply(null,arguments)};var _ed25519_sign=Module["_ed25519_sign"]=function(){return(_ed25519_sign=Module["_ed25519_sign"]=Module["asm"]["ed25519_sign"]).apply(null,arguments)};var _ed25519_verify=Module["_ed25519_verify"]=function(){return(_ed25519_verify=Module["_ed25519_verify"]=Module["asm"]["ed25519_verify"]).apply(null,arguments)};var _secp256k1_ctx_release=Module["_secp256k1_ctx_release"]=function(){return(_secp256k1_ctx_release=Module["_secp256k1_ctx_release"]=Module["asm"]["secp256k1_ctx_release"]).apply(null,arguments)};var _secp256k1_ctx_init=Module["_secp256k1_ctx_init"]=function(){return(_secp256k1_ctx_init=Module["_secp256k1_ctx_init"]=Module["asm"]["secp256k1_ctx_init"]).apply(null,arguments)};var _secp256k1_pubkey_create=Module["_secp256k1_pubkey_create"]=function(){return(_secp256k1_pubkey_create=Module["_secp256k1_pubkey_create"]=Module["asm"]["secp256k1_pubkey_create"]).apply(null,arguments)};var _secp256k1_pubkey_compress=Module["_secp256k1_pubkey_compress"]=function(){return(_secp256k1_pubkey_compress=Module["_secp256k1_pubkey_compress"]=Module["asm"]["secp256k1_pubkey_compress"]).apply(null,arguments)};var _secp256k1_schnorr_sign=Module["_secp256k1_schnorr_sign"]=function(){return(_secp256k1_schnorr_sign=Module["_secp256k1_schnorr_sign"]=Module["asm"]["secp256k1_schnorr_sign"]).apply(null,arguments)};var _secp256k1_schnorr_verify=Module["_secp256k1_schnorr_verify"]=function(){return(_secp256k1_schnorr_verify=Module["_secp256k1_schnorr_verify"]=Module["asm"]["secp256k1_schnorr_verify"]).apply(null,arguments)};var _secp256k1_hash_pubkeys=Module["_secp256k1_hash_pubkeys"]=function(){return(_secp256k1_hash_pubkeys=Module["_secp256k1_hash_pubkeys"]=Module["asm"]["secp256k1_hash_pubkeys"]).apply(null,arguments)};var _secp256k1_derive_delinearized_seckey=Module["_secp256k1_derive_delinearized_seckey"]=function(){return(_secp256k1_derive_delinearized_seckey=Module["_secp256k1_derive_delinearized_seckey"]=Module["asm"]["secp256k1_derive_delinearized_seckey"]).apply(null,arguments)};var _secp256k1_delinearize_pubkey=Module["_secp256k1_delinearize_pubkey"]=function(){return(_secp256k1_delinearize_pubkey=Module["_secp256k1_delinearize_pubkey"]=Module["asm"]["secp256k1_delinearize_pubkey"]).apply(null,arguments)};var _secp256k1_aggregate_delinearized_publkeys=Module["_secp256k1_aggregate_delinearized_publkeys"]=function(){return(_secp256k1_aggregate_delinearized_publkeys=Module["_secp256k1_aggregate_delinearized_publkeys"]=Module["asm"]["secp256k1_aggregate_delinearized_publkeys"]).apply(null,arguments)};var _secp256k1_partial_sign=Module["_secp256k1_partial_sign"]=function(){return(_secp256k1_partial_sign=Module["_secp256k1_partial_sign"]=Module["asm"]["secp256k1_partial_sign"]).apply(null,arguments)};var _secp256k1_create_commitment=Module["_secp256k1_create_commitment"]=function(){return(_secp256k1_create_commitment=Module["_secp256k1_create_commitment"]=Module["asm"]["secp256k1_create_commitment"]).apply(null,arguments)};var _secp256k1_aggregate_commitments=Module["_secp256k1_aggregate_commitments"]=function(){return(_secp256k1_aggregate_commitments=Module["_secp256k1_aggregate_commitments"]=Module["asm"]["secp256k1_aggregate_commitments"]).apply(null,arguments)};var _secp256k1_add_scalars=Module["_secp256k1_add_scalars"]=function(){return(_secp256k1_add_scalars=Module["_secp256k1_add_scalars"]=Module["asm"]["secp256k1_add_scalars"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["__errno_location"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["stackSave"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["stackRestore"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["stackAlloc"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["dynCall_jiji"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var calledMain=false;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){EXITSTATUS=status;if(implicit&&keepRuntimeAlive()&&status===0){return}if(keepRuntimeAlive()){}else{exitRuntime();if(Module["onExit"])Module["onExit"](status);ABORT=true}quit_(status,new ExitStatus(status))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();return Module.ready}}();if(typeof exports==="object"&&typeof module==="object")module.exports=Module;else if(typeof define==="function"&&define["amd"])define([],function(){return Module});else if(typeof exports==="object")exports["Module"]=Module;if(typeof module!=="undefined")module.exports=Module;if(typeof WasmHelper!=="undefined")WasmHelper.fireModuleLoaded();else if(typeof Krypton!=="undefined"&&Krypton.WasmHelper)Krypton.WasmHelper.fireModuleLoaded();
|
package/worker-wasm.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
var Module=function(){var _scriptDir=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:undefined;if(typeof __filename!=="undefined")_scriptDir=_scriptDir||__filename;return function(Module){Module=Module||{};var Module;if(!Module)Module=typeof Module!=="undefined"?Module:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=Number(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function==="function"){var typeNames={i:"i32",j:"i64",f:"f32",d:"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i<sig.length;++i){type.parameters.push(typeNames[sig[i]])}return new WebAssembly.Function(type,func)}var typeSection=[1,0,1,96];var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={i:127,j:126,f:125,d:124};typeSection.push(sigParam.length);for(var i=0;i<sigParam.length;++i){typeSection.push(typeCodes[sigParam[i]])}if(sigRet=="v"){typeSection.push(0)}else{typeSection=typeSection.concat([1,typeCodes[sigRet]])}typeSection[1]=typeSection.length-2;var bytes=new Uint8Array([0,97,115,109,1,0,0,0].concat(typeSection,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0]));var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc}var freeTableIndexes=[];var functionsInTableMap;function getEmptyTableSlot(){if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1}function addFunctionWasm(func,sig){if(!functionsInTableMap){functionsInTableMap=new WeakMap;for(var i=0;i<wasmTable.length;i++){var item=wasmTable.get(i);if(item){functionsInTableMap.set(item,i)}}}if(functionsInTableMap.has(func)){return functionsInTableMap.get(func)}var ret=getEmptyTableSlot();try{wasmTable.set(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);wasmTable.set(ret,wrapped)}functionsInTableMap.set(func,ret);return ret}function removeFunction(index){functionsInTableMap.delete(wasmTable.get(index));freeTableIndexes.push(index)}function addFunction(func,sig){return addFunctionWasm(func,sig)}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}function getValue(ptr,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":return HEAP8[ptr>>0];case"i8":return HEAP8[ptr>>0];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP32[ptr>>2];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];default:abort("invalid type for getValue: "+type)}return null}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={string:function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},array:function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);ret=convertReturnValue(ret);if(stack!==0)stackRestore(stack);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type==="number"});var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var ALLOC_NORMAL=0;var ALLOC_STACK=1;function allocate(slab,allocator){var ret;if(allocator==ALLOC_STACK){ret=stackAlloc(slab.length)}else{ret=_malloc(slab.length)}if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function AsciiToString(ptr){var str="";while(1){var ch=HEAPU8[ptr++>>0];if(!ch)return str;str+=String.fromCharCode(ch)}}function stringToAscii(str,outPtr){return writeAsciiToMemory(str,outPtr,false)}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343)++i;len+=4}return len}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}function writeStringToMemory(string,buffer,dontAddNull){warnOnce("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!");var lastChar,end;if(dontAddNull){end=buffer+lengthBytesUTF8(string);lastChar=HEAP8[end]}stringToUTF8(string,buffer,Infinity);if(dontAddNull)HEAP8[end]=lastChar}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var HEAP,buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var TOTAL_STACK=5242880;var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPreMain(cb){__ATMAIN__.unshift(cb)}function addOnExit(cb){}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile="worker-wasm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={env:asmLibraryArg,wasi_snapshot_preview1:asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["memory"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["__indirect_function_table"];addOnInit(Module["asm"]["__wasm_call_ctors"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;var ASM_CONSTS={};function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function jsStackTrace(){var error=new Error;if(!error.stack){try{throw new Error}catch(e){error=e}if(!error.stack){return"(no stack trace available)"}}return error.stack.toString()}var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}function ___assert_fail(condition,filename,line,func){abort("Assertion failed: "+UTF8ToString(condition)+", at: "+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function abortOnCannotGrowMemory(requestedSize){abort("OOM")}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;abortOnCannotGrowMemory(requestedSize)}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function flush_NO_FILESYSTEM(){if(typeof _fflush!=="undefined")_fflush(0);var buffers=SYSCALLS.buffers;if(buffers[1].length)SYSCALLS.printChar(1,10);if(buffers[2].length)SYSCALLS.printChar(2,10)}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j<len;j++){SYSCALLS.printChar(fd,HEAPU8[ptr+j])}num+=len}HEAP32[pnum>>2]=num;return 0}function _setTempRet0(val){setTempRet0(val)}var ASSERTIONS=false;function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){if(ASSERTIONS){assert(false,"Character code "+chr+" ("+String.fromCharCode(chr)+") at offset "+i+" not in 0x00-0xFF.")}chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")}var asmLibraryArg={__assert_fail:___assert_fail,abort:_abort,emscripten_memcpy_big:_emscripten_memcpy_big,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,setTempRet0:_setTempRet0};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["__wasm_call_ctors"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["malloc"]).apply(null,arguments)};var _krypton_blake2=Module["_krypton_blake2"]=function(){return(_krypton_blake2=Module["_krypton_blake2"]=Module["asm"]["krypton_blake2"]).apply(null,arguments)};var _krypton_sha256=Module["_krypton_sha256"]=function(){return(_krypton_sha256=Module["_krypton_sha256"]=Module["asm"]["krypton_sha256"]).apply(null,arguments)};var _krypton_sha512=Module["_krypton_sha512"]=function(){return(_krypton_sha512=Module["_krypton_sha512"]=Module["asm"]["krypton_sha512"]).apply(null,arguments)};var _krypton_argon2=Module["_krypton_argon2"]=function(){return(_krypton_argon2=Module["_krypton_argon2"]=Module["asm"]["krypton_argon2"]).apply(null,arguments)};var _krypton_argon2_no_wipe=Module["_krypton_argon2_no_wipe"]=function(){return(_krypton_argon2_no_wipe=Module["_krypton_argon2_no_wipe"]=Module["asm"]["krypton_argon2_no_wipe"]).apply(null,arguments)};var _krypton_kdf_legacy=Module["_krypton_kdf_legacy"]=function(){return(_krypton_kdf_legacy=Module["_krypton_kdf_legacy"]=Module["asm"]["krypton_kdf_legacy"]).apply(null,arguments)};var _krypton_kdf=Module["_krypton_kdf"]=function(){return(_krypton_kdf=Module["_krypton_kdf"]=Module["asm"]["krypton_kdf"]).apply(null,arguments)};var _krypton_argon2_target=Module["_krypton_argon2_target"]=function(){return(_krypton_argon2_target=Module["_krypton_argon2_target"]=Module["asm"]["krypton_argon2_target"]).apply(null,arguments)};var _krypton_argon2_verify=Module["_krypton_argon2_verify"]=function(){return(_krypton_argon2_verify=Module["_krypton_argon2_verify"]=Module["asm"]["krypton_argon2_verify"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["free"]).apply(null,arguments)};var _ed25519_hash_public_keys=Module["_ed25519_hash_public_keys"]=function(){return(_ed25519_hash_public_keys=Module["_ed25519_hash_public_keys"]=Module["asm"]["ed25519_hash_public_keys"]).apply(null,arguments)};var _ed25519_derive_delinearized_private_key=Module["_ed25519_derive_delinearized_private_key"]=function(){return(_ed25519_derive_delinearized_private_key=Module["_ed25519_derive_delinearized_private_key"]=Module["asm"]["ed25519_derive_delinearized_private_key"]).apply(null,arguments)};var _ed25519_aggregate_delinearized_public_keys=Module["_ed25519_aggregate_delinearized_public_keys"]=function(){return(_ed25519_aggregate_delinearized_public_keys=Module["_ed25519_aggregate_delinearized_public_keys"]=Module["asm"]["ed25519_aggregate_delinearized_public_keys"]).apply(null,arguments)};var _ed25519_delinearize_public_key=Module["_ed25519_delinearize_public_key"]=function(){return(_ed25519_delinearize_public_key=Module["_ed25519_delinearize_public_key"]=Module["asm"]["ed25519_delinearize_public_key"]).apply(null,arguments)};var _ed25519_aggregate_commitments=Module["_ed25519_aggregate_commitments"]=function(){return(_ed25519_aggregate_commitments=Module["_ed25519_aggregate_commitments"]=Module["asm"]["ed25519_aggregate_commitments"]).apply(null,arguments)};var _ed25519_add_scalars=Module["_ed25519_add_scalars"]=function(){return(_ed25519_add_scalars=Module["_ed25519_add_scalars"]=Module["asm"]["ed25519_add_scalars"]).apply(null,arguments)};var _ed25519_create_commitment=Module["_ed25519_create_commitment"]=function(){return(_ed25519_create_commitment=Module["_ed25519_create_commitment"]=Module["asm"]["ed25519_create_commitment"]).apply(null,arguments)};var _ed25519_public_key_derive=Module["_ed25519_public_key_derive"]=function(){return(_ed25519_public_key_derive=Module["_ed25519_public_key_derive"]=Module["asm"]["ed25519_public_key_derive"]).apply(null,arguments)};var _get_static_memory_start=Module["_get_static_memory_start"]=function(){return(_get_static_memory_start=Module["_get_static_memory_start"]=Module["asm"]["get_static_memory_start"]).apply(null,arguments)};var _get_static_memory_size=Module["_get_static_memory_size"]=function(){return(_get_static_memory_size=Module["_get_static_memory_size"]=Module["asm"]["get_static_memory_size"]).apply(null,arguments)};var _ripemd160=Module["_ripemd160"]=function(){return(_ripemd160=Module["_ripemd160"]=Module["asm"]["ripemd160"]).apply(null,arguments)};var _keccak256=Module["_keccak256"]=function(){return(_keccak256=Module["_keccak256"]=Module["asm"]["keccak256"]).apply(null,arguments)};var _ed25519_delinearized_partial_sign=Module["_ed25519_delinearized_partial_sign"]=function(){return(_ed25519_delinearized_partial_sign=Module["_ed25519_delinearized_partial_sign"]=Module["asm"]["ed25519_delinearized_partial_sign"]).apply(null,arguments)};var _ed25519_sign=Module["_ed25519_sign"]=function(){return(_ed25519_sign=Module["_ed25519_sign"]=Module["asm"]["ed25519_sign"]).apply(null,arguments)};var _ed25519_verify=Module["_ed25519_verify"]=function(){return(_ed25519_verify=Module["_ed25519_verify"]=Module["asm"]["ed25519_verify"]).apply(null,arguments)};var _secp256k1_ctx_release=Module["_secp256k1_ctx_release"]=function(){return(_secp256k1_ctx_release=Module["_secp256k1_ctx_release"]=Module["asm"]["secp256k1_ctx_release"]).apply(null,arguments)};var _secp256k1_ctx_init=Module["_secp256k1_ctx_init"]=function(){return(_secp256k1_ctx_init=Module["_secp256k1_ctx_init"]=Module["asm"]["secp256k1_ctx_init"]).apply(null,arguments)};var _secp256k1_pubkey_create=Module["_secp256k1_pubkey_create"]=function(){return(_secp256k1_pubkey_create=Module["_secp256k1_pubkey_create"]=Module["asm"]["secp256k1_pubkey_create"]).apply(null,arguments)};var _secp256k1_pubkey_compress=Module["_secp256k1_pubkey_compress"]=function(){return(_secp256k1_pubkey_compress=Module["_secp256k1_pubkey_compress"]=Module["asm"]["secp256k1_pubkey_compress"]).apply(null,arguments)};var _secp256k1_schnorr_sign=Module["_secp256k1_schnorr_sign"]=function(){return(_secp256k1_schnorr_sign=Module["_secp256k1_schnorr_sign"]=Module["asm"]["secp256k1_schnorr_sign"]).apply(null,arguments)};var _secp256k1_schnorr_verify=Module["_secp256k1_schnorr_verify"]=function(){return(_secp256k1_schnorr_verify=Module["_secp256k1_schnorr_verify"]=Module["asm"]["secp256k1_schnorr_verify"]).apply(null,arguments)};var _secp256k1_hash_pubkeys=Module["_secp256k1_hash_pubkeys"]=function(){return(_secp256k1_hash_pubkeys=Module["_secp256k1_hash_pubkeys"]=Module["asm"]["secp256k1_hash_pubkeys"]).apply(null,arguments)};var _secp256k1_derive_delinearized_seckey=Module["_secp256k1_derive_delinearized_seckey"]=function(){return(_secp256k1_derive_delinearized_seckey=Module["_secp256k1_derive_delinearized_seckey"]=Module["asm"]["secp256k1_derive_delinearized_seckey"]).apply(null,arguments)};var _secp256k1_delinearize_pubkey=Module["_secp256k1_delinearize_pubkey"]=function(){return(_secp256k1_delinearize_pubkey=Module["_secp256k1_delinearize_pubkey"]=Module["asm"]["secp256k1_delinearize_pubkey"]).apply(null,arguments)};var _secp256k1_aggregate_delinearized_publkeys=Module["_secp256k1_aggregate_delinearized_publkeys"]=function(){return(_secp256k1_aggregate_delinearized_publkeys=Module["_secp256k1_aggregate_delinearized_publkeys"]=Module["asm"]["secp256k1_aggregate_delinearized_publkeys"]).apply(null,arguments)};var _secp256k1_partial_sign=Module["_secp256k1_partial_sign"]=function(){return(_secp256k1_partial_sign=Module["_secp256k1_partial_sign"]=Module["asm"]["secp256k1_partial_sign"]).apply(null,arguments)};var _secp256k1_create_commitment=Module["_secp256k1_create_commitment"]=function(){return(_secp256k1_create_commitment=Module["_secp256k1_create_commitment"]=Module["asm"]["secp256k1_create_commitment"]).apply(null,arguments)};var _secp256k1_aggregate_commitments=Module["_secp256k1_aggregate_commitments"]=function(){return(_secp256k1_aggregate_commitments=Module["_secp256k1_aggregate_commitments"]=Module["asm"]["secp256k1_aggregate_commitments"]).apply(null,arguments)};var _secp256k1_add_scalars=Module["_secp256k1_add_scalars"]=function(){return(_secp256k1_add_scalars=Module["_secp256k1_add_scalars"]=Module["asm"]["secp256k1_add_scalars"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["__errno_location"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["stackSave"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["stackRestore"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["stackAlloc"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["dynCall_jiji"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var calledMain=false;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){EXITSTATUS=status;if(implicit&&keepRuntimeAlive()&&status===0){return}if(keepRuntimeAlive()){}else{exitRuntime();if(Module["onExit"])Module["onExit"](status);ABORT=true}quit_(status,new ExitStatus(status))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();return Module.ready}}();if(typeof exports==="object"&&typeof module==="object")module.exports=Module;else if(typeof define==="function"&&define["amd"])define([],function(){return Module});else if(typeof exports==="object")exports["Module"]=Module;if(typeof module!=="undefined")module.exports=Module;if(typeof WasmHelper!=="undefined")WasmHelper.fireModuleLoaded();else if(typeof Krypton!=="undefined"&&Krypton.WasmHelper)Krypton.WasmHelper.fireModuleLoaded();
|
package/worker-wasm.wasm
ADDED
Binary file
|
package/worker.js
ADDED
@@ -0,0 +1,2 @@
|
|
1
|
+
class Class{static get scope(){return"undefined"!=typeof exports?exports:"undefined"!=typeof self?self:window}static register(e){"undefined"!=typeof exports&&(exports[e.name]=e)}}Class.register(Class);class LogNative{constructor(){this._global_level=Log.INFO,this._tag_levels={};try{if(window.localStorage)try{let e=window.localStorage.getItem("log_tag_levels");e&&"string"==typeof e&&(e=JSON.parse(e)),e&&"object"==typeof e&&(this._tag_levels=e)}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),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(){return Log._instance||(Log._instance=new Log(new LogNative)),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){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,r=Array.prototype.slice.call(arguments,0)),Log.instance.msg(Log.DEBUG,e,r)}static e(e,t,...r){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,r=Array.prototype.slice.call(arguments,0)),Log.instance.msg(Log.ERROR,e,r)}static i(e,t,...r){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,r=Array.prototype.slice.call(arguments,0)),Log.instance.msg(Log.INFO,e,r)}static v(e,t,...r){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,r=Array.prototype.slice.call(arguments,0)),Log.instance.msg(Log.VERBOSE,e,r)}static w(e,t,...r){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,r=Array.prototype.slice.call(arguments,0)),Log.instance.msg(Log.WARNING,e,r)}static t(e,t,...r){arguments.length>=2?(e=arguments[0],r=Array.prototype.slice.call(arguments,1)):(e=void 0,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 IWorker{static async createProxy(e,t,r){return new(IWorker.Proxy(e))(r,t)}static async startWorkerForProxy(e,t,r){return IWorker._workersSupported?(r||(r=`${Krypton._path}worker.js`),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),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 s=()=>setTimeout(t,100);i.onreadystatechange=s,i.onload=s,r.appendChild(i)}static Proxy(e){const t=class extends e{constructor(t,r){return super(),this._name=r,this._messageId=0,this._worker=t,this._worker.onmessage=this._receive.bind(this),this._waiting=new Map,this._invoke("init",[e.name,r]).then(()=>this)}_receive(e){const t=this._waiting.get(e.data.id);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)):Log.w(WorkerProxy,"Unknown reply",e)}_invoke(e,t=[]){return new Promise((r,i)=>{const s={command:e,args:t,id:this._messageId++};this._waiting.set(s.id,{resolve:r,error:i}),this._worker.postMessage(s)})}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 t=this._invoke(e.data.command,e.data.args);t instanceof Promise?t.then(t=>{this._result(e,"OK",t)}):this._result(e,"OK",t)}catch(t){this._result(e,"error",t.message||t)}}init(e){this._name=e,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(){return await this._updateToSize(),this}get poolSize(){return this._poolSize}set poolSize(e){this._poolSize=e,this._updateToSize().catch(Log.w.tag(IWorker))}destroy(){return this._poolSize=0,this._updateToSize()}_invoke(e,t){return IWorker._workersSupported?new Promise((r,i)=>{this._waitingCalls.push({name:e,args:t,resolve:r,error:i});const s=this._freeWorkers.shift();s&&this._step(s).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(e){t.error(e)}if(-1===this._workers.indexOf(e))return void e.destroy();t=this._waitingCalls.shift()}this._freeWorkers.push(e)}async _updateToSize(){"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 e of t)this._workers.push(e),this._step(e).catch(Log.w.tag(IWorker));for(;this._workers.length>this._poolSize;){const e=this._freeWorkers.shift()||this._workers.pop(),t=this._workers.indexOf(e);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 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 t=0;t<CryptoUtils.SHA512_BLOCK_SIZE;++t){const s=e[t]||0;r[t]=54^s,i[t]=92^s}const s=Hash.computeSha512(BufferUtils.concatTypedArrays(r,t));return Hash.computeSha512(BufferUtils.concatTypedArrays(i,s))}static computePBKDF2sha512(e,t,r,i){const s=Hash.SIZE.get(Hash.Algorithm.SHA512);if(i>(Math.pow(2,32)-1)*s)throw new Error("Derived key too long");const n=Math.ceil(i/s),o=i-(n-1)*s,a=new SerialBuffer(i);for(let i=1;i<=n;i++){let s=new SerialBuffer(t.length+4);s.write(t),s.writeUint32(i);const l=s=CryptoUtils.computeHmacSha512(e,s);for(let t=1;t<r;t++){s=CryptoUtils.computeHmacSha512(e,s);for(let e=0;e<l.length;e++)l[e]^=s[e]}i<n?a.write(l):a.write(l.slice(0,o))}return a}static async otpKdfLegacy(e,t,r,i){const s=await CryptoWorker.getInstanceAsync(),n=await s.kdfLegacy(t,r,i,e.byteLength);return BufferUtils.xor(e,n)}static async otpKdf(e,t,r,i){const s=await CryptoWorker.getInstanceAsync(),n=await s.kdf(t,r,i,e.byteLength);return BufferUtils.xor(e,n)}}CryptoUtils.SHA512_BLOCK_SIZE=128,Class.register(CryptoUtils);class CryptoWorker{static get lib(){return CryptoLib.instance}static async getInstanceAsync(){return CryptoWorker._workerAsync||(CryptoWorker._workerAsync=await IWorker.startWorkerPoolForProxy(CryptoWorker,"crypto",4)),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,s){}}CryptoWorker._workerAsync=null,Class.register(CryptoWorker);class CryptoWorkerImpl extends(IWorker.Stub(CryptoWorker)){constructor(){super(),this._superInit=super.init}async init(e){await this._superInit.call(this,e),PlatformUtils.isBrowser()&&await WasmHelper.doImportBrowser(),CryptoWorker._workerAsync=this}computeArgon2d(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.ARGON2D)),r=NodeNative.node_argon2(t,new Uint8Array(e),512);if(0!==r)throw r;return t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.ARGON2D),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);const n=Module._krypton_argon2(i,s,e.length,512);if(0!==n)throw n;const o=new Uint8Array(r);return o.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),o}catch(e){throw Log.w(CryptoWorkerImpl,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}computeArgon2dBatch(e){const t=[];if(PlatformUtils.isNodeJs()){for(const r of e){const e=new Uint8Array(Hash.getSize(Hash.Algorithm.ARGON2D)),i=NodeNative.node_argon2(e,new Uint8Array(r),512);if(0!==i)throw i;t.push(e)}return t}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.ARGON2D),s=Module.stackAlloc(i),n=Module.stackSave();for(const r of e){Module.stackRestore(n);const e=Module.stackAlloc(r.length);new Uint8Array(Module.HEAPU8.buffer,e,r.length).set(r);const o=Module._krypton_argon2(s,e,r.length,512);if(0!==o)throw o;const a=new Uint8Array(i);a.set(new Uint8Array(Module.HEAPU8.buffer,s,i)),t.push(a)}return t}catch(e){throw Log.w(CryptoWorkerImpl,e),e}finally{void 0!==r&&Module.stackRestore(r)}}}kdfLegacy(e,t,r,i=Hash.getSize(Hash.Algorithm.ARGON2D)){if(PlatformUtils.isNodeJs()){const s=new Uint8Array(i),n=NodeNative.node_kdf_legacy(s,new Uint8Array(e),new Uint8Array(t),512,r);if(0!==n)throw n;return s}{let s;try{s=Module.stackSave();const n=Module.stackAlloc(i),o=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,o,e.length).set(e);const a=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,a,t.length).set(t);const l=Module._krypton_kdf_legacy(n,i,o,e.length,a,t.length,512,r);if(0!==l)throw l;const c=new Uint8Array(i);return c.set(new Uint8Array(Module.HEAPU8.buffer,n,i)),c}catch(e){throw Log.w(CryptoWorkerImpl,e),e}finally{void 0!==s&&Module.stackRestore(s)}}}kdf(e,t,r,i=Hash.getSize(Hash.Algorithm.ARGON2D)){if(PlatformUtils.isNodeJs()){const s=new Uint8Array(i),n=NodeNative.node_kdf(s,new Uint8Array(e),new Uint8Array(t),512,r);if(0!==n)throw n;return s}{let s;try{s=Module.stackSave();const n=Module.stackAlloc(i),o=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,o,e.length).set(e);const a=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,a,t.length).set(t);const l=Module._krypton_kdf(n,i,o,e.length,a,t.length,512,r);if(0!==l)throw l;const c=new Uint8Array(i);return c.set(new Uint8Array(Module.HEAPU8.buffer,n,i)),c}catch(e){throw Log.w(CryptoWorkerImpl,e),e}finally{void 0!==s&&Module.stackRestore(s)}}}async blockVerify(e,t,r,i,s){GenesisConfig={GENESIS_HASH:Hash.unserialize(new SerialBuffer(i)),NETWORK_ID:s};const n=Block.unserialize(new SerialBuffer(e));for(let e=0;e<t.length;e++)n.body.transactions[e]._valid=t[e];const o=await n._verify(r),a=await n.header.pow(),l=n.interlink.hash(),c=n.body.hash();return{valid:o,pow:a.serialize(),interlinkHash:l.serialize(),bodyHash:c.serialize()}}}IWorker.prepareForWorkerUse(CryptoWorker,new CryptoWorkerImpl),function(e){"use strict";var t,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,s=Math.floor,n="[BigNumber Error] ",o=n+"Number primitive has more than 15 significant digits: ",a=1e14,l=14,c=9007199254740991,h=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],u=1e7,f=1e9;function d(e){var t=0|e;return e>0||e===t?t:t-1}function g(e){for(var t,r,i=1,s=e.length,n=e[0]+"";i<s;){for(t=e[i++]+"",r=l-t.length;r--;t="0"+t);n+=t}for(s=n.length;48===n.charCodeAt(--s););return n.slice(0,s+1||1)}function _(e,t){var r,i,s=e.c,n=t.c,o=e.s,a=t.s,l=e.e,c=t.e;if(!o||!a)return null;if(r=s&&!s[0],i=n&&!n[0],r||i)return r?i?0:-a:o;if(o!=a)return o;if(r=o<0,i=l==c,!s||!n)return i?0:!s^r?1:-1;if(!i)return l>c^r?1:-1;for(a=(l=s.length)<(c=n.length)?l:c,o=0;o<a;o++)if(s[o]!=n[o])return s[o]>n[o]^r?1:-1;return l==c?0:l>c^r?1:-1}function y(e,t,r,o){if(e<t||e>r||e!==(e<0?i(e):s(e)))throw Error(n+(o||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+e)}function A(e){return"[object Array]"==Object.prototype.toString.call(e)}function w(e){var t=e.c.length-1;return d(e.e/l)==t&&e.c[t]%2!=0}function p(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function m(e,t,r){var i,s;if(t<0){for(s=r+".";++t;s+=r);e=s+e}else if(++t>(i=e.length)){for(s=r,t-=i;--t;s+=r);e+=s}else t<i&&(e=e.slice(0,t)+"."+e.slice(t));return e}(t=function e(t){var E,S,U,P,T,I,b,B,k,L=F.prototype={constructor:F,toString:null,valueOf:null},v=new F(1),H=20,N=4,M=-7,C=21,z=-1e7,O=1e7,R=!1,K=1,D=0,W={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0},x="0123456789abcdefghijklmnopqrstuvwxyz";function F(e,t){var i,n,a,h,u,f,d,g=this;if(!(g instanceof F))return new F(e,t);if(null==t){if(e instanceof F)return g.s=e.s,g.e=e.e,void(g.c=(e=e.c)?e.slice():e);if((u="number"==typeof e)&&0*e==0){if(g.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,h=e;h>=10;h/=10,a++);return g.e=a,void(g.c=[e])}d=e+""}else{if(!r.test(d=e+""))return U(g,d,u);g.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}}else{if(y(t,2,x.length,"Base"),d=e+"",10==t)return q(g=new F(e instanceof F?e:d),H+g.e+1,N);if(u="number"==typeof e){if(0*e!=0)return U(g,d,u,t);if(g.s=1/e<0?(d=d.slice(1),-1):1,F.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(o+e);u=!1}else g.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1,t>10&&t<37&&(d=d.toLowerCase());for(i=x.slice(0,t),a=h=0,f=d.length;h<f;h++)if(i.indexOf(n=d.charAt(h))<0){if("."==n&&h>a){a=f;continue}return U(g,e+"",u,t)}d=S(d,t,10,g.s)}for((a=d.indexOf("."))>-1&&(d=d.replace(".","")),(h=d.search(/e/i))>0?(a<0&&(a=h),a+=+d.slice(h+1),d=d.substring(0,h)):a<0&&(a=d.length),h=0;48===d.charCodeAt(h);h++);for(f=d.length;48===d.charCodeAt(--f););if(d=d.slice(h,++f)){if(f-=h,u&&F.DEBUG&&f>15&&(e>c||e!==s(e)))throw Error(o+g.s*e);if((a=a-h-1)>O)g.c=g.e=null;else if(a<z)g.c=[g.e=0];else{if(g.e=a,g.c=[],h=(a+1)%l,a<0&&(h+=l),h<f){for(h&&g.c.push(+d.slice(0,h)),f-=l;h<f;)g.c.push(+d.slice(h,h+=l));d=d.slice(h),h=l-d.length}else h-=f;for(;h--;d+="0");g.c.push(+d)}}else g.c=[g.e=0]}function G(e,t,r,i){var s,n,o,a,l;if(null==r?r=N:y(r,0,8),!e.c)return e.toString();if(s=e.c[0],o=e.e,null==t)l=g(e.c),l=1==i||2==i&&o<=M?p(l,o):m(l,o,"0");else if(n=(e=q(new F(e),t,r)).e,a=(l=g(e.c)).length,1==i||2==i&&(t<=n||n<=M)){for(;a<t;l+="0",a++);l=p(l,n)}else if(t-=o,l=m(l,n,"0"),n+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=n-a)>0)for(n+1==a&&(l+=".");t--;l+="0");return e.s<0&&s?"-"+l:l}function V(e,t){var r,i,s=0;for(A(e[0])&&(e=e[0]),r=new F(e[0]);++s<e.length;){if(!(i=new F(e[s])).s){r=i;break}t.call(r,i)&&(r=i)}return r}function Z(e,t,r){for(var i=1,s=t.length;!t[--s];t.pop());for(s=t[0];s>=10;s/=10,i++);return(r=i+r*l-1)>O?e.c=e.e=null:r<z?e.c=[e.e=0]:(e.e=r,e.c=t),e}function q(e,t,r,n){var o,c,u,f,d,g,_,y=e.c,A=h;if(y){e:{for(o=1,f=y[0];f>=10;f/=10,o++);if((c=t-o)<0)c+=l,u=t,_=(d=y[g=0])/A[o-u-1]%10|0;else if((g=i((c+1)/l))>=y.length){if(!n)break e;for(;y.length<=g;y.push(0));d=_=0,o=1,u=(c%=l)-l+1}else{for(d=f=y[g],o=1;f>=10;f/=10,o++);_=(u=(c%=l)-l+o)<0?0:d/A[o-u-1]%10|0}if(n=n||t<0||null!=y[g+1]||(u<0?d:d%A[o-u-1]),n=r<4?(_||n)&&(0==r||r==(e.s<0?3:2)):_>5||5==_&&(4==r||n||6==r&&(c>0?u>0?d/A[o-u]:0:y[g-1])%10&1||r==(e.s<0?8:7)),t<1||!y[0])return y.length=0,n?(t-=e.e+1,y[0]=A[(l-t%l)%l],e.e=-t||0):y[0]=e.e=0,e;if(0==c?(y.length=g,f=1,g--):(y.length=g+1,f=A[l-c],y[g]=u>0?s(d/A[o-u]%A[u])*f:0),n)for(;;){if(0==g){for(c=1,u=y[0];u>=10;u/=10,c++);for(u=y[0]+=f,f=1;u>=10;u/=10,f++);c!=f&&(e.e++,y[0]==a&&(y[0]=1));break}if(y[g]+=f,y[g]!=a)break;y[g--]=0,f=1}for(c=y.length;0===y[--c];y.pop());}e.e>O?e.c=e.e=null:e.e<z&&(e.c=[e.e=0])}return e}return F.clone=e,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(n+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(y(r=e[t],0,f,t),H=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(y(r=e[t],0,8,t),N=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(A(r=e[t])?(y(r[0],-f,0,t),y(r[1],0,f,t),M=r[0],C=r[1]):(y(r,-f,f,t),M=-(C=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if(A(r=e[t]))y(r[0],-f,-1,t),y(r[1],1,f,t),z=r[0],O=r[1];else{if(y(r,-f,f,t),!r)throw Error(n+t+" cannot be zero: "+r);z=-(O=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(n+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw R=!r,Error(n+"crypto unavailable");R=r}else R=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(y(r=e[t],0,9,t),K=r),e.hasOwnProperty(t="POW_PRECISION")&&(y(r=e[t],0,f,t),D=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(n+t+" not an object: "+r);W=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.$|\.|(.).*\1/.test(r))throw Error(n+t+" invalid: "+r);x=r}}return{DECIMAL_PLACES:H,ROUNDING_MODE:N,EXPONENTIAL_AT:[M,C],RANGE:[z,O],CRYPTO:R,MODULO_MODE:K,POW_PRECISION:D,FORMAT:W,ALPHABET:x}},F.isBigNumber=function(e){return e instanceof F||e&&!0===e._isBigNumber||!1},F.maximum=F.max=function(){return V(arguments,L.lt)},F.minimum=F.min=function(){return V(arguments,L.gt)},F.random=(P=9007199254740992*Math.random()&2097151?function(){return s(9007199254740992*Math.random())}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,o,a,c,u=0,d=[],g=new F(v);if(null==e?e=H:y(e,0,f),a=i(e/l),R)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(a*=2));u<a;)(c=131072*t[u]+(t[u+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[u]=r[0],t[u+1]=r[1]):(d.push(c%1e14),u+=2);u=a/2}else{if(!crypto.randomBytes)throw R=!1,Error(n+"crypto unavailable");for(t=crypto.randomBytes(a*=7);u<a;)(c=281474976710656*(31&t[u])+1099511627776*t[u+1]+4294967296*t[u+2]+16777216*t[u+3]+(t[u+4]<<16)+(t[u+5]<<8)+t[u+6])>=9e15?crypto.randomBytes(7).copy(t,u):(d.push(c%1e14),u+=7);u=a/7}if(!R)for(;u<a;)(c=P())<9e15&&(d[u++]=c%1e14);for(a=d[--u],e%=l,a&&e&&(c=h[l-e],d[u]=s(a/c)*c);0===d[u];d.pop(),u--);if(u<0)d=[o=0];else{for(o=-1;0===d[0];d.splice(0,1),o-=l);for(u=1,c=d[0];c>=10;c/=10,u++);u<l&&(o-=l-u)}return g.e=o,g.c=d,g}),S=function(){function e(e,t,r,i){for(var s,n,o=[0],a=0,l=e.length;a<l;){for(n=o.length;n--;o[n]*=t);for(o[0]+=i.indexOf(e.charAt(a++)),s=0;s<o.length;s++)o[s]>r-1&&(null==o[s+1]&&(o[s+1]=0),o[s+1]+=o[s]/r|0,o[s]%=r)}return o.reverse()}return function(t,r,i,s,n){var o,a,l,c,h,u,f,d,_=t.indexOf("."),y=H,A=N;for(_>=0&&(c=D,D=0,t=t.replace(".",""),u=(d=new F(r)).pow(t.length-_),D=c,d.c=e(m(g(u.c),u.e,"0"),10,i,"0123456789"),d.e=d.c.length),l=c=(f=e(t,r,i,n?(o=x,"0123456789"):(o="0123456789",x))).length;0==f[--c];f.pop());if(!f[0])return o.charAt(0);if(_<0?--l:(u.c=f,u.e=l,u.s=s,f=(u=E(u,d,y,A,i)).c,h=u.r,l=u.e),_=f[a=l+y+1],c=i/2,h=h||a<0||null!=f[a+1],h=A<4?(null!=_||h)&&(0==A||A==(u.s<0?3:2)):_>c||_==c&&(4==A||h||6==A&&1&f[a-1]||A==(u.s<0?8:7)),a<1||!f[0])t=h?m(o.charAt(1),-y,o.charAt(0)):o.charAt(0);else{if(f.length=a,h)for(--i;++f[--a]>i;)f[a]=0,a||(++l,f=[1].concat(f));for(c=f.length;!f[--c];);for(_=0,t="";_<=c;t+=o.charAt(f[_++]));t=m(t,l,o.charAt(0))}return t}}(),E=function(){function e(e,t,r){var i,s,n,o,a=0,l=e.length,c=t%u,h=t/u|0;for(e=e.slice();l--;)a=((s=c*(n=e[l]%u)+(i=h*n+(o=e[l]/u|0)*c)%u*u+a)/r|0)+(i/u|0)+h*o,e[l]=s%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,i){var s,n;if(r!=i)n=r>i?1:-1;else for(s=n=0;s<r;s++)if(e[s]!=t[s]){n=e[s]>t[s]?1:-1;break}return n}function r(e,t,r,i){for(var s=0;r--;)e[r]-=s,s=e[r]<t[r]?1:0,e[r]=s*i+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(i,n,o,c,h){var u,f,g,_,y,A,w,p,m,E,S,U,P,T,I,b,B,k=i.s==n.s?1:-1,L=i.c,v=n.c;if(!(L&&L[0]&&v&&v[0]))return new F(i.s&&n.s&&(L?!v||L[0]!=v[0]:v)?L&&0==L[0]||!v?0*k:k/0:NaN);for(m=(p=new F(k)).c=[],k=o+(f=i.e-n.e)+1,h||(h=a,f=d(i.e/l)-d(n.e/l),k=k/l|0),g=0;v[g]==(L[g]||0);g++);if(v[g]>(L[g]||0)&&f--,k<0)m.push(1),_=!0;else{for(T=L.length,b=v.length,g=0,k+=2,(y=s(h/(v[0]+1)))>1&&(v=e(v,y,h),L=e(L,y,h),b=v.length,T=L.length),P=b,S=(E=L.slice(0,b)).length;S<b;E[S++]=0);B=v.slice(),B=[0].concat(B),I=v[0],v[1]>=h/2&&I++;do{if(y=0,(u=t(v,E,b,S))<0){if(U=E[0],b!=S&&(U=U*h+(E[1]||0)),(y=s(U/I))>1)for(y>=h&&(y=h-1),w=(A=e(v,y,h)).length,S=E.length;1==t(A,E,w,S);)y--,r(A,b<w?B:v,w,h),w=A.length,u=1;else 0==y&&(u=y=1),w=(A=v.slice()).length;if(w<S&&(A=[0].concat(A)),r(E,A,S,h),S=E.length,-1==u)for(;t(v,E,b,S)<1;)y++,r(E,b<S?B:v,S,h),S=E.length}else 0===u&&(y++,E=[0]);m[g++]=y,E[0]?E[S++]=L[P]||0:(E=[L[P]],S=1)}while((P++<T||null!=E[0])&&k--);_=null!=E[0],m[0]||m.splice(0,1)}if(h==a){for(g=1,k=m[0];k>=10;k/=10,g++);q(p,o+(p.e=g+f*l-1)+1,c,_)}else p.e=f,p.r=+_;return p}}(),T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,I=/^([^.]+)\.$/,b=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,k=/^\s*\+(?=[\w.])|^\s+|\s+$/g,U=function(e,t,r,i){var s,o=r?t:t.replace(k,"");if(B.test(o))e.s=isNaN(o)?null:o<0?-1:1,e.c=e.e=null;else{if(!r&&(o=o.replace(T,function(e,t,r){return s="x"==(r=r.toLowerCase())?16:"b"==r?2:8,i&&i!=s?e:t}),i&&(s=i,o=o.replace(I,"$1").replace(b,"0.$1")),t!=o))return new F(o,s);if(F.DEBUG)throw Error(n+"Not a"+(i?" base "+i:"")+" number: "+t);e.c=e.e=e.s=null}},L.absoluteValue=L.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},L.comparedTo=function(e,t){return _(this,new F(e,t))},L.decimalPlaces=L.dp=function(e,t){var r,i,s,n=this;if(null!=e)return y(e,0,f),null==t?t=N:y(t,0,8),q(new F(n),e+n.e+1,t);if(!(r=n.c))return null;if(i=((s=r.length-1)-d(this.e/l))*l,s=r[s])for(;s%10==0;s/=10,i--);return i<0&&(i=0),i},L.dividedBy=L.div=function(e,t){return E(this,new F(e,t),H,N)},L.dividedToIntegerBy=L.idiv=function(e,t){return E(this,new F(e,t),0,1)},L.exponentiatedBy=L.pow=function(e,t){var r,o,a,c,h,u,f,d=this;if((e=new F(e)).c&&!e.isInteger())throw Error(n+"Exponent not an integer: "+e);if(null!=t&&(t=new F(t)),c=e.e>14,!d.c||!d.c[0]||1==d.c[0]&&!d.e&&1==d.c.length||!e.c||!e.c[0])return f=new F(Math.pow(+d.valueOf(),c?2-w(e):+e)),t?f.mod(t):f;if(h=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);(o=!h&&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)))return a=d.s<0&&w(e)?-0:0,d.e>-1&&(a=1/a),new F(h?1/a:a);D&&(a=i(D/l+2))}for(c?(r=new F(.5),u=w(e)):u=e%2,h&&(e.s=1),f=new F(v);;){if(u){if(!(f=f.times(d)).c)break;a?f.c.length>a&&(f.c.length=a):o&&(f=f.mod(t))}if(c){if(q(e=e.times(r),e.e+1,1),!e.c[0])break;c=e.e>14,u=w(e)}else{if(!(e=s(e/2)))break;u=e%2}d=d.times(d),a?d.c&&d.c.length>a&&(d.c.length=a):o&&(d=d.mod(t))}return o?f:(h&&(f=v.div(f)),t?f.mod(t):a?q(f,D,N,void 0):f)},L.integerValue=function(e){var t=new F(this);return null==e?e=N:y(e,0,8),q(t,t.e+1,e)},L.isEqualTo=L.eq=L.equals=function(e,t){return 0===_(this,new F(e,t))},L.isFinite=function(){return!!this.c},L.isGreaterThan=L.gt=function(e,t){return _(this,new F(e,t))>0},L.isGreaterThanOrEqualTo=L.gte=function(e,t){return 1===(t=_(this,new F(e,t)))||0===t},L.isInteger=function(){return!!this.c&&d(this.e/l)>this.c.length-2},L.isLessThan=L.lt=function(e,t){return _(this,new F(e,t))<0},L.isLessThanOrEqualTo=L.lte=function(e,t){return-1===(t=_(this,new F(e,t)))||0===t},L.isNaN=function(){return!this.s},L.isNegative=function(){return this.s<0},L.isPositive=function(){return this.s>0},L.isZero=function(){return!!this.c&&0==this.c[0]},L.minus=function(e,t){var r,i,s,n,o=this,c=o.s;if(t=(e=new F(e,t)).s,!c||!t)return new F(NaN);if(c!=t)return e.s=-t,o.plus(e);var h=o.e/l,u=e.e/l,f=o.c,g=e.c;if(!h||!u){if(!f||!g)return f?(e.s=-t,e):new F(g?o:NaN);if(!f[0]||!g[0])return g[0]?(e.s=-t,e):new F(f[0]?o:3==N?-0:0)}if(h=d(h),u=d(u),f=f.slice(),c=h-u){for((n=c<0)?(c=-c,s=f):(u=h,s=g),s.reverse(),t=c;t--;s.push(0));s.reverse()}else for(i=(n=(c=f.length)<(t=g.length))?c:t,c=t=0;t<i;t++)if(f[t]!=g[t]){n=f[t]<g[t];break}if(n&&(s=f,f=g,g=s,e.s=-e.s),(t=(i=g.length)-(r=f.length))>0)for(;t--;f[r++]=0);for(t=a-1;i>c;){if(f[--i]<g[i]){for(r=i;r&&!f[--r];f[r]=t);--f[r],f[i]+=a}f[i]-=g[i]}for(;0==f[0];f.splice(0,1),--u);return f[0]?Z(e,f,u):(e.s=3==N?-1:1,e.c=[e.e=0],e)},L.modulo=L.mod=function(e,t){var r,i,s=this;return e=new F(e,t),!s.c||!e.s||e.c&&!e.c[0]?new F(NaN):!e.c||s.c&&!s.c[0]?new F(s):(9==K?(i=e.s,e.s=1,r=E(s,e,0,3),e.s=i,r.s*=i):r=E(s,e,0,K),(e=s.minus(r.times(e))).c[0]||1!=K||(e.s=s.s),e)},L.multipliedBy=L.times=function(e,t){var r,i,s,n,o,c,h,f,g,_,y,A,w,p,m,E=this,S=E.c,U=(e=new F(e,t)).c;if(!(S&&U&&S[0]&&U[0]))return!E.s||!e.s||S&&!S[0]&&!U||U&&!U[0]&&!S?e.c=e.e=e.s=null:(e.s*=E.s,S&&U?(e.c=[0],e.e=0):e.c=e.e=null),e;for(i=d(E.e/l)+d(e.e/l),e.s*=E.s,(h=S.length)<(_=U.length)&&(w=S,S=U,U=w,s=h,h=_,_=s),s=h+_,w=[];s--;w.push(0));for(p=a,m=u,s=_;--s>=0;){for(r=0,y=U[s]%m,A=U[s]/m|0,n=s+(o=h);n>s;)r=((f=y*(f=S[--o]%m)+(c=A*f+(g=S[o]/m|0)*y)%m*m+w[n]+r)/p|0)+(c/m|0)+A*g,w[n--]=f%p;w[n]=r}return r?++i:w.splice(0,1),Z(e,w,i)},L.negated=function(){var e=new F(this);return e.s=-e.s||null,e},L.plus=function(e,t){var r,i=this,s=i.s;if(t=(e=new F(e,t)).s,!s||!t)return new F(NaN);if(s!=t)return e.s=-t,i.minus(e);var n=i.e/l,o=e.e/l,c=i.c,h=e.c;if(!n||!o){if(!c||!h)return new F(s/0);if(!c[0]||!h[0])return h[0]?e:new F(c[0]?i:0*s)}if(n=d(n),o=d(o),c=c.slice(),s=n-o){for(s>0?(o=n,r=h):(s=-s,r=c),r.reverse();s--;r.push(0));r.reverse()}for((s=c.length)-(t=h.length)<0&&(r=h,h=c,c=r,t=s),s=0;t;)s=(c[--t]=c[t]+h[t]+s)/a|0,c[t]=a===c[t]?0:c[t]%a;return s&&(c=[s].concat(c),++o),Z(e,c,o)},L.precision=L.sd=function(e,t){var r,i,s,n=this;if(null!=e&&e!==!!e)return y(e,1,f),null==t?t=N:y(t,0,8),q(new F(n),e,t);if(!(r=n.c))return null;if(i=(s=r.length-1)*l+1,s=r[s]){for(;s%10==0;s/=10,i--);for(s=r[0];s>=10;s/=10,i++);}return e&&n.e+1>i&&(i=n.e+1),i},L.shiftedBy=function(e){return y(e,-c,c),this.times("1e"+e)},L.squareRoot=L.sqrt=function(){var e,t,r,i,s,n=this,o=n.c,a=n.s,l=n.e,c=H+4,h=new F("0.5");if(1!==a||!o||!o[0])return new F(!a||a<0&&(!o||o[0])?NaN:o?n:1/0);if(0==(a=Math.sqrt(+n))||a==1/0?(((t=g(o)).length+l)%2==0&&(t+="0"),a=Math.sqrt(t),l=d((l+1)/2)-(l<0||l%2),r=new F(t=a==1/0?"1e"+l:(t=a.toExponential()).slice(0,t.indexOf("e")+1)+l)):r=new F(a+""),r.c[0])for((a=(l=r.e)+c)<3&&(a=0);;)if(s=r,r=h.times(s.plus(E(n,s,c,1))),g(s.c).slice(0,a)===(t=g(r.c)).slice(0,a)){if(r.e<l&&--a,"9999"!=(t=t.slice(a-3,a+1))&&(i||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(r,r.e+H+2,1),e=!r.times(r).eq(n));break}if(!i&&(q(s,s.e+H+2,0),s.times(s).eq(n))){r=s;break}c+=4,a+=4,i=1}return q(r,r.e+H+1,N,e)},L.toExponential=function(e,t){return null!=e&&(y(e,0,f),e++),G(this,e,t,1)},L.toFixed=function(e,t){return null!=e&&(y(e,0,f),e=e+this.e+1),G(this,e,t)},L.toFormat=function(e,t){var r=this.toFixed(e,t);if(this.c){var i,s=r.split("."),n=+W.groupSize,o=+W.secondaryGroupSize,a=W.groupSeparator,l=s[0],c=s[1],h=this.s<0,u=h?l.slice(1):l,f=u.length;if(o&&(i=n,n=o,o=i,f-=i),n>0&&f>0){for(i=f%n||n,l=u.substr(0,i);i<f;i+=n)l+=a+u.substr(i,n);o>0&&(l+=a+u.slice(i)),h&&(l="-"+l)}r=c?l+W.decimalSeparator+((o=+W.fractionGroupSize)?c.replace(new RegExp("\\d{"+o+"}\\B","g"),"$&"+W.fractionGroupSeparator):c):l}return r},L.toFraction=function(e){var t,r,i,s,o,a,c,u,f,d,_,y,A=this,w=A.c;if(null!=e&&(!(u=new F(e)).isInteger()&&(u.c||1!==u.s)||u.lt(v)))throw Error(n+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+e);if(!w)return A.toString();for(r=new F(v),d=i=new F(v),s=f=new F(v),y=g(w),a=r.e=y.length-A.e-1,r.c[0]=h[(c=a%l)<0?l+c:c],e=!e||u.comparedTo(r)>0?a>0?r:d:u,c=O,O=1/0,u=new F(y),f.c[0]=0;_=E(u,r,0,1),1!=(o=i.plus(_.times(s))).comparedTo(e);)i=s,s=o,d=f.plus(_.times(o=d)),f=o,r=u.minus(_.times(o=r)),u=o;return o=E(e.minus(i),s,0,1),f=f.plus(o.times(d)),i=i.plus(o.times(s)),f.s=d.s=A.s,t=E(d,s,a*=2,N).minus(A).abs().comparedTo(E(f,i,a,N).minus(A).abs())<1?[d.toString(),s.toString()]:[f.toString(),i.toString()],O=c,t},L.toNumber=function(){return+this},L.toPrecision=function(e,t){return null!=e&&y(e,1,f),G(this,e,t,2)},L.toString=function(e){var t,r=this,i=r.s,s=r.e;return null===s?i?(t="Infinity",i<0&&(t="-"+t)):t="NaN":(t=g(r.c),null==e?t=s<=M||s>=C?p(t,s):m(t,s,"0"):(y(e,2,x.length,"Base"),t=S(m(t,s,"0"),10,e,i,!0)),i<0&&r.c[0]&&(t="-"+t)),t},L.valueOf=L.toJSON=function(){var e,t=this,r=t.e;return null===r?t.toString():(e=g(t.c),e=r<=M||r>=C?p(e,r):m(e,r,"0"),t.s<0?"-"+e:e)},L._isBigNumber=!0,null!=t&&F.set(t),F}()).default=t.BigNumber=t,e.BigNumber=t}(Class.scope);const BigNumber=Class.scope.BigNumber;BigNumber.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 BigNumber("ffffffffffffffffffffffffffffffff",16),Class.register(NumberUtils);class BufferUtils{static toAscii(e){const t=BufferUtils._toUint8View(e);let r="";for(let e=0;e<t.length;e+=8192)r+=String.fromCharCode.apply(null,t.subarray(e,e+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(void 0===BufferUtils._ISO_8859_15_DECODER)try{BufferUtils._ISO_8859_15_DECODER=new TextDecoder("iso-8859-15")}catch(e){throw BufferUtils._ISO_8859_15_DECODER=null,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 s=[];for(let n=t;n<r;n+=3)i=(e[n]<<16&16711680)+(e[n+1]<<8&65280)+(255&e[n+2]),s.push(BufferUtils._tripletToBase64(i));return s.join("")}static _base64fromByteArray(e){let t;const r=e.length,i=r%3;let s="";const n=[];for(let t=0,s=r-i;t<s;t+=16383)n.push(BufferUtils._base64encodeChunk(e,t,t+16383>s?s:t+16383));return 1===i?(t=e[r-1],s+=BufferUtils._BASE64_LOOKUP[t>>2],s+=BufferUtils._BASE64_LOOKUP[t<<4&63],s+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],s+=BufferUtils._BASE64_LOOKUP[t>>10],s+=BufferUtils._BASE64_LOOKUP[t>>4&63],s+=BufferUtils._BASE64_LOOKUP[t<<2&63],s+="="),n.push(s),n.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(e){}return BufferUtils._base64fromByteArray(BufferUtils._toUint8View(e))}static fromBase64(e,t){const r=new Uint8Array(atob(e).split("").map(e=>e.charCodeAt(0)));if(void 0!==t&&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,s,n=3,o=0,a="";for(s=0;s<e.length;s++)a+=t[31&(i=o|(r=e[s])>>n)],n>5&&(a+=t[31&(i=r>>(n-=5))]),o=r<<(n=5-n),n=8-n;for(3!==n&&(a+=t[31&o]);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,s=8,n=0,o=[];return e.toUpperCase().split("").forEach(e=>{33===t.length&&e===t[32]||(i=255&r[e],(s-=5)>0?n|=i<<s:s<0?(o.push(n|i>>-s),n=i<<(s+=8)&255):(o.push(n|i),s=8,n=0))}),8!==s&&0!==n&&o.push(n),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){if(e=e.trim(),!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 s=e.charCodeAt(i);s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&i+1<e.length&&56320==(64512&e.charCodeAt(i+1))?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++i)),t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128)}return 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(void 0===BufferUtils._UTF8_ENCODER)try{BufferUtils._UTF8_ENCODER=new TextEncoder}catch(e){throw BufferUtils._UTF8_ENCODER=null,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(e){}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(e){}try{return BufferUtils.fromBase64(e,t)}catch(e){}throw new Error("Invalid buffer format")}static concatTypedArrays(e,t){const r=new e.constructor(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}static equals(e,t){const r=BufferUtils._toUint8View(e),i=BufferUtils._toUint8View(t);if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])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=[],s="",n=0;for(;n<e.length&&!e[n];n++)s+=t[0];for(;n<e.length;n++){let t=e[n];for(r=0;r in i||t;){let e=i[r]?(i[r]<<8)+t:t;t=e/58|0,i[r]=e%58,r++}}for(;r--;)s+=t[i[r]];return s}static fromBase58(e,t=BufferUtils.BASE58_ALPHABET){let r,i=[],s=[],n=0;for(;n<e.length&&!t.indexOf(e[n]);n++)i.push(0);for(;n<e.length;n++){let i=t.indexOf(e[n]);if(i<0)return"";for(r=0;r in s||i;){let e=s[r]?58*s[r]+i:i;i=e>>8,s[r]=e%256,r++}}for(;r--;)i.push(s[r]);return new Uint8Array(i)}static toBase58Check(e,t=128,r,i=BufferUtils.BASE58_ALPHABET){let s;s=new SerialBuffer(r?[255&t,...e,255&r]:[255&t,...e]);const n=Hash.computeSha256(Hash.computeSha256(s)).subarray(0,4),o=new SerialBuffer([...s,...n]);return BufferUtils.toBase58(o,i)}static fromBase58Check(e,t=!1,r=BufferUtils.BASE58_ALPHABET){const i=BufferUtils.fromBase58(e,r),s=t?-5:-4;return new Uint8Array(i.slice(1,s))}}BufferUtils.BASE64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BufferUtils.BASE32_ALPHABET={RFC4648:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",RFC4648_HEX:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",KRYPTON:"0123456789ABCDEFGHJKLMNPQRSTUVXY"},BufferUtils.HEX_ALPHABET="0123456789abcdef",BufferUtils._BASE64_LOOKUP=[];for(let e=0,t=BufferUtils.BASE64_ALPHABET.length;e<t;++e)BufferUtils._BASE64_LOOKUP[e]=BufferUtils.BASE64_ALPHABET[e];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);return this._readPos+=e,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);return this._readPos+=2,e}writeUint16(e){this._view.setUint16(this._writePos,e),this._writePos+=2}readUint32(){const e=this._view.getUint32(this._readPos);return this._readPos+=4,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");return this._readPos+=8,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 BigNumber("1000000000000000000000000",16),t=new BigNumber("10000000000000000",16),r=new BigNumber("100000000",16),i=this._view.getUint32(this._readPos),s=this._view.getUint32(this._readPos+4),n=this._view.getUint32(this._readPos+8),o=this._view.getUint32(this._readPos+12),a=e.times(i).plus(t.times(s)).plus(r.times(n)).plus(o);if(!NumberUtils.isUint128(a))throw new Error("Malformed value");return this._readPos+=16,a}writeUint128(e){if(!NumberUtils.isUint128(e))throw new Error("Malformed value");const t=new BigNumber("1000000000000000000000000",16),r=new BigNumber("10000000000000000",16),i=new BigNumber("100000000",16),s=e.idiv(t),n=e.mod(t).idiv(r),o=e.mod(r).idiv(i),a=e.mod(i);this._view.setUint32(this._writePos,s.toNumber()),this._view.setUint32(this._writePos+4,n.toNumber()),this._view.setUint32(this._writePos+8,o.toNumber()),this._view.setUint32(this._writePos+12,a.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");e<253?this.writeUint8(e):e<=65535?(this.writeUint8(253),this.writeUint16(e)):e<=4294967295?(this.writeUint8(254),this.writeUint32(e)):(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);return this._readPos+=8,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 t of e)r.set(t,i),i+=t.length;return r}}SerialBuffer.EMPTY=new SerialBuffer(0),Class.register(SerialBuffer);class MinerWorker{async multiMine(e,t,r,i){}}Class.register(MinerWorker);class MinerWorkerImpl extends(IWorker.Stub(MinerWorker)){constructor(){super(),this._superInit=super.init}async init(e){await this._superInit.call(this,e),PlatformUtils.isBrowser()&&await WasmHelper.doImportBrowser()}async multiMine(e,t,r,i){const s=new Uint8Array(32);let n,o;try{n=Module._malloc(s.length),o=Module._malloc(e.length),Module.HEAPU8.set(e,o);const a=Module._krypton_argon2_target(n,o,e.length,t,r,i,512);return a!==i&&(s.set(new Uint8Array(Module.HEAPU8.buffer,n,s.length)),{hash:s,nonce:a})}catch(e){throw Log.w(MinerWorkerImpl,e),e}finally{void 0!==n&&Module._free(n),void 0!==o&&Module._free(o)}}}IWorker.prepareForWorkerUse(MinerWorker,new MinerWorkerImpl);class MinerWorkerPool extends(IWorker.Pool(MinerWorker)){constructor(e=1){super(e=>IWorker.startWorkerForProxy(MinerWorker,e),"miner",e),this._miningEnabled=!1,this._activeNonces=[],this._block=null,this._noncesPerRun=256,this._observable=new Observable,this._shareCompact=Policy.BLOCK_TARGET_MAX,this._runsPerCycle=1/0,this._cycleWait=100,this._superUpdateToSize=super._updateToSize,PlatformUtils.isNodeJs()&&(Log.i(MinerWorkerPool,`Using add-on optimized for instruction set: ${cpuSupport}`),this.multiMine=function(e,t,r,i){return new Promise((s,n)=>{NodeNative.node_argon2_target_async(async t=>{try{if(t===i)s(!1);else{e.writePos-=4,e.writeUint32(t);const r=await(await CryptoWorker.getInstanceAsync()).computeArgon2d(e);s({hash:r,nonce:t})}}catch(e){n(e)}},e,t,r,i,512)})})}get noncesPerRun(){return this._noncesPerRun}set noncesPerRun(e){this._noncesPerRun=e}get runsPerCycle(){return this._runsPerCycle}set runsPerCycle(e){this._runsPerCycle=e}get cycleWait(){return this._cycleWait}set cycleWait(e){this._cycleWait=e}on(e,t){return this._observable.on(e,t)}off(e,t){this._observable.off(e,t)}async startMiningOnBlock(e,t){if(this._block=e,this._shareCompact=t||e.nBits,this._miningEnabled)this._activeNonces=[{minNonce:0,maxNonce:0}];else{await this._updateToSize(),this._activeNonces=[],this._miningEnabled=!0;for(let e=0;e<this.poolSize;++e)this._startMiner()}}stop(){this._miningEnabled=!1}async _updateToSize(){for(PlatformUtils.isNodeJs()||await this._superUpdateToSize.call(this);this._miningEnabled&&this._activeNonces.length<this.poolSize;)this._startMiner()}_startMiner(){if(this._activeNonces.length>=this.poolSize)return;const e=0===this._activeNonces.length?0:Math.max.apply(null,this._activeNonces.map(e=>e.maxNonce)),t={minNonce:e,maxNonce:e+this._noncesPerRun};this._activeNonces.push(t),this._singleMiner(t).catch(e=>Log.e(MinerWorkerPool,e))}async _singleMiner(e){let t=0;for(;this._miningEnabled&&(IWorker.areWorkersAsync||PlatformUtils.isNodeJs()||0===t)&&t<this._runsPerCycle;){t++;const r=this._block,i=await this.multiMine(r.header.serialize(),this._shareCompact,e.minNonce,e.maxNonce);if(i){const e=new Hash(i.hash);this._observable.fire("share",{block:r,nonce:i.nonce,hash:e})}else this._observable.fire("no-share",{nonce:e.maxNonce});if(this._activeNonces.length>this.poolSize)return void this._activeNonces.splice(this._activeNonces.indexOf(e),1);{const t=Math.max.apply(null,this._activeNonces.map(e=>e.maxNonce)),r={minNonce:t,maxNonce:t+this._noncesPerRun};this._activeNonces.splice(this._activeNonces.indexOf(e),1,r),e=r}}this._miningEnabled&&setTimeout(()=>this._singleMiner(e),this._cycleWait)}}Class.register(MinerWorkerPool);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","{WORKER_WASM_HASH}"):await WasmHelper.importScriptBrowser("worker-js.js","Module","{WORKER_JS_HASH}")})();try{await WasmHelper._importBrowserPromise}catch(e){throw WasmHelper._importBrowserPromise=null,e}}static async importWasm(e,t="Module"){return WasmHelper.importWasmBrowser(e,t)}static async importWasmBrowser(e,t="Module"){return e=WasmHelper._adjustWasmPath(e),WasmHelper._global.WebAssembly?new Promise(r=>{try{const i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(){WasmHelper._global[t]=WasmHelper._global[t]||{},WasmHelper._global[t].wasmBinary=i.response,r(!0)},i.onerror=function(){Log.w(WasmHelper,`Failed to access WebAssembly module ${e}`),r(!1)},i.send(null)}catch(t){Log.w(WasmHelper,`Failed to access WebAssembly module ${e}`),r(!1)}}):(Log.w(WasmHelper,"No support for WebAssembly available."),Promise.resolve(!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(s,n)=>{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)return void n("No way to load scripts.");WasmHelper._global[t]=require(e)(i)}await o,i.asm&&!WasmHelper._global[t].asm&&(WasmHelper._global[t]=i),s(!0)})}static fireModuleLoaded(e="Module"){"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,null!=t&&(i.integrity=t,i.crossOrigin="anonymous"),r.appendChild(i)}static _adjustWasmPath(e){return"undefined"!=typeof Krypton&&Krypton._path&&(e=`${Krypton._path}${e}`),"string"==typeof __dirname&&-1===e.indexOf("/")&&(e=`${__dirname}/${e}`),e}static _adjustScriptPath(e){return"undefined"!=typeof Krypton&&Krypton._path&&(e=`${Krypton._path}${e}`),"string"==typeof __dirname&&-1===e.indexOf("/")&&(e=`${__dirname}/${e}`),e}static get _global(){return"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:null}}WasmHelper._moduleLoadedCallbacks={},Class.register(WasmHelper);class GenesisConfig{}Class.register(GenesisConfig);class ArrayUtils{static randomElement(e){return e[Math.floor(Math.random()*e.length)]}static subarray(e,t,r){function i(e,t,r){return e<t?t:e>r?r:e}void 0===t&&(t=0),void 0===r&&(r=e.byteLength),t=i(t,0,e.byteLength);let s=(r=i(r,0,e.byteLength))-t;return s<0&&(s=0),new Uint8Array(e.buffer,e.byteOffset+t,s)}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 s=Array.from(new Array(t),(e,r)=>t-r-1);for(;;){let n=t-1,o=!1;for(n of s)if(i[n]!==n+r-t){o=!0;break}if(!o)return;i[n]+=1;for(const e of Array.from(new Array(t-n-1),(e,t)=>n+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 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),s=e.slice(0,i),n=e.slice(i),o=MerkleTree._computeRoot(s,t),a=MerkleTree._computeRoot(n,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),s=[];return MerklePath._compute(e,i,s,r),new MerklePath(s)}static _compute(e,t,r,i){const s=e.length;let n;if(0===s)return{containsLeaf:!1,inner:n=Hash.light(new Uint8Array(0))};if(1===s)return{containsLeaf:(n=i(e[0])).equals(t),inner:n};const o=Math.round(s/2),a=e.slice(0,o),l=e.slice(o),{containsLeaf:c,inner:h}=MerklePath._compute(a,t,r,i),{containsLeaf:u,inner:f}=MerklePath._compute(l,t,r,i);return n=Hash.light(BufferUtils.concatTypedArrays(h.serialize(),f.serialize())),c?(r.push(new MerklePathNode(f,!1)),{containsLeaf:!0,inner:n}):u?(r.push(new MerklePathNode(h,!0)),{containsLeaf:!0,inner:n}):{containsLeaf:!1,inner:n}}computeRoot(e,t=MerkleTree._hash){let r=t(e);for(const e of this._nodes){const t=e.left,i=e.hash,s=new SerialBuffer(2*i.serializedSize);t&&i.serialize(s),r.serialize(s),t||i.serialize(s),r=Hash.light(s)}return r}static _compress(e){const t=e.length,r=Math.ceil(t/8),i=new Uint8Array(r);for(let r=0;r<t;r++)e[r].left&&(i[Math.floor(r/8)]|=128>>>r%8);return i}static unserialize(e){const t=e.readUint8(),r=Math.ceil(t/8),i=e.read(r),s=[];for(let r=0;r<t;r++){const t=0!=(i[Math.floor(r/8)]&128>>>r%8),n=e.readUint8(),o=Hash.unserialize(e,n);s.push(new MerklePathNode(o,t))}return new MerklePath(s)}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 Policy{static coinsToSatoshis(e){return new BigNumber(e).times(Policy.SATOSHIS_PER_COIN).integerValue()}static satoshisToCoins(e){return new BigNumber(e).div(Policy.SATOSHIS_PER_COIN)}static blockRewardAt(e){if(e<=0)return new BigNumber(0);const t=Math.min(Math.floor((e-1)/Policy.HALVING_INTERVAL),Policy.HALVING_TARGET_MAX-1);return new BigNumber(Policy.INITIAL_BLOCK_REWARD).idiv(Math.pow(2,t))}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,s=e-Policy.HALVING_INTERVAL,n=1;for(;s>Policy.HALVING_INTERVAL&&n<Policy.HALVING_TARGET_MAX;)i+=Policy.HALVING_INTERVAL*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-n),s-=Policy.HALVING_INTERVAL,n+=1;return n>=Policy.HALVING_TARGET_MAX?i+=(s-1)*Policy.INITIAL_BLOCK_TIME:i+=(s-1)*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-n),i}static targetedTimeBlockRange(e,t){const r=e>1?e:1,i=t>1?t:1;if(r>=i)return 0;const s=Policy.HALVING_INTERVAL*Policy.HALVING_TARGET_MAX;let n=i-r;if(i<=Policy.BLOCK_TIME_MILESTONE||r>s)return n*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:n*o;const a=Math.floor((r-1)/Policy.HALVING_INTERVAL);let l,c=Math.floor((i-1)/Policy.HALVING_INTERVAL);if(a===c)return n*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-a);let h,u=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>s)c=Policy.HALVING_TARGET_MAX,h=(i-s-1)*Policy.INITIAL_BLOCK_TIME;else{h=(i-c*Policy.HALVING_INTERVAL-1)*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-c)}for(let e=a+1;e<c;e++)u+=Policy.HALVING_INTERVAL*Policy.BLOCK_TIME_MULTIPLE*(Policy.HALVING_TARGET_MAX-e);return l+u+h}static txFee(e){if(e<=1)return new BigNumber(0);const t=Math.floor((e-1)/Policy.TX_FEE_CHANGING_INTERVAL);return t<Policy.TX_FEE_CHANGING_TOTAL_NUMBER?new BigNumber(Policy.INITIAL_TX_FEE).div(Math.pow(10,t)):new BigNumber(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 BigNumber(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){return(e=e||new SerialBuffer(this.serializedSize)).write(this._obj),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(e){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(e){}try{return Hash.fromBase64(e)}catch(e){}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));return NodeNative.node_blake2(t,new Uint8Array(e)),t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.BLAKE2B),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e);const n=Module._krypton_blake2(i,s,e.length);if(0!==n)throw n;const o=new Uint8Array(r);return o.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),o}catch(e){throw Log.w(Hash,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}static computeSha256(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA256));return NodeNative.node_sha256(t,new Uint8Array(e)),t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.SHA256),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),Module._krypton_sha256(i,s,e.length);const n=new Uint8Array(r);return n.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),n}catch(e){throw Log.w(Hash,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}static computeSha512(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA512));return NodeNative.node_sha512(t,new Uint8Array(e)),t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.SHA512),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),Module._krypton_sha512(i,s,e.length);const n=new Uint8Array(r);return n.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),n}catch(e){throw Log.w(Hash,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}static computeRipemd160(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.RIPEMD160));return NodeNative.node_ripemd160(t,new Uint8Array(e)),t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.RIPEMD160),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),Module._ripemd160(s,e.length,i);const n=new Uint8Array(r);return n.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),n}catch(e){throw Log.w(Hash,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}static computeKeccak256(e){if(PlatformUtils.isNodeJs()){const t=new Uint8Array(Hash.getSize(Hash.Algorithm.KECCAK256));return NodeNative.node_keccak256(t,new Uint8Array(e)),t}{let t;try{t=Module.stackSave();const r=Hash.getSize(Hash.Algorithm.KECCAK256),i=Module.stackAlloc(r),s=Module.stackAlloc(e.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),Module._keccak256(s,e.length,i);const n=new Uint8Array(r);return n.set(new Uint8Array(Module.HEAPU8.buffer,i,r)),n}catch(e){throw Log.w(Hash,e),e}finally{void 0!==t&&Module.stackRestore(t)}}}}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 PublicKey extends Serializable{static copy(e){return e?new PublicKey(new Uint8Array(e._obj)):e}constructor(e){if(super(),!(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){return(e=e.slice()).sort((e,t)=>e.compare(t)),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(e){throw new Error("Invalid public key format")}}serialize(e){return(e=e||new SerialBuffer(this.serializedSize)).write(this._obj),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);if(CryptoWorker.lib.getRandomValues(t),PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(t);const r=new Uint8Array(PublicKey.COMPRESSED_SIZE);return NodeNative.node_secp256k1_pubkey_compress(r,new Uint8Array(e)),NodeNative.node_secp256k1_ctx_release(),r}{let r;try{r=Module.stackSave();const i=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,i,32).set(t),Module._secp256k1_ctx_init(i);const s=Module.stackAlloc(PublicKey.COMPRESSED_SIZE),n=new Uint8Array(Module.HEAP8.buffer,s,PublicKey.COMPRESSED_SIZE),o=Module.stackAlloc(PublicKey.SIZE);new Uint8Array(Module.HEAP8.buffer,o,PublicKey.SIZE).set(e),Module._secp256k1_pubkey_compress(s,o);const a=new Uint8Array(PublicKey.COMPRESSED_SIZE);return a.set(n),a}catch(e){throw Log.w(PublicKey,e),e}finally{Module._secp256k1_ctx_release(),void 0!==r&&Module.stackRestore(r)}}}static _publicKeyDerive(e){if(e.byteLength!==PrivateKey.SIZE)throw Error("Wrong buffer size.");const t=new Uint8Array(32);if(CryptoWorker.lib.getRandomValues(t),PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(t);const r=new Uint8Array(PublicKey.SIZE);return NodeNative.node_secp256k1_pubkey_create(r,new Uint8Array(e)),NodeNative.node_secp256k1_ctx_release(),r}{let r;try{r=Module.stackSave();const i=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,i,32).set(t),Module._secp256k1_ctx_init(i);const s=Module.stackAlloc(PublicKey.SIZE),n=new Uint8Array(Module.HEAP8.buffer,s,PublicKey.SIZE),o=Module.stackAlloc(e.length),a=new Uint8Array(Module.HEAP8.buffer,o,PrivateKey.SIZE);a.set(e),Module._secp256k1_pubkey_create(s,PublicKey.SIZE,o),a.fill(0);const l=new Uint8Array(PublicKey.SIZE);return l.set(n),l}catch(e){throw Log.w(PublicKey,e),e}finally{Module._secp256k1_ctx_release(),void 0!==r&&Module.stackRestore(r)}}}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 r=0;r<e.length;++r)t.set(e[r],r*PublicKey.SIZE);if(PlatformUtils.isNodeJs()){const r=new Uint8Array(Hash.getSize(Hash.Algorithm.SHA256));return NodeNative.node_secp256k1_hash_pubkeys(r,t,e.length,PublicKey.SIZE),r}{let r;try{r=Module.stackSave();const i=Hash.getSize(Hash.Algorithm.SHA256),s=Module.stackAlloc(i),n=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,n,t.length).set(t),Module._secp256k1_hash_pubkeys(s,n,e.length,PublicKey.SIZE);const o=new Uint8Array(i);return o.set(new Uint8Array(Module.HEAPU8.buffer,s,i)),o}catch(e){throw Log.w(PublicKey,e),e}finally{void 0!==r&&Module.stackRestore(r)}}}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);return NodeNative.node_secp256k1_delinearize_pubkey(r,new Uint8Array(t),new Uint8Array(e)),r}{let r;try{r=Module.stackSave();const i=Module.stackAlloc(PublicKey.SIZE),s=Module.stackAlloc(e.length),n=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),new Uint8Array(Module.HEAPU8.buffer,n,t.length).set(t),Module._secp256k1_delinearize_pubkey(i,n,s);const o=new Uint8Array(PublicKey.SIZE);return o.set(new Uint8Array(Module.HEAPU8.buffer,i,PublicKey.SIZE)),o}catch(e){throw Log.w(PublicKey,e),e}finally{void 0!==r&&Module.stackRestore(r)}}}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 t=0;t<e.length;++t)r.set(e[t],t*PublicKey.SIZE);if(PlatformUtils.isNodeJs()){const i=new Uint8Array(PublicKey.SIZE);return NodeNative.node_secp256k1_aggregate_delinearized_publkeys(i,new Uint8Array(t),r,e.length,PublicKey.SIZE),i}{let i;try{i=Module.stackSave();const s=Module.stackAlloc(PublicKey.SIZE),n=Module.stackAlloc(r.length),o=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,n,r.length).set(r),new Uint8Array(Module.HEAPU8.buffer,o,t.length).set(t),Module._secp256k1_aggregate_delinearized_publkeys(s,o,n,e.length,PublicKey.SIZE);const a=new Uint8Array(PublicKey.SIZE);return a.set(new Uint8Array(Module.HEAPU8.buffer,s,PublicKey.SIZE)),a}catch(e){throw Log.w(PublicKey,e),e}finally{void 0!==i&&Module.stackRestore(i)}}}}PublicKey.COMPRESSED_SIZE=33,PublicKey.SIZE=65,Class.register(PublicKey);class Signature extends Serializable{static copy(e){if(!e)return e;const t=new Uint8Array(e._obj);return new Signature(t)}constructor(e){if(super(),!(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(e){throw new Error("Invalid signature format")}}serialize(e){return(e=e||new SerialBuffer(this.serializedSize)).write(this._obj),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),s=t.slice(PartialSignature.HALF_SIZE),n=Signature._scalarsAdd(i,s);return BufferUtils.concatTypedArrays(r,n)})}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);return NodeNative.node_secp256k1_add_scalars(r,new Uint8Array(e),new Uint8Array(t)),r}{let r;try{r=Module.stackSave();const i=Module.stackAlloc(PartialSignature.HALF_SIZE),s=Module.stackAlloc(e.length),n=Module.stackAlloc(t.length);new Uint8Array(Module.HEAPU8.buffer,s,e.length).set(e),new Uint8Array(Module.HEAPU8.buffer,n,t.length).set(t),Module._secp256k1_add_scalars(i,s,n);const o=new Uint8Array(PartialSignature.HALF_SIZE);return o.set(new Uint8Array(Module.HEAPU8.buffer,i,PartialSignature.HALF_SIZE)),o}catch(e){throw Log.w(Signature,e),e}finally{void 0!==r&&Module.stackRestore(r)}}}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);if(CryptoWorker.lib.getRandomValues(i),PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(i);const s=new Uint8Array(Signature.SIZE);return NodeNative.node_secp256k1_schnorr_sign(s,new Uint8Array(r),new Uint8Array(t),new Uint8Array(e)),NodeNative.node_secp256k1_ctx_release(),s}{let s;try{s=Module.stackSave();const n=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,n,32).set(i),Module._secp256k1_ctx_init(n);const o=Module.stackAlloc(Signature.SIZE),a=new Uint8Array(Module.HEAP8.buffer,o,Signature.SIZE),l=Module.stackAlloc(r.length);new Uint8Array(Module.HEAP8.buffer,l,r.length).set(r);const c=Module.stackAlloc(t.length);new Uint8Array(Module.HEAP8.buffer,c,t.length).set(t);const h=Module.stackAlloc(e.length),u=new Uint8Array(Module.HEAP8.buffer,h,e.length);u.set(e),Module._secp256k1_schnorr_sign(o,l,r.byteLength,c,h),u.fill(0);const f=new Uint8Array(Signature.SIZE);return f.set(a),f}catch(e){throw Log.w(Signature,e),e}finally{Module._secp256k1_ctx_release(),void 0!==s&&Module.stackRestore(s)}}}static _signatureVerify(e,t,r){const i=new Uint8Array(32);if(CryptoWorker.lib.getRandomValues(i),PlatformUtils.isNodeJs()){NodeNative.node_secp256k1_ctx_init(i);const s=!!NodeNative.node_secp256k1_schnorr_verify(new Uint8Array(r),new Uint8Array(t),new Uint8Array(e));return NodeNative.node_secp256k1_ctx_release(),s}{let s;try{s=Module.stackSave();const n=Module.stackAlloc(32);new Uint8Array(Module.HEAP8.buffer,n,32).set(i),Module._secp256k1_ctx_init(n);const o=Module.stackAlloc(e.length);new Uint8Array(Module.HEAP8.buffer,o,e.length).set(e);const a=Module.stackAlloc(t.length);new Uint8Array(Module.HEAP8.buffer,a,t.length).set(t);const l=Module.stackAlloc(r.length);return new Uint8Array(Module.HEAP8.buffer,l,r.length).set(r),!!Module._secp256k1_schnorr_verify(l,a,t.byteLength,o)}catch(e){throw Log.w(Signature,e),e}finally{Module._secp256k1_ctx_release(),void 0!==s&&Module.stackRestore(s)}}}}Signature.SIZE=64,Class.register(Signature);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){if(super(),!(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){return(e=e||new SerialBuffer(this.serializedSize)).write(this._obj),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(e){}try{return Address.fromHex(e)}catch(e){}try{return Address.fromBase64(e)}catch(e){}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);for(t.push(0),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,s=[];for(let e=0;e<6;++e)s.push(i>>5*(5-e)&31);return SerialBuffer.from(s)}static bech32Encode(e,t){const r=SerialBuffer.concat([t,Bech32.createChecksum(e,t)]);let i=e+"1";for(let e=0;e<r.length;++e)i+=Bech32.CHARSET.charAt(r[e]);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 s=(e=e.toLowerCase()).lastIndexOf("1");if(s<1||s+7>e.length||e.length>90)return null;const n=e.substring(0,s),o=[];for(t=s+1;t<e.length;++t){const r=Bech32.CHARSET.indexOf(e.charAt(t));if(-1===r)return null;o.push(r)}return Bech32.verifyChecksum(n,SerialBuffer.from(o))?{hrp:n,data:SerialBuffer.from(o.slice(0,o.length-6))}:null}static convertBits(e,t,r,i=!0){let s=0,n=0;const o=[],a=(1<<r)-1;for(let i=0;i<e.length;++i){const l=e[i];if(l<0||l>>t!=0)return null;for(s=s<<t|l,n+=t;n>=r;)n-=r,o.push(s>>n&a)}if(i)n>0&&o.push(s<<r-n&a);else if(n>=t||s<<r-n&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:s}=r;if(i!==t)throw new Error(`Expected hrp to be ${t} but got ${i}`);const n=Bech32.convertBits(s.slice(1),5,8,!1);if(null===n)throw new Error("Could not convert buffer to bytes");return new SerialBuffer(n)}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,t){const r=new BigNumber(t);if(!NumberUtils.isUint8(e))throw new Error("Malformed type");if(!NumberUtils.isUint128(r))throw new Error("Malformed balance");this._type=e,this._balance=r}static unserialize(e){const t=e.readUint8();if(e.readPos--,!Account.TYPE_MAP.has(t))throw new Error("Unknown account type");return Account.TYPE_MAP.get(t).unserialize(e)}serialize(e){return(e=e||new SerialBuffer(this.serializedSize)).writeUint8(this._type),e.writeUint128(this._balance),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||void 0===e.type)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 PrunedAccount{constructor(e,t){if(!(e instanceof Address))throw new Error("Malformed address");this._address=e,this._account=t}static unserialize(e){return new PrunedAccount(Address.unserialize(e),Account.unserialize(e))}static fromAny(e){return e instanceof PrunedAccount?e:PrunedAccount.fromPlain(e)}static fromPlain(e){return new PrunedAccount(Address.fromAny(e.address),Account.fromAny(e.account))}compare(e){return this._address.compare(e._address)}get address(){return this._address}get account(){return this._account}serialize(e){return e=e||new SerialBuffer(this.serializedSize),this._address.serialize(e),this._account.serialize(e),this}get serializedSize(){return this._address.serializedSize+this._account.serializedSize}hashCode(){return this._address.hashCode()}toPlain(){return{address:this.address.toPlain(),account:this.account.toPlain()}}}Class.register(PrunedAccount);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 t=SignatureProof.unserialize(new SerialBuffer(e));return{signature:t.signature.toHex(),publicKey:t.publicKey.toHex(),signer:t.publicKey.toAddress().toPlain(),pathLength:t.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,t=Address.NULL,r=Address.NULL,i=Hash.NULL,s=1,n=0,o=e){super(Account.Type.HTLC,e);const a=new BigNumber(o);if(!(t instanceof Address))throw new Error("Malformed sender address");if(!(r instanceof Address))throw new Error("Malformed recipient address");if(!(i instanceof Hash))throw new Error("Malformed hashRoot");if(!NumberUtils.isUint8(s)||0===s)throw new Error("Malformed hashCount");if(!NumberUtils.isUint32(n))throw new Error("Malformed timeout");if(!NumberUtils.isUint128(a))throw new Error("Malformed totalAmount");this._sender=t,this._recipient=r,this._hashRoot=i,this._hashCount=s,this._timeout=n,this._totalAmount=a}static create(e,t,r){const i=new SerialBuffer(r.data),s=Address.unserialize(i),n=Address.unserialize(i),o=i.readUint8(),a=Hash.unserialize(i,o),l=i.readUint8(),c=i.readUint32();return new HashedTimeLockedContract(e,s,n,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),s=e.readUint8(),n=Hash.unserialize(e,s),o=e.readUint8(),a=e.readUint32(),l=e.readUint128();return new HashedTimeLockedContract(t,r,i,n,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){return 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),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();return 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(),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 t=new SerialBuffer(e.proof);switch(t.readUint8()){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{const r=t.readUint8(),i=t.readUint8(),s=Hash.unserialize(t,r);let n=Hash.unserialize(t,r);for(let e=0;e<i;++e)n=Hash.compute(n.array,r);if(!s.equals(n))return!1;if(!SignatureProof.unserialize(t).verify(null,e.serializeContent()))return!1;break}case HashedTimeLockedContract.ProofType.EARLY_RESOLVE:if(!SignatureProof.unserialize(t).verify(null,e.serializeContent()))return!1;if(!SignatureProof.unserialize(t).verify(null,e.serializeContent()))return!1;break;case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:if(!SignatureProof.unserialize(t).verify(null,e.serializeContent()))return!1;break;default:return!1}return t.readPos===t.byteLength}catch(e){return!1}}static verifyIncomingTransaction(e){try{const t=new SerialBuffer(e.data);Address.unserialize(t),Address.unserialize(t);const r=t.readUint8();Hash.unserialize(t,r);const i=t.readUint8();return t.readUint32(),0!==i&&(r!==Hash.Algorithm.ARGON2D&&(t.readPos===t.byteLength&&Contract.verifyIncomingTransaction(e)))}catch(e){return!1}}withBalance(e){return new HashedTimeLockedContract(e,this._sender,this._recipient,this._hashRoot,this._hashCount,this._timeout,this._totalAmount)}withOutgoingTransaction(e,t,r,i=!1){const s=new SerialBuffer(e.proof);let n=0;switch(s.readUint8()){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{if(this._timeout<t)throw new Account.ProofError;const e=s.readUint8(),r=s.readUint8();if(!Hash.unserialize(s,e).equals(this._hashRoot))throw new Account.ProofError;if(Hash.unserialize(s,e),!SignatureProof.unserialize(s).isSignedBy(this._recipient))throw new Account.ProofError;n=BigNumber.max(0,this._totalAmount.times(1-r/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>=t)throw new Account.ProofError;if(!SignatureProof.unserialize(s).isSignedBy(this._sender))throw new Account.ProofError;break;default:throw new Account.ProofError}if(!i){if(this._balance.minus(e.value).minus(e.fee).lt(n))throw new Account.BalanceError}return super.withOutgoingTransaction(e,t,r,i)}withIncomingTransaction(e,t,r=!1){throw new Error("Illegal incoming transaction")}static dataToPlain(e){try{const t=new SerialBuffer(e),r=Address.unserialize(t),i=Address.unserialize(t),s=t.readUint8(),n=Hash.unserialize(t,s),o=t.readUint8(),a=t.readUint32();return{sender:r.toPlain(),recipient:i.toPlain(),hashAlgorithm:Hash.Algorithm.toString(s),hashRoot:n.toPlain(),hashCount:o,timeout:a}}catch(t){return Account.dataToPlain(e)}}static proofToPlain(e){try{const t=new SerialBuffer(e),r=t.readUint8();switch(r){case HashedTimeLockedContract.ProofType.REGULAR_TRANSFER:{const e=t.readUint8(),i=t.readUint8(),s=Hash.unserialize(t,e),n=Hash.unserialize(t,e),o=SignatureProof.unserialize(t);return{type:HashedTimeLockedContract.ProofType.toString(r),hashAlgorithm:Hash.Algorithm.toString(e),hashDepth:i,hashRoot:s.toPlain(),preImage:n.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(t),i=SignatureProof.unserialize(t);return{type:HashedTimeLockedContract.ProofType.toString(r),signer:e.publicKey.toAddress().toPlain(),signature:e.signature.toHex(),publicKey:e.publicKey.toHex(),pathLength:e.merklePath.nodes.length,creator:i.publicKey.toAddress().toPlain(),creatorSignature:i.signature.toHex(),creatorPublicKey:i.publicKey.toHex(),creatorPathLength:i.merklePath.nodes.length}}case HashedTimeLockedContract.ProofType.TIMEOUT_RESOLVE:{const e=SignatureProof.unserialize(t);return{type:HashedTimeLockedContract.ProofType.toString(r),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,t=Address.NULL,r=0,i=0,s=e,n=e){super(Account.Type.VESTING,e);const o=new BigNumber(s),a=new BigNumber(n);if(!(t instanceof Address))throw new Error("Malformed owner address");if(!NumberUtils.isUint32(r))throw new Error("Malformed vestingStart");if(!NumberUtils.isUint32(i))throw new Error("Malformed vestingStepBlocks");if(!NumberUtils.isUint128(o))throw new Error("Malformed vestingStepAmount");if(!NumberUtils.isUint128(a))throw new Error("Malformed vestingTotalAmount");this._owner=t,this._vestingStart=r,this._vestingStepBlocks=i,this._vestingStepAmount=o,this._vestingTotalAmount=a}static create(e,t,r){let i,s,n,o;const a=new SerialBuffer(r.data),l=Address.unserialize(a);switch(o=r.value,r.data.length){case Address.SERIALIZED_SIZE+4:i=0,s=a.readUint32(),n=o;break;case Address.SERIALIZED_SIZE+24:i=a.readUint32(),s=a.readUint32(),n=a.readUint128();break;case Address.SERIALIZED_SIZE+40:i=a.readUint32(),s=a.readUint32(),n=a.readUint128(),o=a.readUint128();break;default:throw new Error("Invalid transaction data")}return new VestingContract(e,l,i,s,n,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(),s=e.readUint32(),n=e.readUint128(),o=e.readUint128();return new VestingContract(t,r,i,s,n,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){return 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),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();return e.owner=this.owner.toPlain(),e.vestingStart=this.vestingStart,e.vestingStepBlocks=this.vestingStepBlocks,e.vestingStepAmount=this.vestingStepAmount.toString(),e.vestingTotalAmount=this.vestingTotalAmount.toString(),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)?BigNumber.max(0,this._vestingTotalAmount.minus(this._vestingStepAmount.times(Math.floor((e-this._vestingStart)/this._vestingStepBlocks)))):new BigNumber(0)}static dataToPlain(e){try{let t,r,i,s;const n=new SerialBuffer(e),o=Address.unserialize(n);switch(e.length){case Address.SERIALIZED_SIZE+4:t=0,r=n.readUint32();break;case Address.SERIALIZED_SIZE+24:t=n.readUint32(),r=n.readUint32(),i=n.readUint128().toString();break;case Address.SERIALIZED_SIZE+40:t=n.readUint32(),r=n.readUint32(),i=n.readUint128().toString(),s=n.readUint128().toString();break;default:throw new Error("Invalid transaction data")}return{owner:o.toPlain(),vestingStart:t,vestingStepBlocks:r,vestingStepAmount:i,vestingTotalAmount:s}}catch(t){return Account.dataToPlain(e)}}static proofToPlain(e){try{const t=SignatureProof.unserialize(new SerialBuffer(e));return{signature:t.signature.toHex(),publicKey:t.publicKey.toHex(),signer:t.publicKey.toAddress().toPlain(),pathLength:t.merklePath.nodes.length}}catch(t){return Account.proofToPlain(e)}}}Account.TYPE_MAP.set(Account.Type.VESTING,VestingContract),Class.register(VestingContract);class BlockHeader{constructor(e,t,r,i,s,n,o,a,l=BlockHeader.CURRENT_VERSION){if(!NumberUtils.isUint16(l))throw new Error("Malformed version");if(!Hash.isHash(e))throw new Error("Malformed prevHash");if(!Hash.isHash(t))throw new Error("Malformed interlinkHash");if(!Hash.isHash(r))throw new Error("Malformed bodyHash");if(!Hash.isHash(i))throw new Error("Malformed accountsHash");if(!NumberUtils.isUint32(s)||!BlockUtils.isValidCompact(s))throw new Error("Malformed nBits");if(!NumberUtils.isUint32(n))throw new Error("Invalid height");if(!NumberUtils.isUint32(o))throw new Error("Malformed timestamp");if(!NumberUtils.isUint32(a))throw new Error("Malformed nonce");this._version=l,this._prevHash=e,this._interlinkHash=t,this._bodyHash=r,this._accountsHash=i,this._nBits=s,this._height=n,this._timestamp=o,this._nonce=a}static unserialize(e){const t=e.readUint16();if(!BlockHeader.SUPPORTED_VERSIONS.includes(t))throw new Error(`Unsupported block version ${t}`);const r=Hash.unserialize(e),i=Hash.unserialize(e),s=Hash.unserialize(e),n=Hash.unserialize(e),o=e.readUint32(),a=e.readUint32(),l=e.readUint32(),c=e.readUint32();return new BlockHeader(r,i,s,n,o,a,l,c,t)}serialize(e){return(e=e||new SerialBuffer(this.serializedSize)).writeUint16(this._version),this._prevHash.serialize(e),this._interlinkHash.serialize(e),this._bodyHash.serialize(e),this._accountsHash.serialize(e),e.writeUint32(this._nBits),e.writeUint32(this._height),e.writeUint32(this._timestamp),e.writeUint32(this._nonce),e}get serializedSize(){return 2+this._prevHash.serializedSize+this._interlinkHash.serializedSize+this._bodyHash.serializedSize+this._accountsHash.serializedSize+4+4+4+4}async verifyProofOfWork(e){const t=await this.pow(e);return BlockUtils.isProofOfWork(t,this.target)}isImmediateSuccessorOf(e){if(this.height!==e.height+1)return!1;if(this.timestamp<e.timestamp)return!1;const t=e.hash();return!!this.prevHash.equals(t)}hash(e){return this._hash=this._hash||Hash.light(this.serialize(e)),this._hash}async pow(e){return this._pow=this._pow||await Hash.hard(this.serialize(e)),this._pow}equals(e){return e instanceof BlockHeader&&this._prevHash.equals(e.prevHash)&&this._interlinkHash.equals(e.interlinkHash)&&this._bodyHash.equals(e.bodyHash)&&this._accountsHash.equals(e.accountsHash)&&this._nBits===e.nBits&&this._height===e.height&&this._timestamp===e.timestamp&&this._nonce===e.nonce}toString(){return"BlockHeader{"+`prevHash=${this._prevHash}, `+`interlinkHash=${this._interlinkHash}, `+`bodyHash=${this._bodyHash}, `+`accountsHash=${this._accountsHash}, `+`nBits=${this._nBits.toString(16)}, `+`height=${this._height}, `+`timestamp=${this._timestamp}, `+`nonce=${this._nonce}`+"}"}get version(){return this._version}get prevHash(){return this._prevHash}get interlinkHash(){return this._interlinkHash}get bodyHash(){return this._bodyHash}get accountsHash(){return this._accountsHash}get nBits(){return this._nBits}get target(){return BlockUtils.compactToTarget(this._nBits)}get difficulty(){return BlockUtils.compactToDifficulty(this._nBits)}get height(){return this._height}get timestamp(){return this._timestamp}get nonce(){return this._nonce}set nonce(e){this._nonce=e,this._hash=null,this._pow=null}}BlockHeader.Version={V1:1},BlockHeader.CURRENT_VERSION=BlockHeader.Version.V1,BlockHeader.SUPPORTED_VERSIONS=[BlockHeader.Version.V1],BlockHeader.SERIALIZED_SIZE=146,Class.register(BlockHeader);class BlockInterlink{static _compress(e,t){const r=e.length,i=Math.ceil(r/8),s=new Uint8Array(i);let n=t;const o=[];for(let t=0;t<r;t++){const r=e[t];r.equals(n)?s[Math.floor(t/8)]|=128>>>t%8:(o.push(r),n=r)}return{repeatBits:s,compressed:o}}constructor(e,t,r,i){if(!Array.isArray(e)||!NumberUtils.isUint8(e.length)||e.some(e=>!(e instanceof Hash)))throw new Error("Malformed hashes");if((r||i)&&(!r||!i))throw new Error("Malformed repeatBits/compressed");if(!t&&!r)throw new Error("Either prevHash or repeatBits/compressed required");r||({repeatBits:r,compressed:i}=BlockInterlink._compress(e,t)),this._hashes=e,this._repeatBits=r,this._compressed=i}static unserialize(e,t){const r=e.readUint8(),i=Math.ceil(r/8),s=e.read(i);let n=t;const o=[],a=[];for(let t=0;t<r;t++){0!=(s[Math.floor(t/8)]&128>>>t%8)||(n=Hash.unserialize(e),a.push(n)),o.push(n)}return new BlockInterlink(o,t,s,a)}serialize(e){(e=e||new SerialBuffer(this.serializedSize)).writeUint8(this._hashes.length),e.write(this._repeatBits);for(const t of this._compressed)t.serialize(e);return e}get serializedSize(){return 1+this._repeatBits.length+this._compressed.reduce((e,t)=>e+t.serializedSize,0)}equals(e){return e instanceof BlockInterlink&&this._hashes.length===e._hashes.length&&this._hashes.every((t,r)=>t.equals(e.hashes[r]))}hash(){return this._hash||(this._hash=MerkleTree.computeRoot([this._repeatBits,GenesisConfig.GENESIS_HASH,...this._compressed])),this._hash}get hashes(){return this._hashes}get length(){return this._hashes.length}}Class.register(BlockInterlink);class BlockBody{static getMetadataSize(e){return Address.SERIALIZED_SIZE+1+e.byteLength+2+2}constructor(e,t,r=new Uint8Array(0),i=[]){if(!(e instanceof Address))throw new Error("Malformed minerAddr");if(!Array.isArray(t)||t.some(e=>!(e instanceof Transaction)))throw new Error("Malformed transactions");if(!(r instanceof Uint8Array&&NumberUtils.isUint8(r.byteLength)))throw new Error("Malformed extraData");this._minerAddr=e,this._extraData=r,this._transactions=t,this._prunedAccounts=i,this._hash=null}static unserialize(e){const t=Address.unserialize(e),r=e.readUint8(),i=e.read(r),s=e.readUint16(),n=new Array(s);for(let t=0;t<s;t++)n[t]=Transaction.unserialize(e);const o=e.readUint16(),a=[];for(let t=0;t<o;t++)a.push(PrunedAccount.unserialize(e));return new BlockBody(t,n,i,a)}serialize(e){e=e||new SerialBuffer(this.serializedSize),this._minerAddr.serialize(e),e.writeUint8(this._extraData.byteLength),e.write(this._extraData),e.writeUint16(this._transactions.length);for(const t of this._transactions)t.serialize(e);e.writeUint16(this._prunedAccounts.length);for(const t of this._prunedAccounts)t.serialize(e);return e}get serializedSize(){let e=this._minerAddr.serializedSize+1+this._extraData.byteLength+2+2;for(const t of this._transactions)e+=t.serializedSize;return e+=this._prunedAccounts.reduce((e,t)=>e+t.serializedSize,0)}verify(){let e=null;for(const t of this._transactions){if(e&&e.compareBlockOrder(t)>=0)return Log.w(BlockBody,"Invalid block - transactions not ordered."),!1;if(e=t,!t.verify())return Log.w(BlockBody,"Invalid block - invalid transaction"),!1}let t=null;for(const e of this._prunedAccounts){if(t&&t.compare(e)>=0)return Log.w(BlockBody,"Invalid block - pruned accounts not ordered."),!1;if(t=e,!e.account.isToBePruned())return Log.w(BlockBody,"Invalid block - invalid pruned account"),!1}return!0}getMerkleLeafs(){return[this._minerAddr,this._extraData,...this._transactions,...this.prunedAccounts]}hash(){return this._hash||(this._hash=MerkleTree.computeRoot(this.getMerkleLeafs())),this._hash}equals(e){return e instanceof BlockBody&&this._minerAddr.equals(e.minerAddr)&&BufferUtils.equals(this._extraData,e.extraData)&&this._transactions.length===e.transactions.length&&this._transactions.every((t,r)=>t.equals(e.transactions[r]))}getAddresses(){const e=[this._minerAddr];for(const t of this._transactions)e.push(t.sender,t.recipient);return e}get extraData(){return this._extraData}get minerAddr(){return this._minerAddr}get transactions(){return this._transactions}get transactionCount(){return this._transactions.length}get prunedAccounts(){return this._prunedAccounts}}Class.register(BlockBody);class BlockUtils{static compactToTarget(e){return new BigNumber(16777215&e).times(new BigNumber(2).pow(8*Math.max((e>>24)-3,0)))}static targetToCompact(e){if(!e.isFinite()||e.isNaN())throw new Error("Invalid Target");let t=Math.max(Math.ceil(Math.log2(e.toNumber())/8),1);return e/Math.pow(2,8*(t-1))>=128&&t>=3&&t++,(t<<24)+(e/Math.pow(2,8*Math.max(t-3,0))&16777215)}static getTargetHeight(e){return Math.ceil(Math.log2(e.toNumber()))}static getTargetDepth(e){return BlockUtils.getTargetHeight(Policy.BLOCK_TARGET_MAX)-BlockUtils.getTargetHeight(e)}static compactToDifficulty(e){return Policy.BLOCK_TARGET_MAX.div(BlockUtils.compactToTarget(e))}static difficultyToCompact(e){return BlockUtils.targetToCompact(BlockUtils.difficultyToTarget(e))}static difficultyToTarget(e){return Policy.BLOCK_TARGET_MAX.div(e)}static targetToDifficulty(e){return Policy.BLOCK_TARGET_MAX.div(e)}static hashToTarget(e){return new BigNumber(e.toHex(),16)}static realDifficulty(e){return BlockUtils.targetToDifficulty(BlockUtils.hashToTarget(e))}static getHashDepth(e){return BlockUtils.getTargetDepth(BlockUtils.hashToTarget(e))}static isProofOfWork(e,t){return new BigNumber(e.toHex(),16).lte(t)}static isValidCompact(e){return BlockUtils.isValidTarget(BlockUtils.compactToTarget(e))}static isValidTarget(e){return null!==e&&e.gte(1)&&e.lte(Policy.BLOCK_TARGET_MAX)}static getNextTarget(e,t,r){const i=Policy.difficultyBlockWindow(e.height);Assert.that(e.height-t.height===i||e.height<=i&&1===t.height,`Tail and head block must be ${i} blocks apart`);let s=e.timestamp-t.timestamp;e.height<=i&&(s+=(i-e.height+1)*Policy.INITIAL_BLOCK_TIME,r=r.plus(i-e.height+1));let n=s/(i*Policy.blockTime(e.height));e.height>=Policy.SECOND_FORKING_FOR_BLOCK_DIFFICULTY?(n=Math.max(n,1/Policy.SECOND_DIFFICULTY_MAX_ADJUSTMENT_FACTOR),n=Math.min(n,1/Policy.SECOND_DIFFICULTY_MIN_ADJUSTMENT_FACTOR)):e.height>=Policy.FORKING_FOR_BLOCK_DIFFICULTY_BLOCK_SIZE?(n=Math.max(n,1/Policy.NEW_DIFFICULTY_MAX_ADJUSTMENT_FACTOR),n=Math.min(n,1/Policy.NEW_DIFFICULTY_MIN_ADJUSTMENT_FACTOR)):(n=Math.max(n,1/Policy.DIFFICULTY_MAX_ADJUSTMENT_FACTOR),n=Math.min(n,Policy.DIFFICULTY_MAX_ADJUSTMENT_FACTOR));const o=r.div(i);let a=BlockUtils.difficultyToTarget(o).times(n);a=BigNumber.min(a,Policy.BLOCK_TARGET_MAX),a=BigNumber.max(a,1);const l=BlockUtils.targetToCompact(a);return BlockUtils.compactToTarget(l)}}Class.register(BlockUtils);class Block{constructor(e,t,r){if(!(e instanceof BlockHeader))throw new Error("Malformed header");if(!(t instanceof BlockInterlink))throw new Error("Malformed interlink");if(r&&!(r instanceof BlockBody))throw new Error("Malformed body");this._header=e,this._interlink=t,this._body=r}static unserialize(e){const t=BlockHeader.unserialize(e),r=BlockInterlink.unserialize(e,t.prevHash);let i=void 0;return e.readUint8()&&(i=BlockBody.unserialize(e)),new Block(t,r,i)}serialize(e){return e=e||new SerialBuffer(this.serializedSize),this._header.serialize(e),this._interlink.serialize(e),this._body?(e.writeUint8(1),this._body.serialize(e)):e.writeUint8(0),e}get serializedSize(){return this._header.serializedSize+this._interlink.serializedSize+1+(this._body?this._body.serializedSize:0)}async verify(e){if(void 0===this._valid)if(this.isLight()||this.body.transactions.length<150||!IWorker.areWorkersAsync)this._valid=await this._verify(e.now());else{const t=this.body.transactions.map(e=>e._valid),r=await CryptoWorker.getInstanceAsync(),{valid:i,pow:s,interlinkHash:n,bodyHash:o}=await r.blockVerify(this.serialize(),t,e.now(),GenesisConfig.GENESIS_HASH.serialize(),GenesisConfig.NETWORK_ID);this._valid=i,this.header._pow=Hash.unserialize(new SerialBuffer(s)),this.interlink._hash=Hash.unserialize(new SerialBuffer(n)),this.body._hash=Hash.unserialize(new SerialBuffer(o))}return this._valid}async _verify(e){return 1e3*this._header.timestamp>e+1e3*Block.TIMESTAMP_DRIFT_MAX?(Log.w(Block,"Invalid block - timestamp too far in the future"),!1):await this._header.verifyProofOfWork()?this.serializedSize>Policy.blockSize(this.height)?(Log.w(Block,"Invalid block - max block size exceeded"),!1):!!this._verifyInterlink()&&!(this.isFull()&&!this._verifyBody()):(Log.w(Block,"Invalid block - PoW verification failed"),!1)}_verifyInterlink(){if(1===this.height&&this._header.interlinkHash.equals(new Hash(null)))return!0;const e=this._interlink.hash();return!!this._header.interlinkHash.equals(e)||(Log.w(Block,"Invalid block - interlink hash mismatch"),!1)}_verifyBody(){if(!this._body.verify())return!1;const e=this._body.hash();return!!this._header.bodyHash.equals(e)||(Log.w(Block,"Invalid block - body hash mismatch"),!1)}async isImmediateSuccessorOf(e){if(!this._header.isImmediateSuccessorOf(e.header))return!1;const t=await e.getNextInterlink(this.target,this.version);return!!this._interlink.equals(t)}async isInterlinkSuccessorOf(e){if(this._header.height<=e.header.height)return Log.v(Block,"No interlink successor - height"),!1;if(this._header.timestamp<e.header.timestamp)return Log.v(Block,"No interlink successor - timestamp"),!1;const t=e.hash();if(!GenesisConfig.GENESIS_HASH.equals(t)){const r=await e.pow(),i=BlockUtils.getTargetHeight(this.target);let s=!1,n=0;for(;n<this._interlink.length;n++)if(t.equals(this._interlink.hashes[n])){s=!0;const e=new BigNumber(2).pow(i-n);if(!BlockUtils.isProofOfWork(r,e))return Log.v(Block,"No interlink successor - invalid position in interlink"),!1}if(!s)return Log.v(Block,"No interlink successor - not in interlink"),!1}if(this._header.prevHash.equals(t)){if(this._header.height!==e.header.height+1)return Log.v(Block,"No interlink successor - immediate height"),!1;const t=(await e.getNextInterlink(this.target,this.version)).hash();if(!this._header.interlinkHash.equals(t))return Log.v(Block,"No interlink successor - immediate interlink"),!1}else{if(this._header.height===e.header.height+1)return Log.v(Block,"No interlink successor - immediate height (2)"),!1;{const t=new HashSet;if(t.addAll(this._interlink.hashes),t.removeAll(e.interlink.hashes),t.length>this._header.height-e.header.height)return Log.v(Block,"No interlink successor - too many new blocks"),!1;const r=BlockUtils.getTargetDepth(this.target)-BlockUtils.getTargetDepth(e.target);if(this._interlink.length<e.interlink.length-r)return Log.v(Block,"No interlink successor - interlink too short"),!1;let i=!1;const s=this._interlink.hashes,n=e.interlink.hashes;for(let e=1;e<n.length&&e-r<s.length;e++)if(n[e].equals(s[e-r]))i=!0;else if(i)return Log.v(Block,"No interlink successor - invalid common suffix"),!1}}return!0}async isSuccessorOf(e){return await this.isImmediateSuccessorOf(e)||await this.isInterlinkSuccessorOf(e)}async getNextInterlink(e,t=BlockHeader.CURRENT_VERSION){const r=[],i=this.hash(),s=BlockUtils.getHashDepth(await this.pow()),n=BlockUtils.getTargetDepth(e),o=Math.max(s-n+1,0);for(let e=0;e<o;e++)r.push(i);for(let e=o+(n-BlockUtils.getTargetDepth(this.target));e<this.interlink.length;e++)r.push(this.interlink.hashes[e]);return new BlockInterlink(r,i)}shallowCopy(){return new Block(this._header,this._interlink,this._body)}equals(e){return e instanceof Block&&this._header.equals(e._header)&&this._interlink.equals(e._interlink)&&(this._body?this._body.equals(e._body):!e._body)}isLight(){return!this._body}isFull(){return!!this._body}toLight(){return this.isLight()?this:new Block(this._header,this._interlink)}toFull(e){return this.isFull()?this:new Block(this._header,this._interlink,e)}get header(){return this._header}get interlink(){return this._interlink}get body(){if(this.isLight())throw new Error("Cannot access body of light block");return this._body}get version(){return this._header.version}get prevHash(){return this._header.prevHash}get interlinkHash(){return this._header.interlinkHash}get bodyHash(){return this._header.bodyHash}get accountsHash(){return this._header.accountsHash}get nBits(){return this._header.nBits}get target(){return this._header.target}get difficulty(){return this._header.difficulty}get height(){return this._header.height}get timestamp(){return this._header.timestamp}get nonce(){return this._header.nonce}get minerAddr(){return this._body?this._body.minerAddr:void 0}get transactions(){return this._body?this._body.transactions:void 0}get extraData(){return this._body?this._body.extraData:void 0}get prunedAccounts(){return this._body?this._body.prunedAccounts:void 0}get transactionCount(){return this._body?this._body.transactionCount:void 0}hash(e){return this._header.hash(e)}pow(e){return this._header.pow(e)}static fromAny(e){if(e instanceof Block)return e;if("object"==typeof e)return Block.fromPlain(e);if("string"==typeof e)return Block.unserialize(BufferUtils.fromHex(e));throw new Error("Invalid block")}static fromPlain(e){const t=new BlockHeader(Hash.fromAny(e.prevHash),Hash.fromAny(e.interlinkHash),Hash.fromAny(e.bodyHash),Hash.fromAny(e.accountsHash),e.nBits,e.height,e.timestamp,e.nonce,e.version),r=new BlockInterlink((e.interlink.hashes||e.interlink).map(e=>Hash.fromAny(e)),Hash.fromAny(e.prevHash));let i=null;return e.minerAddr&&void 0!==e.extraData&&Array.isArray(e.transactions)&&Array.isArray(e.prunedAccounts)&&(i=new BlockBody(Address.fromAny(e.minerAddr),e.transactions.map(e=>Transaction.fromAny(e)),BufferUtils.fromAny(e.extraData),e.prunedAccounts.map(e=>PrunedAccount.fromAny(e)))),new Block(t,r,i)}toString(){return`Block{height=${this.height},prev=${this.prevHash}}`}toPlain(){const e={version:this.version,hash:this.hash().toPlain(),prevHash:this.prevHash.toPlain(),interlinkHash:this.interlinkHash.toPlain(),bodyHash:this.bodyHash.toPlain(),accountsHash:this.accountsHash.toPlain(),nBits:this.nBits,difficulty:this.difficulty.toString(),height:this.height,timestamp:this.timestamp,nonce:this.nonce,interlink:this.interlink.hashes.map(e=>e.toPlain())};return this.isFull()&&(e.minerAddr=this.minerAddr.toPlain(),e.transactions=this.transactions.map(e=>e.toPlain()),e.extraData=BufferUtils.toHex(this.extraData),e.prunedAccounts=this.prunedAccounts.map(e=>e.toPlain())),e}}Block.TIMESTAMP_DRIFT_MAX=600,Class.register(Block);class Transaction{constructor(e,t,r,i,s,n,o,a,l,c,h=GenesisConfig.NETWORK_ID){const u=new BigNumber(n);if(!(t instanceof Address))throw new Error("Malformed sender");if(!NumberUtils.isUint8(r))throw new Error("Malformed sender type");if(!(i instanceof Address))throw new Error("Malformed recipient");if(!NumberUtils.isUint8(s))throw new Error("Malformed recipient type");if(!NumberUtils.isUint128(u)||u.eq(0))throw new Error("Malformed value");if(!NumberUtils.isUint32(o))throw new Error("Malformed validityStartHeight");if(!NumberUtils.isUint8(a)&&(a&~Transaction.Flag.ALL)>0)throw new Error("Malformed flags");if(!(l instanceof Uint8Array&&NumberUtils.isUint16(l.byteLength)))throw new Error("Malformed data");if(c&&(!(c instanceof Uint8Array)||!NumberUtils.isUint16(c.byteLength)))throw new Error("Malformed proof");if(!NumberUtils.isUint8(h))throw new Error("Malformed networkId");this._format=e,this._sender=t,this._senderType=r,this._recipient=i,this._recipientType=s,this._value=u,this._fee=Policy.txFee(o),this._networkId=h,this._validityStartHeight=o,this._flags=a,this._data=l,this._proof=c,this._recipient===Address.CONTRACT_CREATION&&(this._recipient=this.getContractCreationAddress())}static unserialize(e){const t=e.readUint8();if(e.readPos--,!Transaction.FORMAT_MAP.has(t))throw new Error("Invalid transaction type");return Transaction.FORMAT_MAP.get(t).unserialize(e)}serializeContent(e){return(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),e}get serializedContentSize(){return 2+this._data.byteLength+this._sender.serializedSize+1+this._recipient.serializedSize+1+16+16+4+1+1}verify(e){return void 0===this._valid&&(this._valid=this._verify(e)),this._valid}_verify(e=GenesisConfig.NETWORK_ID){return this._networkId!==e?(Log.w(Transaction,"Transaction is not valid in this network",this),!1):this._recipient.equals(this._sender)?(Log.w(Transaction,"Sender and recipient must not match",this),!1):Account.TYPE_MAP.has(this._senderType)&&Account.TYPE_MAP.has(this._recipientType)?Account.TYPE_MAP.get(this._senderType).verifyOutgoingTransaction(this)?Account.TYPE_MAP.get(this._recipientType).verifyIncomingTransaction(this)?!!this._fee.eq(Policy.txFee(this._validityStartHeight))||(Log.w(Transaction,"Invalid for tx fee",this),!1):(Log.w(Transaction,"Invalid for recipient",this),!1):(Log.w(Transaction,"Invalid for sender",this),!1):(Log.w(Transaction,"Invalid account type",this),!1)}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(){return this._hash=this._hash||Hash.light(this.serializeContent()),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);return t.raw=BufferUtils.toHex(this.proof),{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());return e._recipient=Address.NULL,e._hash=null,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 t=new SerialBuffer(e.proof),r=SignatureProof.unserialize(t);return t.readPos!==t.byteLength?(Log.w(SignatureProof,"Invalid SignatureProof - overlong"),!1):r.verify(e.sender,e.serializeContent())}catch(e){return Log.w(SignatureProof,`Failed to verify transaction: ${e.message||e}`),!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){return e=e||new SerialBuffer(this.serializedSize),this._publicKey.serialize(e),this._merklePath.serialize(e),this._signature&&this._signature.serialize(e),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){return null===e||this.isSignedBy(e)?this._signature?!!this._signature.verify(this._publicKey,t)||(Log.w(SignatureProof,"Invalid SignatureProof - signature is invalid"),!1):(Log.w(SignatureProof,"Invalid SignatureProof - signature is missing"),!1):(Log.w(SignatureProof,"Invalid SignatureProof - signer does not match sender address"),!1)}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,s,n){if(!(e instanceof PublicKey))throw new Error("Malformed senderPubKey");if(void 0!==s&&!(s instanceof Signature))throw new Error("Malformed signature");const o=SignatureProof.singleSig(e,s);super(Transaction.Format.BASIC,e.toAddress(),Account.Type.BASIC,t,Account.Type.BASIC,r,i,Transaction.Flag.NONE,new Uint8Array(0),o.serialize(),n),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),s=e.readUint128(),n=(e.readUint128(),e.readUint32()),o=e.readUint8(),a=Signature.unserialize(e);return new BasicTransaction(r,i,s,n,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){return(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),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,s,n,o,a,l=new Uint8Array(0),c){super(Transaction.Format.EXTENDED,e,t,r,i,s,n,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),s=Address.unserialize(e),n=e.readUint8(),o=Address.unserialize(e),a=e.readUint8(),l=e.readUint128(),c=(e.readUint128(),e.readUint32()),h=e.readUint8(),u=e.readUint8(),f=e.readUint16(),d=e.read(f);return new ExtendedTransaction(s,n,o,a,l,c,u,i,d,h)}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(void 0===e.data.raw?e.data:e.data.raw),BufferUtils.fromAny(void 0===e.proof.raw?e.proof:e.proof.raw),GenesisConfig.networkIdFromAny(e.network||e.networkId))}serialize(e){return(e=e||new SerialBuffer(this.serializedSize)).writeUint8(Transaction.Format.EXTENDED),this.serializeContent(e),e.writeUint16(this._proof.byteLength),e.write(this._proof),e}get serializedSize(){return 1+this.serializedContentSize+2+this._proof.byteLength}}Transaction.FORMAT_MAP.set(Transaction.Format.EXTENDED,ExtendedTransaction),Class.register(ExtendedTransaction);
|
2
|
+
//# sourceMappingURL=worker.js.map
|