@corpus-core/colibri-stateless 0.1.13 → 0.1.14
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/c4w.js +1 -1
- package/c4w.wasm +0 -0
- package/index.d.ts +22 -0
- package/index.js +82 -35
- package/package.json +1 -1
- package/server.d.ts +8 -0
- package/server.js +177 -0
- package/wasm.d.ts +4 -4
package/c4w.js
CHANGED
|
@@ -5,7 +5,7 @@ var c4w = (() => {
|
|
|
5
5
|
async function(moduleArg = {}) {
|
|
6
6
|
var moduleRtn;
|
|
7
7
|
|
|
8
|
-
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(!import.meta.url.startsWith("data:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}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(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["h"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("c4w.wasm")}return new URL("c4w.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["g"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}var ASM_CONSTS={56372:($0,$1)=>{var keyStr=UTF8ToString($0);var data=Module.storage.get(keyStr);if(data){var bufferPtr=_c4w_buffer_alloc($1,data.length);HEAPU8.set(data,bufferPtr);return 1}return 0},56560:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},56703:$0=>{var keyStr=UTF8ToString($0);Module.storage.del(keyStr)}};class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[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};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==106?HEAP64[buf>>3]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var _fd_close=fd=>52;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var 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};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array: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(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var wasmImports={a:___assert_fail,b:_emscripten_asm_const_int,d:_emscripten_resize_heap,f:_fd_close,e:_fd_seek,c:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["h"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["i"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["j"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["k"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["l"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["m"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["n"];var _malloc=Module["_malloc"]=wasmExports["o"];var _free=Module["_free"]=wasmExports["p"];var _c4w_handle_client_updates=Module["_c4w_handle_client_updates"]=wasmExports["q"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["r"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["s"];var _c4w_init_chain=Module["_c4w_init_chain"]=wasmExports["t"];var _init_storage=Module["_init_storage"]=wasmExports["u"];var __emscripten_stack_restore=wasmExports["w"];var __emscripten_stack_alloc=wasmExports["x"];var _emscripten_stack_get_current=wasmExports["y"];Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
|
|
8
|
+
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var moduleOverrides={...Module};var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(!import.meta.url.startsWith("data:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}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(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["n"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("c4w.wasm")}return new URL("c4w.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["m"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[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};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var 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};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==106?HEAP64[buf>>3]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var _fd_close=fd=>52;var _fd_read=(fd,iov,iovcnt,pnum)=>52;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array: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(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var ASM_CONSTS={142956:($0,$1)=>{var keyStr=UTF8ToString($0);var data=Module.storage.get(keyStr);if(data){var bufferPtr=_c4w_buffer_alloc($1,data.length);HEAPU8.set(data,bufferPtr);return 1}return 0},143144:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},143287:$0=>{var keyStr=UTF8ToString($0);Module.storage.del(keyStr)}};var wasmImports={a:___assert_fail,b:___cxa_throw,f:__abort_js,k:__tzset_js,c:_emscripten_asm_const_int,g:_emscripten_resize_heap,l:_environ_get,e:_environ_sizes_get,i:_fd_close,j:_fd_read,h:_fd_seek,d:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["n"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["o"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["p"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["q"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["r"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["s"];var _c4w_create_verify_ctx=Module["_c4w_create_verify_ctx"]=wasmExports["t"];var _c4w_free_verify_ctx=Module["_c4w_free_verify_ctx"]=wasmExports["u"];var _free=Module["_free"]=wasmExports["v"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["w"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["x"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["y"];var _init_storage=Module["_init_storage"]=wasmExports["z"];var _malloc=Module["_malloc"]=wasmExports["B"];var __emscripten_stack_restore=wasmExports["C"];var __emscripten_stack_alloc=wasmExports["D"];var _emscripten_stack_get_current=wasmExports["E"];Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
return moduleRtn;
|
package/c4w.wasm
CHANGED
|
Binary file
|
package/index.d.ts
CHANGED
|
@@ -1,13 +1,35 @@
|
|
|
1
1
|
import { Storage as C4Storage } from "./wasm.js";
|
|
2
|
+
export interface Cache {
|
|
3
|
+
cacheable(req: DataRequest): boolean;
|
|
4
|
+
get(req: DataRequest): Uint8Array | undefined;
|
|
5
|
+
set(req: DataRequest, data: Uint8Array): void;
|
|
6
|
+
}
|
|
2
7
|
export interface Config {
|
|
3
8
|
chainId: number;
|
|
4
9
|
beacon_apis: string[];
|
|
5
10
|
rpcs: string[];
|
|
11
|
+
proofer?: string[];
|
|
6
12
|
trusted_block_hashes: string[];
|
|
13
|
+
cache?: Cache;
|
|
14
|
+
debug?: boolean;
|
|
15
|
+
include_code?: boolean;
|
|
16
|
+
verify?: (method: string, args: any[]) => boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface DataRequest {
|
|
19
|
+
method: string;
|
|
20
|
+
chain_id: number;
|
|
21
|
+
encoding: string;
|
|
22
|
+
type: string;
|
|
23
|
+
exclude_mask: number;
|
|
24
|
+
url: string;
|
|
25
|
+
payload: any;
|
|
26
|
+
req_ptr: number;
|
|
7
27
|
}
|
|
28
|
+
export declare function handle_request(req: DataRequest, conf: Config): Promise<void>;
|
|
8
29
|
export default class C4Client {
|
|
9
30
|
config: Config;
|
|
10
31
|
constructor(config?: Partial<Config>);
|
|
32
|
+
private get flags();
|
|
11
33
|
createProof(method: string, args: any[]): Promise<Uint8Array>;
|
|
12
34
|
verifyProof(method: string, args: any[], proof: Uint8Array): Promise<any>;
|
|
13
35
|
rpc(method: string, args: any[]): Promise<any>;
|
package/index.js
CHANGED
|
@@ -1,30 +1,57 @@
|
|
|
1
1
|
// Import the Emscripten-generated module
|
|
2
2
|
import { getC4w, as_char_ptr, as_json, as_bytes, copy_to_c } from "./wasm.js";
|
|
3
3
|
async function initialize_storage(conf) {
|
|
4
|
+
// TODO handle trusted_block_hashes
|
|
4
5
|
const c4w = await getC4w();
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
}
|
|
7
|
+
async function fetch_rpc(urls, method, params, as_proof = false) {
|
|
8
|
+
let last_error = "All nodes failed";
|
|
9
|
+
for (const url of urls) {
|
|
10
|
+
const response = await fetch(url, {
|
|
11
|
+
method: 'POST',
|
|
12
|
+
body: JSON.stringify({ id: 1, jsonrpc: "2.0", method, params }),
|
|
13
|
+
headers: {
|
|
14
|
+
"Content-Type": "application/json",
|
|
15
|
+
"Accept": as_proof ? "application/octet-stream" : "application/json"
|
|
12
16
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
});
|
|
18
|
+
if (response.ok) {
|
|
19
|
+
if (!as_proof) {
|
|
20
|
+
const res = await response.json();
|
|
21
|
+
if (res.error) {
|
|
22
|
+
last_error = res.error?.message || res.error;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
return res.result;
|
|
26
|
+
}
|
|
27
|
+
const bytes = await response.blob().then(blob => blob.arrayBuffer());
|
|
28
|
+
return new Uint8Array(bytes);
|
|
21
29
|
}
|
|
30
|
+
else
|
|
31
|
+
last_error = `HTTP error! Status: ${response.status}, Details: ${await response.text()}`;
|
|
22
32
|
}
|
|
33
|
+
throw new Error(last_error);
|
|
34
|
+
}
|
|
35
|
+
function log(msg) {
|
|
36
|
+
console.error(msg);
|
|
23
37
|
}
|
|
24
|
-
async function handle_request(req, conf) {
|
|
38
|
+
export async function handle_request(req, conf) {
|
|
25
39
|
const free_buffers = [];
|
|
26
40
|
const servers = req.type == "beacon_api" ? conf.beacon_apis : conf.rpcs;
|
|
27
41
|
const c4w = await getC4w();
|
|
42
|
+
let path = (req.type == 'eth_rpc' && req.payload)
|
|
43
|
+
? `rpc: ${req.payload?.method}(${req.payload?.params.join(',')})`
|
|
44
|
+
: req.url;
|
|
45
|
+
let cacheable = conf.cache && conf.cache.cacheable(req);
|
|
46
|
+
if (cacheable && conf.cache) {
|
|
47
|
+
const data = conf.cache.get(req);
|
|
48
|
+
if (data) {
|
|
49
|
+
if (conf.debug)
|
|
50
|
+
log(`::: ${path} (len=${data.length} bytes) CACHED`);
|
|
51
|
+
c4w._c4w_req_set_response(req.req_ptr, copy_to_c(data, c4w), data.length, 0);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
28
55
|
let node_index = 0;
|
|
29
56
|
let last_error = "All nodes failed";
|
|
30
57
|
for (const server of servers) {
|
|
@@ -44,7 +71,12 @@ async function handle_request(req, conf) {
|
|
|
44
71
|
if (!response.ok)
|
|
45
72
|
throw new Error(`HTTP error! Status: ${response.status}, Details: ${await response.text()}`);
|
|
46
73
|
const bytes = await response.blob().then(blob => blob.arrayBuffer());
|
|
47
|
-
|
|
74
|
+
const data = new Uint8Array(bytes);
|
|
75
|
+
c4w._c4w_req_set_response(req.req_ptr, copy_to_c(data, c4w), data.length, node_index);
|
|
76
|
+
if (conf.debug)
|
|
77
|
+
log(`::: ${path} (len=${data.length} bytes) FETCHED`);
|
|
78
|
+
if (conf.cache && cacheable)
|
|
79
|
+
conf.cache.set(req, data);
|
|
48
80
|
return;
|
|
49
81
|
}
|
|
50
82
|
catch (e) {
|
|
@@ -54,6 +86,8 @@ async function handle_request(req, conf) {
|
|
|
54
86
|
}
|
|
55
87
|
c4w._c4w_req_set_error(req.req_ptr, as_char_ptr(last_error, c4w, free_buffers), 0);
|
|
56
88
|
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
89
|
+
if (conf.debug)
|
|
90
|
+
log(`::: ${path} (Error: ${last_error})`);
|
|
57
91
|
}
|
|
58
92
|
export default class C4Client {
|
|
59
93
|
config;
|
|
@@ -67,13 +101,16 @@ export default class C4Client {
|
|
|
67
101
|
}, ...config
|
|
68
102
|
};
|
|
69
103
|
}
|
|
104
|
+
get flags() {
|
|
105
|
+
return this.config.include_code ? 1 : 0;
|
|
106
|
+
}
|
|
70
107
|
async createProof(method, args) {
|
|
71
108
|
const c4w = await getC4w();
|
|
72
109
|
const free_buffers = [];
|
|
73
110
|
let ctx = 0;
|
|
74
111
|
try {
|
|
75
112
|
// Call the C function
|
|
76
|
-
ctx = c4w._c4w_create_proof_ctx(as_char_ptr(method, c4w, free_buffers), as_char_ptr(JSON.stringify(args), c4w, free_buffers), BigInt(this.config.chainId));
|
|
113
|
+
ctx = c4w._c4w_create_proof_ctx(as_char_ptr(method, c4w, free_buffers), as_char_ptr(JSON.stringify(args), c4w, free_buffers), BigInt(this.config.chainId), this.flags);
|
|
77
114
|
while (true) {
|
|
78
115
|
const state = as_json(c4w._c4w_execute_proof_ctx(ctx), c4w, true);
|
|
79
116
|
switch (state.status) {
|
|
@@ -96,28 +133,38 @@ export default class C4Client {
|
|
|
96
133
|
}
|
|
97
134
|
async verifyProof(method, args, proof) {
|
|
98
135
|
const c4w = await getC4w();
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
136
|
+
const free_buffers = [];
|
|
137
|
+
let ctx = 0;
|
|
138
|
+
try {
|
|
139
|
+
// Call the C function
|
|
140
|
+
ctx = c4w._c4w_create_verify_ctx(copy_to_c(proof, c4w, free_buffers), proof.length, as_char_ptr(method, c4w, free_buffers), as_char_ptr(JSON.stringify(args), c4w, free_buffers), BigInt(this.config.chainId));
|
|
141
|
+
while (true) {
|
|
142
|
+
const state = as_json(c4w._c4w_verify_proof(ctx), c4w, true);
|
|
143
|
+
switch (state.status) {
|
|
144
|
+
case "success":
|
|
145
|
+
return state.result;
|
|
146
|
+
case "error":
|
|
147
|
+
throw new Error(state.error);
|
|
148
|
+
case "waiting": {
|
|
149
|
+
await Promise.all(state.requests.map((req) => handle_request(req, this.config)));
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
112
152
|
}
|
|
113
|
-
continue;
|
|
114
153
|
}
|
|
115
|
-
throw new Error(result.error);
|
|
116
154
|
}
|
|
117
|
-
|
|
155
|
+
finally {
|
|
156
|
+
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
157
|
+
if (ctx)
|
|
158
|
+
c4w._c4w_free_verify_ctx(ctx);
|
|
159
|
+
}
|
|
118
160
|
}
|
|
119
161
|
async rpc(method, args) {
|
|
120
|
-
|
|
162
|
+
// skip verify
|
|
163
|
+
if (this.config.verify && !this.config.verify(method, args))
|
|
164
|
+
return await fetch_rpc(this.config.rpcs, method, args, false);
|
|
165
|
+
let proof = this.config.proofer && this.config.proofer.length
|
|
166
|
+
? await fetch_rpc(this.config.proofer, method, args, true)
|
|
167
|
+
: await this.createProof(method, args);
|
|
121
168
|
return this.verifyProof(method, args, proof);
|
|
122
169
|
}
|
|
123
170
|
static async register_storage(storage) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@corpus-core/colibri-stateless",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "Colibri is a stateless and trustless ethereum client, which is optimized for the mobile apps or embedded devices, because it does not hols the state, but verifies on demand.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {},
|
package/server.d.ts
ADDED
package/server.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import Client from "./index.js";
|
|
2
|
+
import * as http from 'http';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
// ensure cache_dir
|
|
5
|
+
let cache_memory_limit = parseInt(process.env.CACHE_RAM_LIMIT || '100'); // in MB
|
|
6
|
+
let cache_dir = process.env.CACHE_DIR || '.cache';
|
|
7
|
+
if (!fs.existsSync(cache_dir))
|
|
8
|
+
fs.mkdirSync(cache_dir, { recursive: true });
|
|
9
|
+
function cache_key(req) {
|
|
10
|
+
if (req.type == 'eth_rpc' && req.payload)
|
|
11
|
+
return `rpc_${req.payload?.method}_${req.payload?.params?.join('_')}`;
|
|
12
|
+
return req.url;
|
|
13
|
+
}
|
|
14
|
+
const cached_methods = ["eth_getBlockByNumber", "eth_getBlockByHash", "eth_getBlockReceipts"];
|
|
15
|
+
const memory_cache = new Map();
|
|
16
|
+
function check_limit() {
|
|
17
|
+
let total_size = 0;
|
|
18
|
+
for (const [k, v] of memory_cache.entries()) {
|
|
19
|
+
total_size += v.data.length;
|
|
20
|
+
}
|
|
21
|
+
while (total_size > cache_memory_limit * 1024 * 1024) {
|
|
22
|
+
// find the oldest entry
|
|
23
|
+
let oldest_k = null;
|
|
24
|
+
let oldest_v = null;
|
|
25
|
+
for (const [k, v] of memory_cache.entries()) {
|
|
26
|
+
if (oldest_v == null || v.timestamp < oldest_v.timestamp) {
|
|
27
|
+
oldest_k = k;
|
|
28
|
+
oldest_v = v;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (oldest_k)
|
|
32
|
+
memory_cache.delete(oldest_k);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function is_timeout(key, entry) {
|
|
36
|
+
if (key.endsWith('latest') || key.endsWith('head')) {
|
|
37
|
+
if (!entry)
|
|
38
|
+
return true;
|
|
39
|
+
return entry.timestamp < Date.now() - 1000 * 6;
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
const cache = {
|
|
44
|
+
cacheable: (req) => !!(req.encoding == "ssz" || (req.type == 'eth_rpc' && req.payload && cached_methods.includes(req.payload?.method))),
|
|
45
|
+
get: (req) => {
|
|
46
|
+
const key = cache_key(req);
|
|
47
|
+
let entry = memory_cache.get(key);
|
|
48
|
+
if (is_timeout(key, entry))
|
|
49
|
+
entry = undefined;
|
|
50
|
+
if (!entry && !is_timeout(key)) {
|
|
51
|
+
const file_path = cache_dir + '/' + key;
|
|
52
|
+
if (fs.existsSync(file_path)) {
|
|
53
|
+
let data = fs.readFileSync(file_path);
|
|
54
|
+
memory_cache.set(key, { data, timestamp: fs.statSync(file_path).mtime.getTime() });
|
|
55
|
+
setTimeout(check_limit, 0);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return entry?.data;
|
|
59
|
+
},
|
|
60
|
+
set: (req, data) => {
|
|
61
|
+
const key = cache_key(req);
|
|
62
|
+
memory_cache.set(key, { data, timestamp: Date.now() });
|
|
63
|
+
if (!is_timeout(key))
|
|
64
|
+
fs.writeFile(cache_dir + '/' + key, Buffer.from(data), () => { });
|
|
65
|
+
check_limit();
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
export default class Server {
|
|
69
|
+
client;
|
|
70
|
+
constructor(conf) {
|
|
71
|
+
conf = conf || {};
|
|
72
|
+
if (process.env.CHAIN_ID)
|
|
73
|
+
conf.chainId = parseInt(process.env.CHAIN_ID);
|
|
74
|
+
if (process.env.BEACON_API)
|
|
75
|
+
conf.beacon_apis = process.env.BEACON_API.split(",");
|
|
76
|
+
if (process.env.RPC)
|
|
77
|
+
conf.rpcs = process.env.RPC.split(",");
|
|
78
|
+
conf.cache = cache;
|
|
79
|
+
conf.debug = true;
|
|
80
|
+
this.client = new Client(conf);
|
|
81
|
+
}
|
|
82
|
+
toHexString(bytes) {
|
|
83
|
+
return '0x' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
84
|
+
}
|
|
85
|
+
async handleRequest(req, res) {
|
|
86
|
+
// Only accept POST requests
|
|
87
|
+
if (req.method !== 'POST') {
|
|
88
|
+
const error = 'Method not allowed';
|
|
89
|
+
console.error(`[${new Date().toISOString()}] Error: ${error}`);
|
|
90
|
+
res.writeHead(405, { 'Content-Type': 'application/json' });
|
|
91
|
+
res.end(JSON.stringify({ error }));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
// Read request body
|
|
95
|
+
let body = '';
|
|
96
|
+
req.on('data', (chunk) => {
|
|
97
|
+
body += chunk.toString();
|
|
98
|
+
});
|
|
99
|
+
req.on('end', async () => {
|
|
100
|
+
try {
|
|
101
|
+
const jsonRpc = JSON.parse(body);
|
|
102
|
+
if (!jsonRpc.method || !jsonRpc.params || !Array.isArray(jsonRpc.params)) {
|
|
103
|
+
throw new Error('Invalid JSON-RPC request');
|
|
104
|
+
}
|
|
105
|
+
let start = Date.now();
|
|
106
|
+
console.log(` ==> ${jsonRpc.method} (${jsonRpc.params.join(',')}) ...`);
|
|
107
|
+
// Create proof using the client
|
|
108
|
+
const proof = await this.client.createProof(jsonRpc.method, jsonRpc.params);
|
|
109
|
+
let end = Date.now();
|
|
110
|
+
console.log(` <== ${jsonRpc.method} (${jsonRpc.params.join(',')}) ... ${end - start}ms (${proof.length} bytes)`);
|
|
111
|
+
// Check Accept header to determine response format
|
|
112
|
+
const acceptHeader = req.headers.accept;
|
|
113
|
+
if (acceptHeader === 'application/octet-stream') {
|
|
114
|
+
res.writeHead(200, {
|
|
115
|
+
'Content-Type': 'application/octet-stream',
|
|
116
|
+
'Content-Length': proof.length
|
|
117
|
+
});
|
|
118
|
+
res.end(Buffer.from(proof));
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
const response = {
|
|
122
|
+
jsonrpc: '2.0',
|
|
123
|
+
id: jsonRpc.id,
|
|
124
|
+
result: this.toHexString(proof)
|
|
125
|
+
};
|
|
126
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
127
|
+
res.end(JSON.stringify(response));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const errorMessage = error instanceof Error ? error.message : 'Internal error';
|
|
132
|
+
console.error(`[${new Date().toISOString()}] Error processing request:`, errorMessage);
|
|
133
|
+
if (error instanceof Error && error.stack) {
|
|
134
|
+
console.error(`Stack trace:`, error.stack);
|
|
135
|
+
}
|
|
136
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
137
|
+
const errorResponse = {
|
|
138
|
+
jsonrpc: '2.0',
|
|
139
|
+
id: JSON.parse(body)?.id,
|
|
140
|
+
error: {
|
|
141
|
+
code: -32603,
|
|
142
|
+
message: errorMessage
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
res.end(JSON.stringify(errorResponse));
|
|
146
|
+
console.log(`[${new Date().toISOString()}] Sent error response:`, errorResponse);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
req.on('error', (error) => {
|
|
150
|
+
console.error(`[${new Date().toISOString()}] Request error:`, error);
|
|
151
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
152
|
+
res.end(JSON.stringify({
|
|
153
|
+
jsonrpc: '2.0',
|
|
154
|
+
error: {
|
|
155
|
+
code: -32603,
|
|
156
|
+
message: 'Internal server error'
|
|
157
|
+
}
|
|
158
|
+
}));
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async start(port = 8545) {
|
|
162
|
+
const server = http.createServer((req, res) => this.handleRequest(req, res));
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
server.listen(port, () => {
|
|
165
|
+
console.log(`[${new Date().toISOString()}] Server running at http://localhost:${port}/`);
|
|
166
|
+
resolve();
|
|
167
|
+
});
|
|
168
|
+
server.on('error', (error) => {
|
|
169
|
+
console.error(`[${new Date().toISOString()}] Server error:`, error);
|
|
170
|
+
reject(error);
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Start the server directly
|
|
176
|
+
const server = new Server({});
|
|
177
|
+
server.start(parseInt(process.env.PORT || '8545'));
|
package/wasm.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
export interface C4W {
|
|
2
|
-
_c4w_create_proof_ctx: (method: number, args: number, chainId: bigint) => number;
|
|
2
|
+
_c4w_create_proof_ctx: (method: number, args: number, chainId: bigint, flags: number) => number;
|
|
3
3
|
_c4w_free_proof_ctx: (proofCtx: number) => void;
|
|
4
4
|
_c4w_execute_proof_ctx: (proofCtx: number) => number;
|
|
5
5
|
_c4w_get_pending_data_request: (proofCtx: number) => number;
|
|
6
6
|
_c4w_req_set_response: (reqPtr: number, data: number, len: number, node_index: number) => void;
|
|
7
7
|
_c4w_req_set_error: (reqPtr: number, error: number, node_index: number) => void;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
_c4w_create_verify_ctx: (proof: number, proof_len: number, method: number, args: number, chain_id: bigint) => number;
|
|
9
|
+
_c4w_free_verify_ctx: (verifyCtx: number) => void;
|
|
10
|
+
_c4w_verify_proof: (verifyCtx: number) => number;
|
|
11
11
|
_c4w_req_free: (reqPtr: number) => void;
|
|
12
12
|
_init_storage: () => void;
|
|
13
13
|
HEAPU8: Uint8Array;
|