@corpus-core/colibri-stateless 2.0.4 → 2.0.5
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 +15 -1
- package/c4w.js +1 -1
- package/c4w.wasm +0 -0
- package/cjs/http.js +5 -32
- package/cjs/index.js +44 -54
- package/cjs/index.node.js +53 -0
- package/cjs/runtime.js +53 -0
- package/cjs/runtime_node.js +113 -0
- package/cjs/runtime_wasm.js +132 -0
- package/cjs/wasm.js +10 -0
- package/cjs/wasm_cjs.js +10 -0
- package/http.d.ts +25 -1
- package/http.js +5 -32
- package/index.d.ts +9 -2
- package/index.js +40 -51
- package/index.node.d.ts +24 -0
- package/index.node.js +35 -0
- package/package.json +13 -3
- package/prebuilds/darwin-arm64/colibri_native.node +0 -0
- package/prebuilds/darwin-x64/colibri_native.node +0 -0
- package/prebuilds/linux-arm64/colibri_native.node +0 -0
- package/prebuilds/linux-x64/colibri_native.node +0 -0
- package/prebuilds/win32-x64/colibri_native.node +0 -0
- package/runtime.d.ts +88 -0
- package/runtime.js +49 -0
- package/runtime_node.d.ts +28 -0
- package/runtime_node.js +110 -0
- package/runtime_wasm.d.ts +28 -0
- package/runtime_wasm.js +129 -0
- package/types.d.ts +4 -1
- package/wasm.d.ts +7 -0
- package/wasm.js +11 -0
- package/wasm_cjs.d.ts +7 -0
- package/wasm_cjs.js +9 -0
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|

