use wasmtime::{Config, Engine, Instance, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc};
use crate::corroborate::FunctionRun;
use crate::error::{QueryError, QueryResult};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RunLimits {
pub max_fuel: u64,
pub max_mem_mb: u32,
}
impl Default for RunLimits {
fn default() -> Self {
Self {
max_fuel: 100_000_000,
max_mem_mb: 64,
}
}
}
#[derive(Clone, Debug)]
pub struct Execution {
pub output: Vec<u8>,
pub run: FunctionRun,
}
struct HostState {
limits: StoreLimits,
}
pub struct FunctionRuntime {
engine: Engine,
}
impl Default for FunctionRuntime {
fn default() -> Self {
Self::new()
}
}
impl FunctionRuntime {
pub(crate) fn engine(&self) -> &Engine {
&self.engine
}
pub fn new() -> Self {
let mut config = Config::new();
config.consume_fuel(true);
config.wasm_backtrace(false);
let engine = Engine::new(&config).expect("wasmtime engine (fuel) construction");
Self { engine }
}
pub fn run(
&self,
module_wasm: &[u8],
input: &[u8],
limits: &RunLimits,
) -> QueryResult<Execution> {
let workload_hash = hash(module_wasm);
let input_digest = hash(input);
let module = Module::new(&self.engine, module_wasm)
.map_err(|e| QueryError::Compile(e.to_string()))?;
let max_bytes = limits.max_mem_mb as usize * 1024 * 1024;
let mut store = Store::new(
&self.engine,
HostState {
limits: StoreLimitsBuilder::new().memory_size(max_bytes).build(),
},
);
store.limiter(|h| &mut h.limits);
store
.set_fuel(limits.max_fuel)
.map_err(|e| QueryError::Fuel(e.to_string()))?;
let instance = Instance::new(&mut store, &module, &[])
.map_err(|e| QueryError::Instantiate(e.to_string()))?;
let memory = instance
.get_memory(&mut store, "memory")
.ok_or(QueryError::MissingExport("memory"))?;
let alloc: TypedFunc<i32, i32> = instance
.get_typed_func(&mut store, "alloc")
.map_err(|_| QueryError::MissingExport("alloc"))?;
let run: TypedFunc<(i32, i32), i64> = instance
.get_typed_func(&mut store, "run")
.map_err(|_| QueryError::MissingExport("run"))?;
let in_len =
i32::try_from(input.len()).map_err(|_| QueryError::Abi("input too large".into()))?;
let in_ptr = alloc
.call(&mut store, in_len)
.map_err(|e| QueryError::Trap(e.to_string()))?;
memory
.write(&mut store, in_ptr as usize, input)
.map_err(|e| QueryError::Abi(format!("input write: {e}")))?;
let packed = run
.call(&mut store, (in_ptr, in_len))
.map_err(|e| QueryError::Trap(e.to_string()))?;
let packed = packed as u64;
let out_ptr = (packed >> 32) as usize;
let out_len = (packed & 0xFFFF_FFFF) as usize;
let mut output = vec![0u8; out_len];
memory
.read(&store, out_ptr, &mut output)
.map_err(|e| QueryError::Abi(format!("output read at {out_ptr}+{out_len}: {e}")))?;
let output_digest = hash(&output);
let remaining = store.get_fuel().map_err(|e| QueryError::Fuel(e.to_string()))?;
let fuel_used = limits.max_fuel.saturating_sub(remaining);
let mem_peak_mb = (memory.data_size(&store) / (1024 * 1024)) as u32;
Ok(Execution {
output,
run: FunctionRun {
workload_hash,
input_digest,
output_digest,
fuel_used,
mem_peak_mb,
},
})
}
}
fn hash(bytes: &[u8]) -> [u8; 32] {
*blake3::hash(bytes).as_bytes()
}