1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Support for user applications compiled as WebAssembly (Wasm) modules.
//!
//! Requires a WebAssembly runtime to be selected and enabled using one of the following features:
//!
//! - `wasmer` enables the [Wasmer](https://wasmer.io/) runtime
//! - `wasmtime` enables the [Wasmtime](https://wasmtime.dev/) runtime

#![cfg(any(feature = "wasmer", feature = "wasmtime"))]

mod common;
mod module_cache;
mod runtime_actor;
mod sanitizer;
#[macro_use]
mod system_api;
#[cfg(feature = "wasmer")]
#[path = "wasmer.rs"]
mod wasmer;
#[cfg(feature = "wasmtime")]
#[path = "wasmtime.rs"]
mod wasmtime;

use self::{runtime_actor::RuntimeActor, sanitizer::sanitize};
use crate::{
    ApplicationCallResult, Bytecode, CalleeContext, ContractRuntime, ExecutionError,
    MessageContext, OperationContext, QueryContext, RawExecutionResult, ServiceRuntime,
    SessionCallResult, SessionId, UserContract, UserService, WasmRuntime,
};
use async_lock::RwLock;
use async_trait::async_trait;
use futures::future;
use std::{path::Path, sync::Arc};
use thiserror::Error;

/// A user contract in a compiled WebAssembly module.
pub enum WasmContract {
    #[cfg(feature = "wasmer")]
    Wasmer {
        engine: ::wasmer::Engine,
        module: ::wasmer::Module,
    },
    #[cfg(feature = "wasmtime")]
    Wasmtime { module: Arc<::wasmtime::Module> },
}

impl WasmContract {
    /// Creates a new [`WasmContract`] using the WebAssembly module with the provided bytecodes.
    pub async fn new(
        contract_bytecode: Bytecode,
        runtime: WasmRuntime,
    ) -> Result<Self, WasmExecutionError> {
        let contract_bytecode = if runtime.needs_sanitizer() {
            // Ensure bytecode normalization whenever wasmer and wasmtime are possibly
            // compared.
            sanitize(contract_bytecode).map_err(WasmExecutionError::LoadContractModule)?
        } else {
            contract_bytecode
        };
        match runtime {
            #[cfg(feature = "wasmer")]
            WasmRuntime::Wasmer | WasmRuntime::WasmerWithSanitizer => {
                Self::new_with_wasmer(contract_bytecode).await
            }
            #[cfg(feature = "wasmtime")]
            WasmRuntime::Wasmtime | WasmRuntime::WasmtimeWithSanitizer => {
                Self::new_with_wasmtime(contract_bytecode).await
            }
        }
    }

    /// Creates a new [`WasmContract`] using the WebAssembly module in `bytecode_file`.
    pub async fn from_file(
        contract_bytecode_file: impl AsRef<Path>,
        runtime: WasmRuntime,
    ) -> Result<Self, WasmExecutionError> {
        Self::new(
            Bytecode::load_from_file(contract_bytecode_file)
                .await
                .map_err(anyhow::Error::from)
                .map_err(WasmExecutionError::LoadContractModule)?,
            runtime,
        )
        .await
    }
}

/// A user service in a compiled WebAssembly module.
pub enum WasmService {
    #[cfg(feature = "wasmer")]
    Wasmer { module: Arc<::wasmer::Module> },
    #[cfg(feature = "wasmtime")]
    Wasmtime { module: Arc<::wasmtime::Module> },
}

impl WasmService {
    /// Creates a new [`WasmService`] using the WebAssembly module with the provided bytecodes.
    pub async fn new(
        service_bytecode: Bytecode,
        runtime: WasmRuntime,
    ) -> Result<Self, WasmExecutionError> {
        match runtime {
            #[cfg(feature = "wasmer")]
            WasmRuntime::Wasmer | WasmRuntime::WasmerWithSanitizer => {
                Self::new_with_wasmer(service_bytecode).await
            }
            #[cfg(feature = "wasmtime")]
            WasmRuntime::Wasmtime | WasmRuntime::WasmtimeWithSanitizer => {
                Self::new_with_wasmtime(service_bytecode).await
            }
        }
    }

