1use nomiscript::SymbolTable;
2use tracing::debug;
3use wasmtime::{Engine, Linker, Module, Store};
4
5use crate::error::HookError;
6use crate::format::{BASE_OFFSET, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
7use crate::host::{WasmHost, define_host_functions};
8use crate::parser::{OutputParser, ParsedEntity};
9use crate::runtime::{EngineOpts, build_engine};
10
11const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
12const WASM_PAGE_SIZE: u32 = 65536;
13const DEFAULT_EPOCH_DEADLINE_TICKS: u64 = 5;
21const EPOCH_TICK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
22
23struct EpochTicker {
37 stop: Option<std::sync::mpsc::Sender<()>>,
38 handle: Option<std::thread::JoinHandle<()>>,
39}
40
41impl EpochTicker {
42 fn spawn(engine: Engine, ticks: u64) -> Self {
43 let (stop, rx) = std::sync::mpsc::channel::<()>();
44 let handle = std::thread::spawn(move || {
45 for _ in 0..ticks {
46 match rx.recv_timeout(EPOCH_TICK_INTERVAL) {
47 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => engine.increment_epoch(),
48 _ => return,
49 }
50 }
51 });
52 Self {
53 stop: Some(stop),
54 handle: Some(handle),
55 }
56 }
57}
58
59impl Drop for EpochTicker {
60 fn drop(&mut self) {
61 self.stop.take();
62 if let Some(handle) = self.handle.take() {
63 let _ = handle.join();
64 }
65 }
66}
67
68pub struct ScriptExecutor {
69 host: WasmHost,
70 epoch_deadline_ticks: u64,
71}
72
73impl ScriptExecutor {
74 pub fn try_new() -> Result<Self, HookError> {
81 Ok(Self {
82 host: WasmHost::new(build_engine(EngineOpts::baseline())?, SymbolTable::new()),
83 epoch_deadline_ticks: DEFAULT_EPOCH_DEADLINE_TICKS,
84 })
85 }
86
87 #[must_use]
88 pub fn with_engine(engine: Engine) -> Self {
89 Self {
90 host: WasmHost::new(engine, SymbolTable::new()),
91 epoch_deadline_ticks: DEFAULT_EPOCH_DEADLINE_TICKS,
92 }
93 }
94
95 #[must_use]
101 pub fn with_epoch_deadline_ticks(mut self, ticks: u64) -> Self {
102 self.epoch_deadline_ticks = ticks;
103 self
104 }
105
106 pub fn linked_imports(&self) -> Result<Vec<(String, String)>, HookError> {
108 let mut linker = Linker::new(self.host.engine());
109 define_host_functions(&mut linker)?;
110 let mut store = Store::new(self.host.engine(), self.host.execution_state(0, 0, 0));
111 Ok(linker
112 .iter(&mut store)
113 .map(|(module, name, _)| (module.to_string(), name.to_string()))
114 .collect())
115 }
116
117 fn get_or_compile_module(&self, bytecode: &[u8]) -> Result<Module, HookError> {
118 self.host
119 .module_cache()
120 .get_or_compile(self.host.engine(), bytecode)
121 .map_err(HookError::from)
122 }
123
124 pub fn execute(
125 &self,
126 bytecode: &[u8],
127 input: &[u8],
128 output_size: Option<u32>,
129 ) -> Result<Vec<ParsedEntity>, HookError> {
130 debug!(bytecode_size = bytecode.len(), "script execution start");
131 let output_size = output_size.unwrap_or(DEFAULT_OUTPUT_SIZE);
132 let module = self.get_or_compile_module(bytecode)?;
133 debug!("module compiled");
134
135 let header = GlobalHeader::from_bytes(input)
136 .ok_or_else(|| HookError::Parse("Invalid input header".to_string()))?;
137
138 let input_offset = BASE_OFFSET;
139 let output_offset = input_offset + input.len() as u32;
140 let strings_offset = header.strings_pool_offset;
141
142 let exec_state = self
143 .host
144 .execution_state(input_offset, output_offset, strings_offset);
145 let mut store = Store::new(self.host.engine(), exec_state);
146 store.set_epoch_deadline(self.epoch_deadline_ticks);
147
148 let _ticker = EpochTicker::spawn(self.host.engine().clone(), self.epoch_deadline_ticks);
149
150 let mut linker = Linker::new(self.host.engine());
151 define_host_functions(&mut linker)?;
152
153 let instance = linker.instantiate(&mut store, &module)?;
154
155 let memory = instance
156 .get_memory(&mut store, "memory")
157 .ok_or(HookError::WASMMem)?;
158
159 store.data_mut().memory = Some(memory);
160
161 let total_size = input.len() + output_size as usize;
162 let required_pages = (BASE_OFFSET as usize + total_size).div_ceil(WASM_PAGE_SIZE as usize);
163 let current_pages = memory.size(&store) as usize;
164
165 if required_pages > current_pages {
166 memory.grow(&mut store, (required_pages - current_pages) as u64)?;
167 }
168
169 let mem_data = memory.data_mut(&mut store);
170 let input_start = BASE_OFFSET as usize;
171 mem_data[input_start..input_start + input.len()].copy_from_slice(input);
172
173 let output_start = output_offset as usize;
174 let input_entity_count = header.input_entity_count;
175 let output_header = OutputHeader::new(input_entity_count);
176 mem_data[output_start..output_start + OUTPUT_HEADER_SIZE]
177 .copy_from_slice(&output_header.to_bytes());
178
179 let should_apply = instance
180 .get_typed_func::<(), i32>(&mut store, "should_apply")
181 .map_err(|e| HookError::Script(format!("Missing should_apply export: {e}")))?;
182
183 let result = should_apply.call(&mut store, ())?;
184 debug!(should_apply = result, "should_apply result");
185 if result == 0 {
186 return Ok(Vec::new());
187 }
188
189 let process = instance
190 .get_typed_func::<(), ()>(&mut store, "process")
191 .map_err(|e| HookError::Script(format!("Missing process export: {e}")))?;
192
193 debug!("calling process");
194 process.call(&mut store, ())?;
195
196 let mem_data = memory.data(&store);
197 let output_data = &mem_data[output_start..output_start + output_size as usize];
198
199 let output_header = OutputHeader::from_bytes(output_data)
200 .ok_or_else(|| HookError::Parse("Invalid output header".to_string()))?;
201
202 let output_strings_offset = { output_header.strings_offset } as usize;
203
204 let parser = OutputParser::new(output_data, output_strings_offset)?;
205 let entities: Result<Vec<ParsedEntity>, HookError> = parser.entities().collect();
206 debug!(
207 entity_count = entities.as_ref().map_or(0, std::vec::Vec::len),
208 "output parse complete"
209 );
210 entities
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn test_executor_creation() {
220 let executor = ScriptExecutor::try_new().expect("baseline engine");
221 assert!(
222 executor
223 .host
224 .module_cache()
225 .is_empty()
226 .expect("cache lock must not be poisoned in fresh executor")
227 );
228 }
229
230 #[test]
231 fn linked_imports_list_the_bound_host_functions() {
232 let executor = ScriptExecutor::try_new().expect("baseline engine");
233 let imports = executor.linked_imports().expect("imports");
234
235 assert!(imports.contains(&("env".to_string(), "write_bytes".to_string())));
236 assert!(imports.contains(&("nomi".to_string(), "__nomi_raise".to_string())));
237 assert!(!imports.contains(&("nomi".to_string(), "account_get_account".to_string())));
238 }
239}