|
|
11
11
|
[](https://www.npmjs.com/package/@corpus-core/colibri-stateless)
|
|
12
12
|
|
|
13
|
-
Colibri Stateless is a highly efficient prover/verifier for Ethereum (with upcoming support for Layer-2s such as OP-Stack). This package runs the C core as WebAssembly in Node.js
|
|
13
|
+
Colibri Stateless is a highly efficient prover/verifier for Ethereum (with upcoming support for Layer-2s such as OP-Stack). This package runs the C core as WebAssembly in the browser and as a **native addon in Node.js** (with automatic WASM fallback), and implements the [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) provider interface — so it drops straight into ethers, web3.js, or viem while cryptographically verifying every response.
|
|
14
14
|
|
|
15
15
|
[**Website**](https://www.corpuscore.tech/colibri) · [**Docs**](https://corpus-core.gitbook.io/specification-colibri-stateless/developer-guide/bindings/javascript-typescript) · [**Whitepaper**](https://corpus-core.gitbook.io/whitepaper-colibri-stateless) · [**Privacy (PAP)**](https://corpus-core.gitbook.io/pap-colibri-stateless)
|
|
16
16
|
|
|
@@ -24,6 +24,7 @@ Colibri Stateless is a highly efficient prover/verifier for Ethereum (with upcom
|
|
|
24
24
|
- **`eth_getLogs` completeness proofs** — cryptographic guarantee that for a requested block range no matching event was omitted (opt-in via `logs_completeness`).
|
|
25
25
|
- **Fully verified local transaction simulation** — simulate a transaction against verified state *before signing*, so users can be shown exactly what a transaction will do.
|
|
26
26
|
- **Tiny & fast** — most requests are barely slower than a plain RPC call — see the [benchmarks](https://corpus-core.gitbook.io/specification-colibri-stateless/specifications/ethereum/benchmark).
|
|
27
|
+
- **Native speed in Node.js** — bundled N-API prebuilds with platform-optimized [blst](https://github.com/supranational/blst) assembly make proof verification ~25-30x faster than WASM; unsupported platforms transparently fall back to WASM.
|
|
27
28
|
- **Privacy-aware** — Pragmatic Adaptive Privacy (PAP) mode. See the [Privacy Whitepaper](https://corpus-core.gitbook.io/pap-colibri-stateless).
|
|
28
29
|
|
|
29
30
|
## Installation
|
|
@@ -58,6 +59,19 @@ const { default: Colibri, Strategy, set_wasm_url } = require("@corpus-core/colib
|
|
|
58
59
|
const client = new Colibri();
|
|
59
60
|
```
|
|
60
61
|
|
|
62
|
+
## Native Addon in Node.js
|
|
63
|
+
|
|
64
|
+
In Node.js the package automatically loads a prebuilt native addon (N-API) instead of the WASM build. It statically links the C core with platform-optimized [blst](https://github.com/supranational/blst) assembly, making BLS pairing — the dominant cost of proof verification — **~25-30x faster**. No code changes or optional dependencies are needed; browser bundles are unaffected.
|
|
65
|
+
|
|
66
|
+
Prebuilds are bundled for `linux-x64`, `linux-arm64`, `darwin-arm64`, `darwin-x64` and `win32-x64`. On any other platform (or if loading fails) the client transparently falls back to WASM.
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
import { getRuntime } from "@corpus-core/colibri-stateless";
|
|
70
|
+
console.log((await getRuntime()).kind); // 'native' or 'wasm'
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Overrides: `C4_DISABLE_NATIVE=1` (always WASM), `C4_FORCE_NATIVE=1` (fail instead of falling back), `C4_NATIVE_ADDON=<path>` (explicit addon path). See the [docs](https://corpus-core.gitbook.io/specification-colibri-stateless/developer-guide/bindings/javascript-typescript) for details and build-from-source instructions.
|
|
74
|
+
|
|
61
75
|
## Using Colibri as RPC Provider
|
|
62
76
|
|
|
63
77
|
The Colibri Class implements the EIP-1193 Interface, so any library supporting EIP-1193 Providers can easily use Colibri as RPCProvider.
|
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";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_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)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}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 EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;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["s"]()}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"){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["r"];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={204396:($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},204584:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},204727:$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"]);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 SYSCALLS={varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs}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 _emscripten_date_now=()=>Date.now();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 runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;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 wasmImports={a:___assert_fail,b:___cxa_throw,f:___syscall_fcntl64,j:___syscall_ioctl,k:___syscall_openat,m:__abort_js,l:__tzset_js,d:_emscripten_asm_const_int,g:_emscripten_date_now,n:_emscripten_resize_heap,p:_environ_get,q:_environ_sizes_get,c:_exit,h:_fd_close,i:_fd_read,o:_fd_seek,e:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["s"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["t"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["u"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["v"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["w"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["x"];var _c4w_create_verify_ctx=Module["_c4w_create_verify_ctx"]=wasmExports["y"];var _c4w_free_verify_ctx=Module["_c4w_free_verify_ctx"]=wasmExports["z"];var _free=Module["_free"]=wasmExports["A"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["B"];var _c4w_get_method_type=Module["_c4w_get_method_type"]=wasmExports["C"];var _c4w_create_rpc_ctx=Module["_c4w_create_rpc_ctx"]=wasmExports["D"];var _c4w_execute_rpc_ctx=Module["_c4w_execute_rpc_ctx"]=wasmExports["E"];var _c4w_free_rpc_ctx=Module["_c4w_free_rpc_ctx"]=wasmExports["F"];var _c4w_set_checkpoint=Module["_c4w_set_checkpoint"]=wasmExports["G"];var _c4w_rpc_ctx_set_witness_keys=Module["_c4w_rpc_ctx_set_witness_keys"]=wasmExports["H"];var _c4w_rpc_ctx_set_proxy_urls=Module["_c4w_rpc_ctx_set_proxy_urls"]=wasmExports["I"];var _c4w_rpc_ctx_set_min_latest_block_ts=Module["_c4w_rpc_ctx_set_min_latest_block_ts"]=wasmExports["J"];var _c4w_decode_proof=Module["_c4w_decode_proof"]=wasmExports["K"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["L"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["M"];var _init_storage=Module["_init_storage"]=wasmExports["N"];var _c4w_get_current_version_number=Module["_c4w_get_current_version_number"]=wasmExports["O"];var _malloc=Module["_malloc"]=wasmExports["Q"];var __emscripten_stack_restore=wasmExports["R"];var __emscripten_stack_alloc=wasmExports["S"];var _emscripten_stack_get_current=wasmExports["T"];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";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_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)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}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 EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;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["s"]()}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"){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["r"];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={215420:($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},215608:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},215751:$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"]);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 SYSCALLS={varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs}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 _emscripten_date_now=()=>Date.now();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 runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;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 wasmImports={a:___assert_fail,b:___cxa_throw,f:___syscall_fcntl64,j:___syscall_ioctl,k:___syscall_openat,m:__abort_js,l:__tzset_js,d:_emscripten_asm_const_int,g:_emscripten_date_now,n:_emscripten_resize_heap,p:_environ_get,q:_environ_sizes_get,c:_exit,h:_fd_close,i:_fd_read,o:_fd_seek,e:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["s"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["t"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["u"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["v"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["w"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["x"];var _c4w_create_verify_ctx=Module["_c4w_create_verify_ctx"]=wasmExports["y"];var _c4w_free_verify_ctx=Module["_c4w_free_verify_ctx"]=wasmExports["z"];var _free=Module["_free"]=wasmExports["A"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["B"];var _c4w_get_method_type=Module["_c4w_get_method_type"]=wasmExports["C"];var _c4w_create_rpc_ctx=Module["_c4w_create_rpc_ctx"]=wasmExports["D"];var _c4w_execute_rpc_ctx=Module["_c4w_execute_rpc_ctx"]=wasmExports["E"];var _c4w_free_rpc_ctx=Module["_c4w_free_rpc_ctx"]=wasmExports["F"];var _c4w_set_checkpoint=Module["_c4w_set_checkpoint"]=wasmExports["G"];var _c4w_rpc_ctx_set_witness_keys=Module["_c4w_rpc_ctx_set_witness_keys"]=wasmExports["H"];var _c4w_rpc_ctx_set_proxy_urls=Module["_c4w_rpc_ctx_set_proxy_urls"]=wasmExports["I"];var _c4w_rpc_ctx_set_min_latest_block_ts=Module["_c4w_rpc_ctx_set_min_latest_block_ts"]=wasmExports["J"];var _c4w_decode_proof=Module["_c4w_decode_proof"]=wasmExports["K"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["L"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["M"];var _init_storage=Module["_init_storage"]=wasmExports["N"];var _c4w_get_current_version_number=Module["_c4w_get_current_version_number"]=wasmExports["O"];var _malloc=Module["_malloc"]=wasmExports["Q"];var __emscripten_stack_restore=wasmExports["R"];var __emscripten_stack_alloc=wasmExports["S"];var _emscripten_stack_get_current=wasmExports["T"];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/cjs/http.js
CHANGED
|
@@ -3,29 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.fetch_from_servers = fetch_from_servers;
|
|
4
4
|
exports.fetch_rpc = fetch_rpc;
|
|
5
5
|
exports.handle_request = handle_request;
|
|
6
|
-
/**
|
|
7
|
-
* Copyright (c) 2025 corpus.core
|
|
8
|
-
*
|
|
9
|
-
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
10
|
-
* this software and associated documentation files (the "Software"), to deal in
|
|
11
|
-
* the Software without restriction, including without limitation the rights to
|
|
12
|
-
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
13
|
-
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
14
|
-
* subject to the following conditions:
|
|
15
|
-
*
|
|
16
|
-
* The above copyright notice and this permission notice shall be included in all
|
|
17
|
-
* copies or substantial portions of the Software.
|
|
18
|
-
*
|
|
19
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
-
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
21
|
-
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
22
|
-
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
23
|
-
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
24
|
-
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
25
|
-
*
|
|
26
|
-
* SPDX-License-Identifier: MIT
|
|
27
|
-
*/
|
|
28
|
-
const wasm_js_1 = require("./wasm.js");
|
|
29
6
|
function joinPath(base, path) {
|
|
30
7
|
if (!path)
|
|
31
8
|
return base;
|
|
@@ -163,11 +140,11 @@ async function fetch_rpc(urls, payload, as_proof = false, fetchFn = globalThis.f
|
|
|
163
140
|
/**
|
|
164
141
|
* Handles a C4 data request by fetching from configured servers, setting the
|
|
165
142
|
* response or error back into the C context, and leveraging cache if present.
|
|
143
|
+
* @param runtime The active runtime the request originated from
|
|
166
144
|
* @param req DataRequest descriptor from C
|
|
167
145
|
* @param conf Colibri configuration
|
|
168
146
|
*/
|
|
169
|
-
async function handle_request(req, conf) {
|
|
170
|
-
const free_buffers = [];
|
|
147
|
+
async function handle_request(runtime, req, conf) {
|
|
171
148
|
// Honor a requested delay before (re-)executing (e.g. oblivious-node retry backoff).
|
|
172
149
|
if (req.delay && req.delay > 0)
|
|
173
150
|
await new Promise(resolve => setTimeout(resolve, req.delay));
|
|
@@ -190,7 +167,6 @@ async function handle_request(req, conf) {
|
|
|
190
167
|
servers = conf.rpcs || [...((conf.prover || []).map(p => p + (p.endsWith('/') ? '' : '/') + 'unverified_rpc'))];
|
|
191
168
|
break;
|
|
192
169
|
}
|
|
193
|
-
const c4w = await (0, wasm_js_1.getC4w)();
|
|
194
170
|
let path = (req.type == 'eth_rpc' && req.payload)
|
|
195
171
|
? `rpc: ${req.payload?.method}(${req.payload?.params.join(',')})`
|
|
196
172
|
: req.url;
|
|
@@ -200,7 +176,7 @@ async function handle_request(req, conf) {
|
|
|
200
176
|
if (data) {
|
|
201
177
|
if (conf.debug)
|
|
202
178
|
log(`::: ${path} (len=${data.length} bytes) CACHED`);
|
|
203
|
-
|
|
179
|
+
runtime.reqSetResponse(req, data, 0);
|
|
204
180
|
if (conf.onTransfer)
|
|
205
181
|
conf.onTransfer(data.length, req);
|
|
206
182
|
return;
|
|
@@ -210,7 +186,7 @@ async function handle_request(req, conf) {
|
|
|
210
186
|
const accept = req.encoding == 'json' ? 'json' : 'octet';
|
|
211
187
|
const fetchFn = conf.fetch || globalThis.fetch;
|
|
212
188
|
const { data, nodeIndex } = await fetch_from_servers(servers, req.url || '', req.method, req.payload, accept, req.exclude_mask, fetchFn, req.ttl);
|
|
213
|
-
|
|
189
|
+
runtime.reqSetResponse(req, data, nodeIndex);
|
|
214
190
|
if (conf.onTransfer)
|
|
215
191
|
conf.onTransfer(data.length, req);
|
|
216
192
|
if (conf.debug)
|
|
@@ -220,11 +196,8 @@ async function handle_request(req, conf) {
|
|
|
220
196
|
}
|
|
221
197
|
catch (e) {
|
|
222
198
|
const last_error = (e instanceof Error) ? e.message : String(e);
|
|
223
|
-
|
|
199
|
+
runtime.reqSetError(req, last_error, 0);
|
|
224
200
|
if (conf.debug)
|
|
225
201
|
log(`::: ${path} (Error: ${last_error})`);
|
|
226
202
|
}
|
|
227
|
-
finally {
|
|
228
|
-
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
229
|
-
}
|
|
230
203
|
}
|
package/cjs/index.js
CHANGED
|
@@ -22,9 +22,10 @@
|
|
|
22
22
|
* SPDX-License-Identifier: MIT
|
|
23
23
|
*/
|
|
24
24
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
-
exports.PrototypeProtection = exports.TransactionVerifier = exports.MethodType = exports.ProviderRpcError = exports.
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
exports.PrototypeProtection = exports.TransactionVerifier = exports.MethodType = exports.ProviderRpcError = exports.getRuntime = exports.set_wasm_url = exports.Strategy = void 0;
|
|
26
|
+
exports.decode_proof = decode_proof;
|
|
27
|
+
// Runtime abstraction: WASM (browser/default) or native addon (Node.js entry)
|
|
28
|
+
const runtime_js_1 = require("./runtime.js");
|
|
28
29
|
const eventEmitter_js_1 = require("./eventEmitter.js");
|
|
29
30
|
const connectionState_js_1 = require("./connectionState.js");
|
|
30
31
|
const types_js_1 = require("./types.js");
|
|
@@ -37,9 +38,19 @@ exports.Strategy = strategy_js_1.default;
|
|
|
37
38
|
const transactionVerifier_js_1 = require("./transactionVerifier.js");
|
|
38
39
|
const http_js_1 = require("./http.js");
|
|
39
40
|
// Public helper for controlling WASM loading behavior in Node/bundlers.
|
|
40
|
-
var
|
|
41
|
-
Object.defineProperty(exports, "set_wasm_url", { enumerable: true, get: function () { return
|
|
42
|
-
|
|
41
|
+
var wasm_js_1 = require("./wasm.js");
|
|
42
|
+
Object.defineProperty(exports, "set_wasm_url", { enumerable: true, get: function () { return wasm_js_1.set_wasm_url; } });
|
|
43
|
+
// Runtime introspection (e.g. to check whether the native addon is active in Node).
|
|
44
|
+
var runtime_js_2 = require("./runtime.js");
|
|
45
|
+
Object.defineProperty(exports, "getRuntime", { enumerable: true, get: function () { return runtime_js_2.getRuntime; } });
|
|
46
|
+
/**
|
|
47
|
+
* Decodes a serialized proof into its JSON representation using the active runtime.
|
|
48
|
+
* @param proof The proof bytes
|
|
49
|
+
* @return The decoded proof as JSON
|
|
50
|
+
*/
|
|
51
|
+
async function decode_proof(proof) {
|
|
52
|
+
return (await (0, runtime_js_1.getRuntime)()).decodeProof(proof);
|
|
53
|
+
}
|
|
43
54
|
// Re-export transaction verification utilities
|
|
44
55
|
var transactionVerifier_js_2 = require("./transactionVerifier.js");
|
|
45
56
|
Object.defineProperty(exports, "TransactionVerifier", { enumerable: true, get: function () { return transactionVerifier_js_2.TransactionVerifier; } });
|
|
@@ -133,12 +144,9 @@ class C4Client {
|
|
|
133
144
|
* @returns The method type
|
|
134
145
|
*/
|
|
135
146
|
async getMethodSupport(method, args) {
|
|
136
|
-
const
|
|
137
|
-
const free_buffers = [];
|
|
147
|
+
const runtime = await (0, runtime_js_1.getRuntime)();
|
|
138
148
|
const paramsStr = args ? JSON.stringify(args) : null;
|
|
139
|
-
|
|
140
|
-
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
141
|
-
return method_type;
|
|
149
|
+
return runtime.getMethodType(BigInt(this.config.chainId), method, paramsStr, this.verify_flags);
|
|
142
150
|
}
|
|
143
151
|
/**
|
|
144
152
|
* Creates a proof for the given method and arguments.
|
|
@@ -147,30 +155,27 @@ class C4Client {
|
|
|
147
155
|
* @returns The proof
|
|
148
156
|
*/
|
|
149
157
|
async createProof(method, args) {
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
let ctx = 0;
|
|
158
|
+
const runtime = await (0, runtime_js_1.getRuntime)();
|
|
159
|
+
let ctx = null;
|
|
153
160
|
try {
|
|
154
|
-
|
|
155
|
-
ctx = c4w._c4w_create_proof_ctx((0, wasm_js_1.as_char_ptr)(method, c4w, free_buffers), (0, wasm_js_1.as_char_ptr)(JSON.stringify(args), c4w, free_buffers), BigInt(this.config.chainId), this.flags);
|
|
161
|
+
ctx = runtime.createProverCtx(method, JSON.stringify(args), BigInt(this.config.chainId), this.flags);
|
|
156
162
|
while (true) {
|
|
157
|
-
const state =
|
|
163
|
+
const state = runtime.executeProverCtx(ctx);
|
|
158
164
|
switch (state.status) {
|
|
159
165
|
case "success":
|
|
160
|
-
return
|
|
166
|
+
return state.result;
|
|
161
167
|
case "error":
|
|
162
168
|
throw new Error(state.error);
|
|
163
169
|
case "pending": {
|
|
164
|
-
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(req, this.config)));
|
|
170
|
+
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(runtime, req, this.config)));
|
|
165
171
|
break;
|
|
166
172
|
}
|
|
167
173
|
}
|
|
168
174
|
}
|
|
169
175
|
}
|
|
170
176
|
finally {
|
|
171
|
-
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
172
177
|
if (ctx)
|
|
173
|
-
|
|
178
|
+
runtime.freeProverCtx(ctx);
|
|
174
179
|
}
|
|
175
180
|
}
|
|
176
181
|
/**
|
|
@@ -181,20 +186,12 @@ class C4Client {
|
|
|
181
186
|
* @returns The result
|
|
182
187
|
*/
|
|
183
188
|
async verifyProof(method, args, proof) {
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
let ctx = 0;
|
|
189
|
+
const runtime = await (0, runtime_js_1.getRuntime)();
|
|
190
|
+
let ctx = null;
|
|
187
191
|
try {
|
|
188
|
-
|
|
189
|
-
const checkpoint_ptr = this.config.trusted_checkpoint
|
|
190
|
-
? (0, wasm_js_1.as_char_ptr)(this.config.trusted_checkpoint, c4w, free_buffers)
|
|
191
|
-
: 0;
|
|
192
|
-
const witness_keys_ptr = this.config.checkpoint_witness_keys
|
|
193
|
-
? (0, wasm_js_1.as_char_ptr)(this.config.checkpoint_witness_keys, c4w, free_buffers)
|
|
194
|
-
: 0;
|
|
195
|
-
ctx = c4w._c4w_create_verify_ctx((0, wasm_js_1.copy_to_c)(proof, c4w, free_buffers), proof.length, (0, wasm_js_1.as_char_ptr)(method, c4w, free_buffers), (0, wasm_js_1.as_char_ptr)(JSON.stringify(args), c4w, free_buffers), BigInt(this.config.chainId), checkpoint_ptr, witness_keys_ptr, this.verify_flags, this.get_min_latest_block_ts());
|
|
192
|
+
ctx = runtime.createVerifyCtx(proof, method, JSON.stringify(args), BigInt(this.config.chainId), this.config.trusted_checkpoint || null, this.config.checkpoint_witness_keys || null, this.verify_flags, this.get_min_latest_block_ts());
|
|
196
193
|
while (true) {
|
|
197
|
-
const state =
|
|
194
|
+
const state = runtime.verifyProof(ctx);
|
|
198
195
|
switch (state.status) {
|
|
199
196
|
case "success":
|
|
200
197
|
return state.result;
|
|
@@ -203,16 +200,15 @@ class C4Client {
|
|
|
203
200
|
case "error":
|
|
204
201
|
throw new Error(state.error);
|
|
205
202
|
case "pending": {
|
|
206
|
-
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(req, this.config)));
|
|
203
|
+
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(runtime, req, this.config)));
|
|
207
204
|
break;
|
|
208
205
|
}
|
|
209
206
|
}
|
|
210
207
|
}
|
|
211
208
|
}
|
|
212
209
|
finally {
|
|
213
|
-
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
214
210
|
if (ctx)
|
|
215
|
-
|
|
211
|
+
runtime.freeVerifyCtx(ctx);
|
|
216
212
|
}
|
|
217
213
|
}
|
|
218
214
|
/**
|
|
@@ -234,9 +230,8 @@ class C4Client {
|
|
|
234
230
|
method_type = await this.getMethodSupport(method, args);
|
|
235
231
|
if (method_type === types_js_1.MethodType.PROOFABLE && this.config.verify && !this.config.verify(method, args))
|
|
236
232
|
return await (0, http_js_1.fetch_rpc)(this.config.rpcs, { method, params: args }, false, this.config.fetch);
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
let ctx = 0;
|
|
233
|
+
const runtime = await (0, runtime_js_1.getRuntime)();
|
|
234
|
+
let ctx = null;
|
|
240
235
|
try {
|
|
241
236
|
const prover_mode_map = { local: 0, remote: 1, hybrid: 2, proxy: 3, light_client: 4 };
|
|
242
237
|
const resolved_mode = this.config.prover_mode ?? (this.config.prover?.length ? 'remote' : 'local');
|
|
@@ -244,19 +239,16 @@ class C4Client {
|
|
|
244
239
|
let prover_flags = this.flags;
|
|
245
240
|
if (this.config.zk_proof)
|
|
246
241
|
prover_flags |= (1 << 7);
|
|
247
|
-
ctx =
|
|
248
|
-
if (resolved_mode === 'proxy')
|
|
249
|
-
|
|
250
|
-
const beacon_csv = this.config.beacon_apis.join(',');
|
|
251
|
-
c4w._c4w_rpc_ctx_set_proxy_urls(ctx, (0, wasm_js_1.as_char_ptr)(rpc_csv, c4w, free_buffers), (0, wasm_js_1.as_char_ptr)(beacon_csv, c4w, free_buffers));
|
|
252
|
-
}
|
|
242
|
+
ctx = runtime.createRpcCtx(method, JSON.stringify(args || []), BigInt(this.config.chainId), prover_flags, this.verify_flags, native_mode);
|
|
243
|
+
if (resolved_mode === 'proxy')
|
|
244
|
+
runtime.rpcCtxSetProxyUrls(ctx, this.config.rpcs.join(','), this.config.beacon_apis.join(','));
|
|
253
245
|
if (this.config.trusted_checkpoint)
|
|
254
|
-
|
|
246
|
+
runtime.setCheckpoint(BigInt(this.config.chainId), this.config.trusted_checkpoint);
|
|
255
247
|
if (this.config.checkpoint_witness_keys)
|
|
256
|
-
|
|
257
|
-
|
|
248
|
+
runtime.rpcCtxSetWitnessKeys(ctx, this.config.checkpoint_witness_keys);
|
|
249
|
+
runtime.rpcCtxSetMinLatestBlockTs(ctx, this.get_min_latest_block_ts());
|
|
258
250
|
while (true) {
|
|
259
|
-
const state =
|
|
251
|
+
const state = runtime.executeRpcCtx(ctx);
|
|
260
252
|
switch (state.status) {
|
|
261
253
|
case "success":
|
|
262
254
|
return state.result;
|
|
@@ -270,20 +262,18 @@ class C4Client {
|
|
|
270
262
|
}
|
|
271
263
|
throw new Error(state.error);
|
|
272
264
|
case "pending":
|
|
273
|
-
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(req, this.config)));
|
|
265
|
+
await Promise.all(state.requests.map((req) => (0, http_js_1.handle_request)(runtime, req, this.config)));
|
|
274
266
|
break;
|
|
275
267
|
}
|
|
276
268
|
}
|
|
277
269
|
}
|
|
278
270
|
finally {
|
|
279
|
-
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
280
271
|
if (ctx)
|
|
281
|
-
|
|
272
|
+
runtime.freeRpcCtx(ctx);
|
|
282
273
|
}
|
|
283
274
|
}
|
|
284
275
|
static async register_storage(storage) {
|
|
285
|
-
|
|
286
|
-
c4w.storage = storage;
|
|
276
|
+
(await (0, runtime_js_1.getRuntime)()).registerStorage(storage);
|
|
287
277
|
}
|
|
288
278
|
async request(args) {
|
|
289
279
|
if (!this.connectionState.initialConnectionAttempted) {
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2026 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
25
|
+
if (k2 === undefined) k2 = k;
|
|
26
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
27
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
28
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
29
|
+
}
|
|
30
|
+
Object.defineProperty(o, k2, desc);
|
|
31
|
+
}) : (function(o, m, k, k2) {
|
|
32
|
+
if (k2 === undefined) k2 = k;
|
|
33
|
+
o[k2] = m[k];
|
|
34
|
+
}));
|
|
35
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
36
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.default = void 0;
|
|
40
|
+
/**
|
|
41
|
+
* Node.js entry point (selected via `package.json` conditional exports).
|
|
42
|
+
*
|
|
43
|
+
* Uses the native N-API addon when a prebuild for the current platform is
|
|
44
|
+
* available (blst with platform-optimized assembly, ~10x faster BLS pairing)
|
|
45
|
+
* and transparently falls back to the WASM build otherwise. Browser bundlers
|
|
46
|
+
* never see this file.
|
|
47
|
+
*/
|
|
48
|
+
const runtime_js_1 = require("./runtime.js");
|
|
49
|
+
const runtime_node_js_1 = require("./runtime_node.js");
|
|
50
|
+
(0, runtime_js_1.setRuntimeProvider)(runtime_node_js_1.getNodeRuntime);
|
|
51
|
+
__exportStar(require("./index.js"), exports);
|
|
52
|
+
var index_js_1 = require("./index.js");
|
|
53
|
+
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return index_js_1.default; } });
|
package/cjs/runtime.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2026 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.setRuntimeProvider = setRuntimeProvider;
|
|
26
|
+
exports.getRuntime = getRuntime;
|
|
27
|
+
// The active provider defaults to the WASM runtime and is replaced by the
|
|
28
|
+
// Node entry point (`index.node.ts`) with the native-first provider.
|
|
29
|
+
// Lazy import keeps browser bundles free of unused code paths.
|
|
30
|
+
let activeProvider = async () => (await Promise.resolve().then(() => require('./runtime_wasm.js'))).getWasmRuntime();
|
|
31
|
+
let cached = null;
|
|
32
|
+
/**
|
|
33
|
+
* Replaces the runtime provider (e.g. native addon in Node.js).
|
|
34
|
+
*
|
|
35
|
+
* Intended to be called once by the entry point before the first
|
|
36
|
+
* `getRuntime()` use. Calling it later resets the cached runtime, so the
|
|
37
|
+
* next `getRuntime()` initializes the new provider - context handles
|
|
38
|
+
* created by the previous runtime must not be used afterwards.
|
|
39
|
+
* @param provider Factory returning an initialized runtime
|
|
40
|
+
*/
|
|
41
|
+
function setRuntimeProvider(provider) {
|
|
42
|
+
activeProvider = provider;
|
|
43
|
+
cached = null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Returns the active runtime (initialized lazily, cached afterwards).
|
|
47
|
+
* @return The active C4Runtime instance
|
|
48
|
+
*/
|
|
49
|
+
function getRuntime() {
|
|
50
|
+
if (!cached)
|
|
51
|
+
cached = activeProvider();
|
|
52
|
+
return cached;
|
|
53
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2026 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.getNodeRuntime = getNodeRuntime;
|
|
26
|
+
const wasm_shared_js_1 = require("./wasm_shared.js");
|
|
27
|
+
const wasm_js_1 = require("./wasm.js");
|
|
28
|
+
async function loadNativeBinding() {
|
|
29
|
+
const { createRequire } = await Promise.resolve().then(() => require('node:module'));
|
|
30
|
+
const { join, dirname } = await Promise.resolve().then(() => require('node:path'));
|
|
31
|
+
const fs = await Promise.resolve().then(() => require('node:fs'));
|
|
32
|
+
// Directory of the compiled JS: resolved by wasm.ts (ESM: import.meta.url)
|
|
33
|
+
// or wasm_cjs.ts (CJS: __dirname), which are swapped at build time.
|
|
34
|
+
const dir = await (0, wasm_js_1.module_dir)();
|
|
35
|
+
const requireNative = createRequire(join(dir, 'noop.js'));
|
|
36
|
+
const candidates = [];
|
|
37
|
+
if (process.env.C4_NATIVE_ADDON)
|
|
38
|
+
candidates.push(process.env.C4_NATIVE_ADDON);
|
|
39
|
+
const target = `${process.platform}-${process.arch}`;
|
|
40
|
+
// The CJS build lives in a `cjs/` subfolder; prebuilds sit at the package root.
|
|
41
|
+
candidates.push(join(dir, 'prebuilds', target, 'colibri_native.node'));
|
|
42
|
+
candidates.push(join(dirname(dir), 'prebuilds', target, 'colibri_native.node'));
|
|
43
|
+
for (const candidate of candidates) {
|
|
44
|
+
if (fs.existsSync(candidate))
|
|
45
|
+
return requireNative(candidate);
|
|
46
|
+
}
|
|
47
|
+
throw new Error(`no native colibri addon found for ${target} (checked: ${candidates.join(', ')})`);
|
|
48
|
+
}
|
|
49
|
+
function createNativeRuntime(binding) {
|
|
50
|
+
// Most methods are direct pass-throughs (N-API functions don't need `this`);
|
|
51
|
+
// only status parsing and the req_ptr string conversion add logic.
|
|
52
|
+
return {
|
|
53
|
+
kind: 'native',
|
|
54
|
+
getMethodType: binding.getMethodType,
|
|
55
|
+
createProverCtx: binding.createProverCtx,
|
|
56
|
+
executeProverCtx(ctx) {
|
|
57
|
+
const state = JSON.parse(binding.executeProverCtx(ctx));
|
|
58
|
+
// The JSON status carries the proof as native pointer (unusable in JS);
|
|
59
|
+
// fetch the bytes through the dedicated accessor instead.
|
|
60
|
+
if (state.status === 'success')
|
|
61
|
+
state.result = binding.getProof(ctx);
|
|
62
|
+
return state;
|
|
63
|
+
},
|
|
64
|
+
freeProverCtx: binding.freeProverCtx,
|
|
65
|
+
createVerifyCtx: binding.createVerifyCtx,
|
|
66
|
+
verifyProof: (ctx) => JSON.parse(binding.verifyProof(ctx)),
|
|
67
|
+
freeVerifyCtx: binding.freeVerifyCtx,
|
|
68
|
+
createRpcCtx: binding.createRpcCtx,
|
|
69
|
+
executeRpcCtx: (ctx) => JSON.parse(binding.executeRpcCtx(ctx)),
|
|
70
|
+
freeRpcCtx: binding.freeRpcCtx,
|
|
71
|
+
rpcCtxSetProxyUrls: binding.rpcCtxSetProxyUrls,
|
|
72
|
+
rpcCtxSetWitnessKeys: binding.rpcCtxSetWitnessKeys,
|
|
73
|
+
rpcCtxSetMinLatestBlockTs: binding.rpcCtxSetMinLatestBlockTs,
|
|
74
|
+
setCheckpoint: binding.setCheckpoint,
|
|
75
|
+
reqSetResponse: (req, data, nodeIndex) => binding.reqSetResponse(String(req.req_ptr), data, nodeIndex),
|
|
76
|
+
reqSetError: (req, error, nodeIndex) => binding.reqSetError(String(req.req_ptr), error, nodeIndex),
|
|
77
|
+
decodeProof(proof) {
|
|
78
|
+
const json = binding.decodeProof(proof);
|
|
79
|
+
if (!json)
|
|
80
|
+
throw new Error('Unknown proof format');
|
|
81
|
+
return JSON.parse(json);
|
|
82
|
+
},
|
|
83
|
+
registerStorage: binding.registerStorage,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
let runtime = null;
|
|
87
|
+
async function initNodeRuntime() {
|
|
88
|
+
if (process.env.C4_DISABLE_NATIVE !== '1') {
|
|
89
|
+
try {
|
|
90
|
+
const binding = await loadNativeBinding();
|
|
91
|
+
const rt = createNativeRuntime(binding);
|
|
92
|
+
// Same default persistence behavior as the WASM runtime (fs-based in Node).
|
|
93
|
+
rt.registerStorage(await (0, wasm_shared_js_1.get_default_storage)());
|
|
94
|
+
return rt;
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
if (process.env.C4_FORCE_NATIVE === '1')
|
|
98
|
+
throw e;
|
|
99
|
+
if (process.env.C4_DEBUG_NATIVE === '1')
|
|
100
|
+
console.warn('colibri: native addon unavailable, falling back to WASM:', e);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return (await Promise.resolve().then(() => require('./runtime_wasm.js'))).getWasmRuntime();
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Returns the (cached) Node runtime: native addon if available, otherwise WASM.
|
|
107
|
+
* @return Initialized runtime
|
|
108
|
+
*/
|
|
109
|
+
function getNodeRuntime() {
|
|
110
|
+
if (!runtime)
|
|
111
|
+
runtime = initNodeRuntime();
|
|
112
|
+
return runtime;
|
|
113
|
+
}
|