    /// Creates a new [`WasmService`] using the WebAssembly module in `bytecode_file`.
    pub async fn from_file(
        service_bytecode_file: impl AsRef<Path>,
        runtime: WasmRuntime,
    ) -> Result<Self, WasmExecutionError> {
        Self::new(
            Bytecode::load_from_file(service_bytecode_file)
                .await
                .map_err(anyhow::Error::from)
                .map_err(WasmExecutionError::LoadServiceModule)?,
            runtime,
        )
        .await
    }
}

/// Errors that can occur when executing a user application in a WebAssembly module.
#[cfg(any(feature = "wasmer", feature = "wasmtime"))]
#[derive(Debug, Error)]
pub enum WasmExecutionError {
    #[error("Failed to load contract Wasm module: {_0}")]
    LoadContractModule(#[source] anyhow::Error),
    #[error("Failed to load service Wasm module: {_0}")]
    LoadServiceModule(#[source] anyhow::Error),
    #[cfg(feature = "wasmtime")]
    #[error("Failed to create and configure Wasmtime runtime")]
    CreateWasmtimeEngine(#[source] anyhow::Error),
    #[cfg(feature = "wasmer")]
    #[error("Failed to execute Wasm module (Wasmer)")]
    ExecuteModuleInWasmer(#[from] ::wasmer::RuntimeError),
    #[cfg(feature = "wasmtime")]
    #[error("Failed to execute Wasm module (Wasmtime)")]
    ExecuteModuleInWasmtime(#[from] ::wasmtime::Trap),
    #[error("Attempt to use a system API to write to read-only storage")]
    WriteAttemptToReadOnlyStorage,
    #[error("Runtime failed to respond to application")]
    MissingRuntimeResponse,
    #[error("Host future was polled after it had finished")]
    PolledTwice,
    #[error("Execution of guest future was aborted")]
    Aborted,
}

#[async_trait]
impl UserContract for WasmContract {
    async fn initialize(
        &self,
        context: &OperationContext,
        runtime: &dyn ContractRuntime,
        argument: &[u8],
    ) -> Result<RawExecutionResult<Vec<u8>>, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(RwLock::new(runtime));

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_contract_runtime_with_wasmtime(module, runtime_requests)?
                    .initialize(context, argument)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { engine, module } => {
                Self::prepare_contract_runtime_with_wasmer(engine, module, runtime_requests)?
                    .initialize(context, argument)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;
        wasm_result
    }

    async fn execute_operation(
        &self,
        context: &OperationContext,
        runtime: &dyn ContractRuntime,
        operation: &[u8],
    ) -> Result<RawExecutionResult<Vec<u8>>, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(RwLock::new(runtime));

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_contract_runtime_with_wasmtime(module, runtime_requests)?
                    .execute_operation(context, operation)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { engine, module } => {
                Self::prepare_contract_runtime_with_wasmer(engine, module, runtime_requests)?
                    .execute_operation(context, operation)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;
        wasm_result
    }

    async fn execute_message(
        &self,
        context: &MessageContext,
        runtime: &dyn ContractRuntime,
        message: &[u8],
    ) -> Result<RawExecutionResult<Vec<u8>>, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(RwLock::new(runtime));

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_contract_runtime_with_wasmtime(module, runtime_requests)?
                    .execute_message(context, message)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { engine, module } => {
                Self::prepare_contract_runtime_with_wasmer(engine, module, runtime_requests)?
                    .execute_message(context, message)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;
        wasm_result
    }

    async fn handle_application_call(
        &self,
        context: &CalleeContext,
        runtime: &dyn ContractRuntime,
        argument: &[u8],
        forwarded_sessions: Vec<SessionId>,
    ) -> Result<ApplicationCallResult, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(RwLock::new(runtime));

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_contract_runtime_with_wasmtime(module, runtime_requests)?
                    .handle_application_call(context, argument, forwarded_sessions)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { engine, module } => {
                Self::prepare_contract_runtime_with_wasmer(engine, module, runtime_requests)?
                    .handle_application_call(context, argument, forwarded_sessions)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;
        wasm_result
    }

    async fn handle_session_call(
        &self,
        context: &CalleeContext,
        runtime: &dyn ContractRuntime,
        session_state: &mut Vec<u8>,
        argument: &[u8],
        forwarded_sessions: Vec<SessionId>,
    ) -> Result<SessionCallResult, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(RwLock::new(runtime));

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_contract_runtime_with_wasmtime(module, runtime_requests)?
                    .handle_session_call(context, &*session_state, argument, forwarded_sessions)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { engine, module } => {
                Self::prepare_contract_runtime_with_wasmer(engine, module, runtime_requests)?
                    .handle_session_call(context, &*session_state, argument, forwarded_sessions)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;

        let (result, updated_session_state) = wasm_result?;
        *session_state = updated_session_state;
        Ok(result)
    }
}

#[async_trait]
impl UserService for WasmService {
    async fn handle_query(
        &self,
        context: &QueryContext,
        runtime: &dyn ServiceRuntime,
        argument: &[u8],
    ) -> Result<Vec<u8>, ExecutionError> {
        let (runtime_actor, runtime_requests) = RuntimeActor::new(runtime);

        let wasm_result_receiver = match self {
            #[cfg(feature = "wasmtime")]
            Self::Wasmtime { module } => {
                Self::prepare_service_runtime_with_wasmtime(module, runtime_requests)?
                    .handle_query(context, argument)
            }
            #[cfg(feature = "wasmer")]
            Self::Wasmer { module } => {
                Self::prepare_service_runtime_with_wasmer(module, runtime_requests)?
                    .handle_query(context, argument)
            }
        };

        let (runtime_result, wasm_result) =
            future::join(runtime_actor.run(), wasm_result_receiver).await;

        runtime_result?;
        wasm_result
    }
}

/// This assumes that the current directory is one of the crates.
#[cfg(any(test, feature = "test"))]
pub mod test {
    use crate::{WasmContract, WasmRuntime, WasmService};
    use once_cell::sync::OnceCell;

    fn build_applications() -> Result<(), std::io::Error> {
        tracing::info!("Building example applications with cargo");
        let output = std::process::Command::new("cargo")
            .current_dir("../examples")
            .args(["build", "--release", "--target", "wasm32-unknown-unknown"])
            .output()?;
        if !output.status.success() {
            panic!(
                "Failed to build example applications.\n\n\
                stdout:\n-------\n{}\n\n\
                stderr:\n-------\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
        }
        Ok(())
    }

    pub fn get_example_bytecode_paths(name: &str) -> Result<(String, String), std::io::Error> {
        let name = name.replace('-', "_");
        static INSTANCE: OnceCell<()> = OnceCell::new();
        INSTANCE.get_or_try_init(build_applications)?;
        Ok((
            format!("../examples/target/wasm32-unknown-unknown/release/{name}_contract.wasm"),
            format!("../examples/target/wasm32-unknown-unknown/release/{name}_service.wasm"),
        ))
    }

    pub async fn build_example_application(
        name: &str,
        wasm_runtime: impl Into<Option<WasmRuntime>>,
    ) -> Result<(WasmContract, WasmService), anyhow::Error> {
        let (contract_path, service_path) = get_example_bytecode_paths(name)?;
        let wasm_runtime = wasm_runtime.into().unwrap_or_default();
        let contract = WasmContract::from_file(&contract_path, wasm_runtime).await?;
        let service = WasmService::from_file(&service_path, wasm_runtime).await?;
        Ok((contract, service))
    }
}