use serde::{Deserialize, Serialize};
use std::time::Duration;
pub struct Sandbox {
max_fuel: u64,
max_memory_pages: u32,
timeout: Duration,
}
impl Sandbox {
pub fn new(max_fuel: u64, max_memory_pages: u32, timeout_ms: u64) -> Self {
Self {
max_fuel,
max_memory_pages,
timeout: Duration::from_millis(timeout_ms),
}
}
pub fn default_limits() -> Self {
Self {
max_fuel: 1_000_000,
max_memory_pages: 16, timeout: Duration::from_secs(5),
}
}
pub fn execute(&self, _wasm_bytes: &[u8], _input: &[u8]) -> SandboxResult<Vec<u8>> {
Ok(Vec::new())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionResult {
pub output: Vec<u8>,
pub success: bool,
pub fuel_consumed: u64,
pub memory_used_pages: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SandboxError {
CompilationFailed(String),
InstantiationFailed(String),
ExecutionFailed(String),
MemoryAccessFailed(String),
MissingMemory,
MissingExport(String),
FuelExhausted,
MemoryLimitExceeded,
ConfigurationFailed(String),
Timeout,
}
impl std::fmt::Display for SandboxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SandboxError::CompilationFailed(msg) => write!(f, "Compilation failed: {}", msg),
SandboxError::InstantiationFailed(msg) => write!(f, "Instantiation failed: {}", msg),
SandboxError::ExecutionFailed(msg) => write!(f, "Execution failed: {}", msg),
SandboxError::MemoryAccessFailed(msg) => write!(f, "Memory access failed: {}", msg),
SandboxError::MissingMemory => write!(f, "Missing required memory export"),
SandboxError::MissingExport(name) => write!(f, "Missing required export: {}", name),
SandboxError::FuelExhausted => write!(f, "Fuel exhausted"),
SandboxError::MemoryLimitExceeded => write!(f, "Memory limit exceeded"),
SandboxError::ConfigurationFailed(msg) => write!(f, "Configuration failed: {}", msg),
SandboxError::Timeout => write!(f, "Execution timeout"),
}
}
}
impl std::error::Error for SandboxError {}
pub type SandboxResult<T> = Result<T, SandboxError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sandbox_creation() {
let sandbox = Sandbox::new(1000, 8, 1000);
assert_eq!(sandbox.max_fuel, 1000);
assert_eq!(sandbox.max_memory_pages, 8);
}
#[test]
fn test_default_limits() {
let sandbox = Sandbox::default_limits();
assert_eq!(sandbox.max_fuel, 1_000_000);
assert_eq!(sandbox.max_memory_pages, 16);
}
}