1
use nomiscript::SymbolTable;
2
use tracing::debug;
3
use wasmtime::{Engine, Linker, Module, Store};
4

            
5
use crate::error::HookError;
6
use crate::format::{BASE_OFFSET, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
7
use crate::host::{WasmHost, define_host_functions};
8
use crate::parser::{OutputParser, ParsedEntity};
9
use crate::runtime::{EngineOpts, build_engine};
10

            
11
const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
12
const WASM_PAGE_SIZE: u32 = 65536;
13
/// Wall-clock budget for one script execution, in [`EPOCH_TICK_INTERVAL`] ticks.
14
///
15
/// This is a real-time bound, not a fuel bound, so it is sensitive to how fast
16
/// the host happens to be. Coverage-instrumented builds run several times
17
/// slower, which is why [`ScriptExecutor::with_epoch_deadline_ticks`] exists:
18
/// tests that only care that a script *completes* raise the budget rather than
19
/// racing the clock.
20
const DEFAULT_EPOCH_DEADLINE_TICKS: u64 = 5;
21
const EPOCH_TICK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
22

            
23
/// Drives the engine's epoch clock for the lifetime of one execution.
24
///
25
/// Stopping matters: the epoch counter is shared by every execution on the same
26
/// engine, so a ticker that outlives its call keeps consuming the budget of
27
/// whatever runs next. A `JoinHandle` does not stop a thread when dropped, it
28
/// detaches it — so the previous `drop(ticker)` left it ticking for up to
29
/// `EPOCH_DEADLINE_TICKS` seconds, and every `?` between the spawn and the call
30
/// skipped even that. Executors are reused (the account-script batch path runs
31
/// one across many transactions), which is exactly where a stray bump lands.
32
///
33
/// The stop channel doubles as the sleep: `recv_timeout` returns `Timeout` for a
34
/// real tick and `Disconnected` the moment the guard drops, so teardown is
35
/// prompt rather than waiting out the current second.
36
struct EpochTicker {
37
    stop: Option<std::sync::mpsc::Sender<()>>,
38
    handle: Option<std::thread::JoinHandle<()>>,
39
}
40

            
41
impl EpochTicker {
42
21090
    fn spawn(engine: Engine, ticks: u64) -> Self {
43
21090
        let (stop, rx) = std::sync::mpsc::channel::<()>();
44
21090
        let handle = std::thread::spawn(move || {
45
21090
            for _ in 0..ticks {
46
21850
                match rx.recv_timeout(EPOCH_TICK_INTERVAL) {
47
950
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => engine.increment_epoch(),
48
20900
                    _ => return,
49
                }
50
            }
51
21090
        });
52
21090
        Self {
53
21090
            stop: Some(stop),
54
21090
            handle: Some(handle),
55
21090
        }
56
21090
    }
57
}
58

            
59
impl Drop for EpochTicker {
60
21090
    fn drop(&mut self) {
61
21090
        self.stop.take();
62
21090
        if let Some(handle) = self.handle.take() {
63
21090
            let _ = handle.join();
64
        }
65
21090
    }
66
}
67

            
68
pub struct ScriptExecutor {
69
    host: WasmHost,
70
    epoch_deadline_ticks: u64,
71
}
72

            
73
impl ScriptExecutor {
74
    /// Builds an executor on the baseline engine.
75
    ///
76
    /// Fallible because engine construction is: `wasmtime` validates the
77
    /// configuration and rejects unsupported combinations. There is no
78
    /// infallible `new`/`Default` for the same reason — a constructor that
79
    /// cannot report that failure can only paper over it.
80
13492
    pub fn try_new() -> Result<Self, HookError> {
81
        Ok(Self {
82
13492
            host: WasmHost::new(build_engine(EngineOpts::baseline())?, SymbolTable::new()),
83
13492
            epoch_deadline_ticks: DEFAULT_EPOCH_DEADLINE_TICKS,
84
        })
85
13492
    }
86

            
87
    #[must_use]
88
4940
    pub fn with_engine(engine: Engine) -> Self {
89
4940
        Self {
90
4940
            host: WasmHost::new(engine, SymbolTable::new()),
91
4940
            epoch_deadline_ticks: DEFAULT_EPOCH_DEADLINE_TICKS,
92
4940
        }
93
4940
    }
94

            
95
    /// Overrides the per-execution wall-clock budget.
96
    ///
97
    /// Production uses `DEFAULT_EPOCH_DEADLINE_TICKS`; a caller that runs
98
    /// under coverage instrumentation, a debugger, or a loaded CI node raises
99
    /// it so a slow-but-correct script is not cut off mid-execution.
100
    #[must_use]
101
190
    pub fn with_epoch_deadline_ticks(mut self, ticks: u64) -> Self {
102
190
        self.epoch_deadline_ticks = ticks;
103
190
        self
104
190
    }
105

            
106
    /// The `(module, name)` of every host function a script can import.
107
571
    pub fn linked_imports(&self) -> Result<Vec<(String, String)>, HookError> {
108
571
        let mut linker = Linker::new(self.host.engine());
109
571
        define_host_functions(&mut linker)?;
110
571
        let mut store = Store::new(self.host.engine(), self.host.execution_state(0, 0, 0));
111
571
        Ok(linker
112
571
            .iter(&mut store)
113
6852
            .map(|(module, name, _)| (module.to_string(), name.to_string()))
114
            .collect())
115
571
    }
116

            
117
21470
    fn get_or_compile_module(&self, bytecode: &[u8]) -> Result<Module, HookError> {
118
21470
        self.host
119
21470
            .module_cache()
120
21470
            .get_or_compile(self.host.engine(), bytecode)
121
21470
            .map_err(HookError::from)
122
21470
    }
123

            
124
21470
    pub fn execute(
125
21470
        &self,
126
21470
        bytecode: &[u8],
127
21470
        input: &[u8],
128
21470
        output_size: Option<u32>,
129
21470
    ) -> Result<Vec<ParsedEntity>, HookError> {
130
21470
        debug!(bytecode_size = bytecode.len(), "script execution start");
131
21470
        let output_size = output_size.unwrap_or(DEFAULT_OUTPUT_SIZE);
132
21470
        let module = self.get_or_compile_module(bytecode)?;
133
21090
        debug!("module compiled");
134

            
135
21090
        let header = GlobalHeader::from_bytes(input)
136
            .ok_or_else(|| HookError::Parse("Invalid input header".to_string()))?;
137

            
138
21090
        let input_offset = BASE_OFFSET;
139
21090
        let output_offset = input_offset + input.len() as u32;
140
21090
        let strings_offset = header.strings_pool_offset;
141

            
142
21090
        let exec_state = self
143
21090
            .host
144
21090
            .execution_state(input_offset, output_offset, strings_offset);
145
21090
        let mut store = Store::new(self.host.engine(), exec_state);
146
21090
        store.set_epoch_deadline(self.epoch_deadline_ticks);
147

            
148
21090
        let _ticker = EpochTicker::spawn(self.host.engine().clone(), self.epoch_deadline_ticks);
149

            
150
21090
        let mut linker = Linker::new(self.host.engine());
151
21090
        define_host_functions(&mut linker)?;
152

            
153
21090
        let instance = linker.instantiate(&mut store, &module)?;
154

            
155
21090
        let memory = instance
156
21090
            .get_memory(&mut store, "memory")
157
21090
            .ok_or(HookError::WASMMem)?;
158

            
159
21090
        store.data_mut().memory = Some(memory);
160

            
161
21090
        let total_size = input.len() + output_size as usize;
162
21090
        let required_pages = (BASE_OFFSET as usize + total_size).div_ceil(WASM_PAGE_SIZE as usize);
163
21090
        let current_pages = memory.size(&store) as usize;
164

            
165
21090
        if required_pages > current_pages {
166
8740
            memory.grow(&mut store, (required_pages - current_pages) as u64)?;
167
12350
        }
168

            
169
21090
        let mem_data = memory.data_mut(&mut store);
170
21090
        let input_start = BASE_OFFSET as usize;
171
21090
        mem_data[input_start..input_start + input.len()].copy_from_slice(input);
172

            
173
21090
        let output_start = output_offset as usize;
174
21090
        let input_entity_count = header.input_entity_count;
175
21090
        let output_header = OutputHeader::new(input_entity_count);
176
21090
        mem_data[output_start..output_start + OUTPUT_HEADER_SIZE]
177
21090
            .copy_from_slice(&output_header.to_bytes());
178

            
179
21090
        let should_apply = instance
180
21090
            .get_typed_func::<(), i32>(&mut store, "should_apply")
181
            .map_err(|e| HookError::Script(format!("Missing should_apply export: {e}")))?;
182

            
183
21090
        let result = should_apply.call(&mut store, ())?;
184
21090
        debug!(should_apply = result, "should_apply result");
185
21090
        if result == 0 {
186
3230
            return Ok(Vec::new());
187
17860
        }
188

            
189
17860
        let process = instance
190
17860
            .get_typed_func::<(), ()>(&mut store, "process")
191
            .map_err(|e| HookError::Script(format!("Missing process export: {e}")))?;
192

            
193
17860
        debug!("calling process");
194
17860
        process.call(&mut store, ())?;
195

            
196
14820
        let mem_data = memory.data(&store);
197
14820
        let output_data = &mem_data[output_start..output_start + output_size as usize];
198

            
199
14820
        let output_header = OutputHeader::from_bytes(output_data)
200
            .ok_or_else(|| HookError::Parse("Invalid output header".to_string()))?;
201

            
202
14820
        let output_strings_offset = { output_header.strings_offset } as usize;
203

            
204
14820
        let parser = OutputParser::new(output_data, output_strings_offset)?;
205
14820
        let entities: Result<Vec<ParsedEntity>, HookError> = parser.entities().collect();
206
14820
        debug!(
207
            entity_count = entities.as_ref().map_or(0, std::vec::Vec::len),
208
            "output parse complete"
209
        );
210
14820
        entities
211
21470
    }
212
}
213

            
214
#[cfg(test)]
215
mod tests {
216
    use super::*;
217

            
218
    #[test]
219
1
    fn test_executor_creation() {
220
1
        let executor = ScriptExecutor::try_new().expect("baseline engine");
221
1
        assert!(
222
1
            executor
223
1
                .host
224
1
                .module_cache()
225
1
                .is_empty()
226
1
                .expect("cache lock must not be poisoned in fresh executor")
227
        );
228
1
    }
229

            
230
    #[test]
231
1
    fn linked_imports_list_the_bound_host_functions() {
232
1
        let executor = ScriptExecutor::try_new().expect("baseline engine");
233
1
        let imports = executor.linked_imports().expect("imports");
234

            
235
1
        assert!(imports.contains(&("env".to_string(), "write_bytes".to_string())));
236
1
        assert!(imports.contains(&("nomi".to_string(), "__nomi_raise".to_string())));
237
1
        assert!(!imports.contains(&("nomi".to_string(), "account_get_account".to_string())));
238
1
    }
239
}