diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 7db3b75..869439c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -20,6 +20,14 @@ jobs: uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy + targets: wasm32-wasip2 + + - name: Pin pkcs1 to 0.8.0-rc.4 + # sad-rsa 0.2.3 (pulled in through multi-key) fails to compile against + # pkcs1 0.8.0-rc.5, which added a type parameter to RsaPublicKey. + # Pin the last working pkcs1 pre-release until sad-rsa ships a release + # compatible with it, then remove this step. + run: cargo update -p pkcs1 --precise 0.8.0-rc.4 - name: Check Code Format run: cargo fmt --all -- --check @@ -30,6 +38,9 @@ jobs: - name: Build run: cargo build --verbose + - name: Build Script Fixtures + run: make -C examples/wacc/wast guests + - name: Run tests run: cargo test --verbose @@ -46,5 +57,11 @@ jobs: - name: Install Rust Toolchain (1.96) uses: dtolnay/rust-toolchain@1.96.0 + - name: Pin pkcs1 to 0.8.0-rc.4 + # Same mitigation as in the build job: sad-rsa 0.2.3 fails to compile + # against pkcs1 0.8.0-rc.5. Remove this step when sad-rsa ships a + # compatible release. + run: cargo update -p pkcs1 --precise 0.8.0-rc.4 + - name: Check run: cargo check diff --git a/CHANGELOG.md b/CHANGELOG.md index abf08e1..e61bf5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.2.0] - 2026-10-06 + +### Added + +- WASM Component Model support for scripts. An added `wit/wacc.wit` declares the WIT package `cryptid:wacc@1.0.0` with the typed `host` interface and the two script worlds `unlock-script` (export `for-great-justice`) and `lock-script` (export `move-every-zig`); the eight typed host functions carry the same semantics as the eight raw-ABI core-module imports, and the component path also accepts the legacy snake-case export names through the added export-name map. +- `ScriptKind` with the variants `Module` and `Component`, and `ScriptKind::detect(bytes)`: binary detection by the version byte after the `\0asm` magic and text detection by the leading WAT token. Re-exported from the crate root. +- A blake3-keyed component cache in the public `ModuleCache` (`insert_component_bytes` / `get_component_bytes`, a second bounded map) and the `Runtime::cached_component_count()` accessor; component compilation runs through the internal `Runtime::compile_component`, mirroring the internal `Runtime::compile` on the module path. +- `Builder::with_component_bytes` and `Builder::try_build_component`, producing a `vm::ComponentInstance` with a public `store`, `run`, and `log`, mirroring the module path's fuel and store-limit flow. Typed host imports are generated with `wasmtime::component::bindgen!` and registered once on the runtime's component linker for both worlds, so script components import only `cryptid:wacc/host@1.0.0`. + +### Changed + +- The `wasmtime` dependency gains the `component-model` feature; the dependency stays at version `48.0`. +- `Builder::try_build` now rejects detectable component bytes with `VmError::ScriptKindMismatch` instead of a generic compilation error, and `Builder::try_build_component` rejects detectable module bytes symmetrically. + +### Notes + +- 2.1.2 shipped without a changelog entry. + ## [2.1.1] - 2026-09-02 ### Changed @@ -78,6 +96,7 @@ different from 1.0.5. - Previous standalone release. Used `wasmtime 19.0`, `thiserror 1.0`, and FSL-1.1 license. Git deps for `multicid`, `multihash`, `multikey`, `multisig`, `multitrait`, `multiutil`. +[2.2.0]: https://github.com/cryptidtech/wacc/compare/v2.1.2...v2.2.0 [2.1.1]: https://github.com/cryptidtech/wacc/compare/v2.1.0...v2.1.1 [2.1.0]: https://github.com/cryptidtech/wacc/compare/v2.0.0...v2.1.0 [2.0.0]: https://github.com/cryptidtech/wacc/releases/tag/v2.0.0 diff --git a/Cargo.toml b/Cargo.toml index b301f48..b55c3c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "wacc" -version = "2.1.2" +version = "2.2.0" edition = "2021" rust-version = "1.96" authors = ["Dave Grantham "] @@ -12,18 +12,19 @@ keywords = ["wasm", "cryptographic", "vm", "provenance", "scripting"] categories = ["cryptography", "wasm"] [dependencies] -blake3 = { version = "1.8.1", features = ["traits-preview"] } +blake3 = { version = "1.8", features = ["traits-preview"] } log = "0.4" multi-cid = "0.2" -multi-codec = "1.3" +multi-codec = "1.5" multi-hash = "1.1" -multi-key = "1.2" -multi-sig = "1.3" +multi-key = "2.0" +multi-sig = "1.4" multi-trait = "1.0" multi-util = "1.1" thiserror = "2.0" tracing = "0.1" -wasmtime = { version = "48.0", default-features = false, features = [ +wasmtime = { version = "49.0", default-features = false, features = [ + "component-model", "cranelift", "parallel-compilation", "runtime", @@ -35,6 +36,7 @@ wasmtime = { version = "48.0", default-features = false, features = [ hex = "0.4" proptest = "1.11" test-log = { version = "0.2", features = ["trace", "color"] } +wasmparser = "0.261" [[test]] name = "log" @@ -80,6 +82,10 @@ path = "tests/edge_cases.rs" name = "property_tests" path = "tests/property_tests.rs" +[[test]] +name = "component" +path = "tests/component.rs" + [lints.clippy] pedantic = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 } diff --git a/examples/wacc/abi/.cargo/config.toml b/examples/wacc/abi/.cargo/config.toml new file mode 100644 index 0000000..dac2459 --- /dev/null +++ b/examples/wacc/abi/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +target = "wasm32-wasip2" \ No newline at end of file diff --git a/examples/wacc/abi/Cargo.toml b/examples/wacc/abi/Cargo.toml new file mode 100644 index 0000000..84c757d --- /dev/null +++ b/examples/wacc/abi/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "abi" +version = "0.7.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = { version = "0.46", default-features = false, features = ["macros", "realloc"] } +dlmalloc = { version = "0.2", features = ["global"] } \ No newline at end of file diff --git a/examples/wacc/abi/src/lib.rs b/examples/wacc/abi/src/lib.rs new file mode 100644 index 0000000..14b9e6f --- /dev/null +++ b/examples/wacc/abi/src/lib.rs @@ -0,0 +1,79 @@ +#![no_std] + +use dlmalloc::GlobalDlmalloc; + +#[global_allocator] +static ALLOCATOR: GlobalDlmalloc = GlobalDlmalloc; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + core::arch::wasm32::unreachable() +} + +// The component canonical ABI allocates host-to-guest return buffers through a +// `cabi_realloc` core export. wit-bindgen's runtime omits this export for +// wasm32-wasip2 targets, so the guest supplies it over its global allocator. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn cabi_realloc( + old_ptr: *mut u8, + old_len: usize, + align: usize, + new_len: usize, +) -> *mut u8 { + use core::alloc::{GlobalAlloc, Layout}; + + let ptr = if old_len == 0 { + if new_len == 0 { + return align as *mut u8; + } + ALLOCATOR.alloc(Layout::from_size_align_unchecked(new_len, align)) + } else { + debug_assert_ne!(new_len, 0, "non-zero old_len requires non-zero new_len!"); + ALLOCATOR.realloc( + old_ptr, + Layout::from_size_align_unchecked(old_len, align), + new_len, + ) + }; + if ptr.is_null() { + core::arch::wasm32::unreachable(); + } + ptr +} + +wit_bindgen::generate!({ + world: "unlock-script", + path: "../../../wit/wacc.wit", +}); + +struct Component; + +impl Guest for Component { + fn for_great_justice() -> i32 { + use crate::cryptid::wacc::host::{ + branch, check_eq, check_preimage, check_preimage_value, check_signature, log, push, + push_value, + }; + + let push_ok = push("/abi/"); + let push_value_ok = push_value(&[0xAB, 0xCD]); + let branch_result = branch("/abi/proof"); + let log_branch_ok = log(&branch_result); + + // Each check is expected to fail without matching state; the calls + // exercise the host-side lowering of every import signature. + let _ = check_eq("/abi/nonexistent"); + let _ = check_preimage("/abi/nonexistent"); + let _ = check_preimage_value(&[0x00, 0x12, 0x34], "/abi/nonexistent"); + let _ = check_signature("/abi/nonexistent", "/abi/nonexistent-msg"); + + let log_ok = log("/abi/log-line"); + if push_ok && push_value_ok && log_branch_ok && log_ok && !branch_result.is_empty() { + 1 + } else { + 0 + } + } +} + +export!(Component); diff --git a/examples/wacc/log/.cargo/config.toml b/examples/wacc/log/.cargo/config.toml index f4e8c00..dac2459 100644 --- a/examples/wacc/log/.cargo/config.toml +++ b/examples/wacc/log/.cargo/config.toml @@ -1,2 +1,2 @@ [build] -target = "wasm32-unknown-unknown" +target = "wasm32-wasip2" \ No newline at end of file diff --git a/examples/wacc/log/Cargo.toml b/examples/wacc/log/Cargo.toml index af42419..441a04c 100644 --- a/examples/wacc/log/Cargo.toml +++ b/examples/wacc/log/Cargo.toml @@ -5,3 +5,7 @@ edition = "2021" [lib] crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = { version = "0.46", default-features = false, features = ["macros", "realloc"] } +dlmalloc = { version = "0.2", features = ["global"] } \ No newline at end of file diff --git a/examples/wacc/log/src/lib.rs b/examples/wacc/log/src/lib.rs index a8892a9..c227e8c 100644 --- a/examples/wacc/log/src/lib.rs +++ b/examples/wacc/log/src/lib.rs @@ -1,13 +1,63 @@ -#[link(wasm_import_module = "wacc")] -extern "C" { - fn _log(ptr: *const u8, len: usize) -> bool; +#![no_std] + +use dlmalloc::GlobalDlmalloc; + +#[global_allocator] +static ALLOCATOR: GlobalDlmalloc = GlobalDlmalloc; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + core::arch::wasm32::unreachable() } -fn log(s: &str) -> bool { - unsafe { _log(s.as_ptr(), s.len()) } +// The component canonical ABI allocates host-to-guest return buffers through a +// `cabi_realloc` core export. wit-bindgen's runtime omits this export for +// wasm32-wasip2 targets, so the guest supplies it over its global allocator. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn cabi_realloc( + old_ptr: *mut u8, + old_len: usize, + align: usize, + new_len: usize, +) -> *mut u8 { + use core::alloc::{GlobalAlloc, Layout}; + + let ptr = if old_len == 0 { + if new_len == 0 { + return align as *mut u8; + } + ALLOCATOR.alloc(Layout::from_size_align_unchecked(new_len, align)) + } else { + debug_assert_ne!(new_len, 0, "non-zero old_len requires non-zero new_len!"); + ALLOCATOR.realloc( + old_ptr, + Layout::from_size_align_unchecked(old_len, align), + new_len, + ) + }; + if ptr.is_null() { + core::arch::wasm32::unreachable(); + } + ptr } -#[no_mangle] -pub fn move_every_zig() -> bool { - log("Hello World!") +wit_bindgen::generate!({ + world: "lock-script", + path: "../../../wit/wacc.wit", +}); + +struct Component; + +impl Guest for Component { + fn move_every_zig() -> i32 { + use crate::cryptid::wacc::host::log; + + if log("Hello World!") { + 1 + } else { + 0 + } + } } + +export!(Component); diff --git a/examples/wacc/signature_first/.cargo/config.toml b/examples/wacc/signature_first/.cargo/config.toml index f4e8c00..dac2459 100644 --- a/examples/wacc/signature_first/.cargo/config.toml +++ b/examples/wacc/signature_first/.cargo/config.toml @@ -1,2 +1,2 @@ [build] -target = "wasm32-unknown-unknown" +target = "wasm32-wasip2" \ No newline at end of file diff --git a/examples/wacc/signature_first/Cargo.toml b/examples/wacc/signature_first/Cargo.toml index a21ff6a..f0aeeca 100644 --- a/examples/wacc/signature_first/Cargo.toml +++ b/examples/wacc/signature_first/Cargo.toml @@ -1,7 +1,11 @@ [package] -name = "signature-first" +name = "signature_first" version = "0.7.0" edition = "2021" [lib] crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = { version = "0.46", default-features = false, features = ["macros", "realloc"] } +dlmalloc = { version = "0.2", features = ["global"] } \ No newline at end of file diff --git a/examples/wacc/signature_first/src/lib.rs b/examples/wacc/signature_first/src/lib.rs index c47eece..6ce166c 100644 --- a/examples/wacc/signature_first/src/lib.rs +++ b/examples/wacc/signature_first/src/lib.rs @@ -1,18 +1,63 @@ -#[link(wasm_import_module = "wacc")] -extern "C" { - fn _check_version(expected: i64) -> i32; - fn _check_signature(ptr: *const u8, len: usize) -> i32; -} +#![no_std] + +use dlmalloc::GlobalDlmalloc; -fn check_version(expected: usize) -> bool { - unsafe { _check_version(expected as i64) != 0 } +#[global_allocator] +static ALLOCATOR: GlobalDlmalloc = GlobalDlmalloc; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + core::arch::wasm32::unreachable() } -fn check_signature(key: &str) -> bool { - unsafe { _check_signature(key.as_ptr(), key.len()) != 0 } +// The component canonical ABI allocates host-to-guest return buffers through a +// `cabi_realloc` core export. wit-bindgen's runtime omits this export for +// wasm32-wasip2 targets, so the guest supplies it over its global allocator. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn cabi_realloc( + old_ptr: *mut u8, + old_len: usize, + align: usize, + new_len: usize, +) -> *mut u8 { + use core::alloc::{GlobalAlloc, Layout}; + + let ptr = if old_len == 0 { + if new_len == 0 { + return align as *mut u8; + } + ALLOCATOR.alloc(Layout::from_size_align_unchecked(new_len, align)) + } else { + debug_assert_ne!(new_len, 0, "non-zero old_len requires non-zero new_len!"); + ALLOCATOR.realloc( + old_ptr, + Layout::from_size_align_unchecked(old_len, align), + new_len, + ) + }; + if ptr.is_null() { + core::arch::wasm32::unreachable(); + } + ptr } -#[no_mangle] -pub fn move_zig() -> bool { - check_version(0) && check_signature("ephemeral") +wit_bindgen::generate!({ + world: "lock-script", + path: "../../../wit/wacc.wit", +}); + +struct Component; + +impl Guest for Component { + fn move_every_zig() -> i32 { + use crate::cryptid::wacc::host::check_signature; + + if check_signature("ephemeral", "/entry/") { + 1 + } else { + 0 + } + } } + +export!(Component); diff --git a/examples/wacc/signature_lock/.cargo/config.toml b/examples/wacc/signature_lock/.cargo/config.toml index f4e8c00..dac2459 100644 --- a/examples/wacc/signature_lock/.cargo/config.toml +++ b/examples/wacc/signature_lock/.cargo/config.toml @@ -1,2 +1,2 @@ [build] -target = "wasm32-unknown-unknown" +target = "wasm32-wasip2" \ No newline at end of file diff --git a/examples/wacc/signature_lock/Cargo.toml b/examples/wacc/signature_lock/Cargo.toml index 0db37c2..101cccf 100644 --- a/examples/wacc/signature_lock/Cargo.toml +++ b/examples/wacc/signature_lock/Cargo.toml @@ -1,7 +1,11 @@ [package] -name = "signature-lock" +name = "signature_lock" version = "0.7.0" edition = "2021" [lib] crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = { version = "0.46", default-features = false, features = ["macros", "realloc"] } +dlmalloc = { version = "0.2", features = ["global"] } \ No newline at end of file diff --git a/examples/wacc/signature_lock/src/lib.rs b/examples/wacc/signature_lock/src/lib.rs index 05fe89c..cad8fd4 100644 --- a/examples/wacc/signature_lock/src/lib.rs +++ b/examples/wacc/signature_lock/src/lib.rs @@ -1,18 +1,66 @@ -#[link(wasm_import_module = "wacc")] -extern "C" { - fn _check_signature(ptr: *const u8, len: usize) -> i32; - fn _check_preimage(ptr: *const u8, len: usize) -> i32; -} +#![no_std] + +use dlmalloc::GlobalDlmalloc; -fn check_signature(key: &str) -> bool { - unsafe { _check_signature(key.as_ptr(), key.len()) != 0 } +#[global_allocator] +static ALLOCATOR: GlobalDlmalloc = GlobalDlmalloc; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + core::arch::wasm32::unreachable() } -fn check_preimage(key: &str) -> bool { - unsafe { _check_preimage(key.as_ptr(), key.len()) != 0 } +// The component canonical ABI allocates host-to-guest return buffers through a +// `cabi_realloc` core export. wit-bindgen's runtime omits this export for +// wasm32-wasip2 targets, so the guest supplies it over its global allocator. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn cabi_realloc( + old_ptr: *mut u8, + old_len: usize, + align: usize, + new_len: usize, +) -> *mut u8 { + use core::alloc::{GlobalAlloc, Layout}; + + let ptr = if old_len == 0 { + if new_len == 0 { + return align as *mut u8; + } + ALLOCATOR.alloc(Layout::from_size_align_unchecked(new_len, align)) + } else { + debug_assert_ne!(new_len, 0, "non-zero old_len requires non-zero new_len!"); + ALLOCATOR.realloc( + old_ptr, + Layout::from_size_align_unchecked(old_len, align), + new_len, + ) + }; + if ptr.is_null() { + core::arch::wasm32::unreachable(); + } + ptr } -#[no_mangle] -pub fn move_zig() -> bool { - check_signature("/tpubkey") || check_signature("/keys/primary") || check_preimage("/hash") +wit_bindgen::generate!({ + world: "lock-script", + path: "../../../wit/wacc.wit", +}); + +struct Component; + +impl Guest for Component { + fn move_every_zig() -> i32 { + use crate::cryptid::wacc::host::{check_preimage, check_signature}; + + if check_signature("/tpubkey", "/entry/") + || check_signature("/keys/primary", "/entry/") + || check_preimage("/hash") + { + 1 + } else { + 0 + } + } } + +export!(Component); diff --git a/examples/wacc/unlock/.cargo/config.toml b/examples/wacc/unlock/.cargo/config.toml index f4e8c00..dac2459 100644 --- a/examples/wacc/unlock/.cargo/config.toml +++ b/examples/wacc/unlock/.cargo/config.toml @@ -1,2 +1,2 @@ [build] -target = "wasm32-unknown-unknown" +target = "wasm32-wasip2" \ No newline at end of file diff --git a/examples/wacc/unlock/Cargo.toml b/examples/wacc/unlock/Cargo.toml index 42c7291..56b167f 100644 --- a/examples/wacc/unlock/Cargo.toml +++ b/examples/wacc/unlock/Cargo.toml @@ -5,3 +5,7 @@ edition = "2021" [lib] crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = { version = "0.46", default-features = false, features = ["macros", "realloc"] } +dlmalloc = { version = "0.2", features = ["global"] } \ No newline at end of file diff --git a/examples/wacc/unlock/src/lib.rs b/examples/wacc/unlock/src/lib.rs index ea08a33..e25a0a9 100644 --- a/examples/wacc/unlock/src/lib.rs +++ b/examples/wacc/unlock/src/lib.rs @@ -1,18 +1,65 @@ -#[link(wasm_import_module = "wacc")] -extern "C" { - fn _push(ptr: *const u8, len: usize) -> bool; +#![no_std] + +use dlmalloc::GlobalDlmalloc; + +#[global_allocator] +static ALLOCATOR: GlobalDlmalloc = GlobalDlmalloc; + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + core::arch::wasm32::unreachable() } -fn push(key: &str) -> bool { - unsafe { _push(key.as_ptr(), key.len()) } +// The component canonical ABI allocates host-to-guest return buffers through a +// `cabi_realloc` core export. wit-bindgen's runtime omits this export for +// wasm32-wasip2 targets, so the guest supplies it over its global allocator. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn cabi_realloc( + old_ptr: *mut u8, + old_len: usize, + align: usize, + new_len: usize, +) -> *mut u8 { + use core::alloc::{GlobalAlloc, Layout}; + + let ptr = if old_len == 0 { + if new_len == 0 { + return align as *mut u8; + } + ALLOCATOR.alloc(Layout::from_size_align_unchecked(new_len, align)) + } else { + debug_assert_ne!(new_len, 0, "non-zero old_len requires non-zero new_len!"); + ALLOCATOR.realloc( + old_ptr, + Layout::from_size_align_unchecked(old_len, align), + new_len, + ) + }; + if ptr.is_null() { + core::arch::wasm32::unreachable(); + } + ptr } -#[no_mangle] -pub fn for_great_justice() -> bool { - // push "/entry/" - push("/entry/"); - // push "/entry/proof" - push("/entry/proof"); +wit_bindgen::generate!({ + world: "unlock-script", + path: "../../../wit/wacc.wit", +}); - true +struct Component; + +impl Guest for Component { + fn for_great_justice() -> i32 { + use crate::cryptid::wacc::host::push; + + let first = push("/entry/"); + let second = push("/entry/proof"); + if first && second { + 1 + } else { + 0 + } + } } + +export!(Component); diff --git a/examples/wacc/wast/Makefile b/examples/wacc/wast/Makefile index 6ef128e..23b339e 100644 --- a/examples/wacc/wast/Makefile +++ b/examples/wacc/wast/Makefile @@ -1,13 +1,29 @@ wasm = $(subst wast,wasm,$(wildcard *.wast)) +# The wacc crate directory; this Makefile lives at examples/wacc/wast. +ROOT := $(abspath ../../..) +GUESTS := unlock log signature_lock signature_first abi +COMPONENTS_DIR := $(ROOT)/target/components + all: $(wasm) %.wasm: %.wast wat2wasm --debug-parser $< -o $@ +guests: + @mkdir -p $(COMPONENTS_DIR) + @for g in $(GUESTS); do \ + echo "building guest $$g"; \ + cargo build --target wasm32-wasip2 --release --manifest-path $(ROOT)/examples/wacc/$$g/Cargo.toml || exit 1; \ + cp $(ROOT)/examples/wacc/$$g/target/wasm32-wasip2/release/$$g.wasm $(COMPONENTS_DIR)/$$g.wasm || exit 1; \ + done + +fixtures: all guests + clean: for f in $(wasm); do \ rm -f $${f}; \ done + rm -rf $(COMPONENTS_DIR) -.PHONY: all clean +.PHONY: all clean guests fixtures \ No newline at end of file diff --git a/examples/wacc/wast/fork_lock.wast b/examples/wacc/wast/fork_lock.wast index 34ae98d..8d8ff6b 100644 --- a/examples/wacc/wast/fork_lock.wast +++ b/examples/wacc/wast/fork_lock.wast @@ -44,7 +44,6 @@ ) ) - ;; check_version failed so return false i32.const 0 return ) diff --git a/examples/wacc/wast/lock.wast b/examples/wacc/wast/lock.wast index 5041e13..bc0d344 100644 --- a/examples/wacc/wast/lock.wast +++ b/examples/wacc/wast/lock.wast @@ -51,7 +51,6 @@ ) ) ) - ;; check_version failed so return false i32.const 0 return ) diff --git a/src/error.rs b/src/error.rs index 2a5e63b..b0798ae 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 +use crate::vm::component::ScriptKind; + /// Errors created by this library #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -186,4 +188,14 @@ pub enum VmError { /// Error message (includes source error details) message: String, }, + + /// The script kind detected in the bytes does not match the kind that the + /// targeted build or call path executes + #[error("script kind mismatch: expected {expected}, found {actual}")] + ScriptKindMismatch { + /// The script kind supported by the targeted execution path + expected: ScriptKind, + /// The script kind detected in the input bytes + actual: ScriptKind, + }, } diff --git a/src/lib.rs b/src/lib.rs index 03475b0..317e80d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,7 +135,9 @@ pub mod types; /// The virtual machine for executing WACC code pub mod vm; -pub use vm::{Builder, Context, Instance, PreparedModule, Runtime, Value}; +pub use vm::{ + Builder, ComponentInstance, Context, Instance, PreparedModule, Runtime, ScriptKind, Value, +}; /// ...and in the darkness bind them pub mod prelude { diff --git a/src/vm.rs b/src/vm.rs index 96f96fb..815d15a 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -3,6 +3,9 @@ /// virtual machine builder pub mod builder; +/// WASM Component Model script support +pub mod component; + /// module caching for performance pub mod cache; @@ -27,6 +30,7 @@ pub mod xmss_guard; pub use builder::Builder; pub use cache::ModuleCache; pub use compiler::Compiler; +pub use component::{ComponentInstance, ScriptKind}; pub use context::Context; pub use instance::Instance; pub use runtime::{PreparedModule, Runtime}; diff --git a/src/vm/builder.rs b/src/vm/builder.rs index 59abe60..1c512a3 100644 --- a/src/vm/builder.rs +++ b/src/vm/builder.rs @@ -1,6 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - error::VmError, security::SecurityLimits, types::FuelAmount, vm::runtime::default_runtime, + error::VmError, + security::SecurityLimits, + types::FuelAmount, + vm::runtime::default_runtime, + vm::{ComponentInstance, ScriptKind}, Context, Error, Instance, PreparedModule, Runtime, }; use std::sync::Arc; @@ -203,6 +207,18 @@ impl Builder { self } + /// Initializes the bytes to execute as a WASM component + /// + /// The bytes are compiled and instantiated through + /// [`Self::try_build_component()`]. Feeding detectable module bytes here + /// makes [`Self::try_build_component()`] fail with + /// [`VmError::ScriptKindMismatch`], mirroring the guard that + /// [`Self::try_build()`] applies to detectable component bytes. + pub fn with_component_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self { + self.bytes = bytes.as_ref().to_vec(); + self + } + /// Add the context for the application state #[must_use] pub fn with_context(mut self, context: Context) -> Self { @@ -229,25 +245,16 @@ impl Builder { /// Tries to build the [`Instance`] from the builder configuration /// /// This method enforces security limits and validates all configuration. - pub fn try_build(self) -> Result { - // Validate fuel against security limits - let fuel = match self.fuel { - Some(f) => { - if f.as_u64() > self.security_limits.max_fuel.as_u64() { - return Err(Error::custom(&format!( - "fuel {} exceeds security limit {}", - f, self.security_limits.max_fuel - ))); - } - f - } - None => { - // Default to security limits fuel - self.security_limits.max_fuel - } - }; + /// + /// Detectable WASM component bytes are rejected with + /// [`VmError::ScriptKindMismatch`]; only [`Self::try_build_component()`] + /// executes components. + pub fn try_build(mut self) -> Result { + self.reject_kind_mismatch(ScriptKind::Module)?; - let (runtime, module) = if let Some(prepared) = self.prepared_module { + let fuel = self.validated_fuel()?; + + let (runtime, module) = if let Some(prepared) = self.prepared_module.take() { if self .runtime .as_ref() @@ -259,7 +266,7 @@ impl Builder { } (prepared.runtime, prepared.module) } else { - let runtime = match self.runtime { + let runtime = match self.runtime.take() { Some(runtime) => runtime, None => default_runtime()?, }; @@ -267,16 +274,7 @@ impl Builder { (runtime, module) }; - // get the context - let context = match self.context { - Some(ctx) => ctx, - None => { - return Err(VmError::MissingContext { - context: "Builder requires context to be set via with_context()".to_string(), - } - .into()) - } - }; + let context = self.required_context()?; // configure the store with fuel (now mandatory for security) let mut store = Store::new(runtime.engine(), context); @@ -294,4 +292,91 @@ impl Builder { store, }) } + + /// Tries to build the [`ComponentInstance`] from the builder configuration + /// + /// Mirrors [`Self::try_build()`]: the same fuel validation, context + /// requirements, security limits, and store setup apply. The component is + /// instantiated against the runtime's component linker, which provides the + /// typed `cryptid:wacc/host@1.0.0` interface for both script worlds. + /// + /// A caller-provided [`PreparedModule`] does not apply here: + /// [`PreparedModule`] carries compiled core modules only, so this method + /// always compiles `self.bytes`. + /// + /// Detectable core-module bytes are rejected with + /// [`VmError::ScriptKindMismatch`]; only [`Self::try_build()`] executes + /// modules. + pub fn try_build_component(mut self) -> Result { + self.reject_kind_mismatch(ScriptKind::Component)?; + + let fuel = self.validated_fuel()?; + + let runtime = match self.runtime.take() { + Some(runtime) => runtime, + None => default_runtime()?, + }; + let component = runtime.compile_component(&self.bytes)?; + + let context = self.required_context()?; + + // configure the store with fuel + let mut store = Store::new(runtime.engine(), context); + store + .set_fuel(fuel.as_u64()) + .map_err(Error::from_wasmtime)?; + + // configure the limiter + store.limiter(|state| &mut state.limiter); + + // instantiate the component and bind the instance + let instance = runtime + .component_linker() + .instantiate(&mut store, component.as_ref()) + .map_err(|e| VmError::InstantiationError { + message: format!("failed to instantiate WASM component: {e}"), + })?; + + Ok(ComponentInstance::new(instance, store)) + } + + /// Returns the fuel to install, validated against the security limits + fn validated_fuel(&self) -> Result { + match self.fuel { + Some(f) => { + if f.as_u64() > self.security_limits.max_fuel.as_u64() { + return Err(Error::custom(&format!( + "fuel {} exceeds security limit {}", + f, self.security_limits.max_fuel + ))); + } + Ok(f) + } + None => { + // Default to security limits fuel + Ok(self.security_limits.max_fuel) + } + } + } + + /// Returns the context required by every build path, failing otherwise + fn required_context(&mut self) -> Result { + self.context.take().ok_or_else(|| { + VmError::MissingContext { + context: "Builder requires context to be set via with_context()".to_string(), + } + .into() + }) + } + + /// Rejects input whose detected script kind does not match the kind the + /// targeted build path executes + fn reject_kind_mismatch(&self, expected: ScriptKind) -> Result<(), Error> { + match ScriptKind::detect(&self.bytes) { + Some(actual) if actual != expected => { + Err(VmError::ScriptKindMismatch { expected, actual }.into()) + } + _ => Ok(()), + } + } } diff --git a/src/vm/cache.rs b/src/vm/cache.rs index 13d648f..39c21ef 100644 --- a/src/vm/cache.rs +++ b/src/vm/cache.rs @@ -8,12 +8,13 @@ use std::collections::HashMap; use std::sync::{Arc, RwLock}; +use wasmtime::component::Component; use wasmtime::Module; -/// A cache for compiled WASM modules +/// A cache for compiled WASM modules and components /// -/// This cache stores compiled modules keyed by their source bytes hash, -/// allowing reuse of expensive compilation results. +/// This cache stores compiled modules and components keyed by their source +/// bytes hash, allowing reuse of expensive compilation results. /// /// # Thread Safety /// @@ -31,6 +32,7 @@ use wasmtime::Module; pub struct ModuleCache { cache: RwLock>>, byte_cache: RwLock>>, + component_cache: RwLock>>, max_entries: usize, } @@ -50,6 +52,7 @@ impl ModuleCache { Self { cache: RwLock::new(HashMap::with_capacity(max_entries.min(100))), byte_cache: RwLock::new(HashMap::with_capacity(max_entries.min(100))), + component_cache: RwLock::new(HashMap::with_capacity(max_entries.min(100))), max_entries, } } @@ -94,6 +97,35 @@ impl ModuleCache { } } + /// Gets a compiled component keyed by the collision-resistant digest of its bytes. + pub fn get_component_bytes(&self, bytes: &[u8]) -> Option> { + self.component_cache + .read() + .ok()? + .get(&Self::digest_bytes(bytes)) + .cloned() + } + + /// Inserts a compiled component keyed by the collision-resistant digest of + /// its bytes. + /// + /// The component cache is bounded by the same `max_entries` limit + /// independently of the module caches. If the cache is full, this is a + /// no-op (simple eviction strategy). + pub fn insert_component_bytes(&self, bytes: &[u8], component: Arc) { + if self.component_len() >= self.max_entries { + return; + } + if let Ok(mut cache) = self.component_cache.write() { + cache.insert(Self::digest_bytes(bytes), component); + } + } + + /// Returns the number of cached components + pub fn component_len(&self) -> usize { + self.component_cache.read().map_or(0, |c| c.len()) + } + /// Returns the number of cached modules pub fn len(&self) -> usize { let keyed = self.cache.read().map_or(0, |c| c.len()); @@ -106,7 +138,7 @@ impl ModuleCache { self.len() == 0 } - /// Clears all cached modules + /// Clears all cached modules and components pub fn clear(&self) { if let Ok(mut cache) = self.cache.write() { cache.clear(); @@ -114,6 +146,9 @@ impl ModuleCache { if let Ok(mut cache) = self.byte_cache.write() { cache.clear(); } + if let Ok(mut cache) = self.component_cache.write() { + cache.clear(); + } } /// Computes a simple hash of the WASM bytes for a caller-managed cache key. @@ -206,4 +241,51 @@ mod tests { cache.insert(3, Arc::new(module3)); assert_eq!(cache.len(), 2); // Should still be 2 } + + const SIMPLE_COMPONENT: &[u8] = b"(component)"; + + fn component_engine() -> Engine { + let mut config = Config::default(); + config.wasm_component_model(true); + Engine::new(&config).unwrap() + } + + #[test] + fn test_component_cache_round_trip() { + let cache = ModuleCache::new(); + assert!(cache.get_component_bytes(SIMPLE_COMPONENT).is_none()); + + let engine = component_engine(); + let component = Component::new(&engine, SIMPLE_COMPONENT).unwrap(); + + cache.insert_component_bytes(SIMPLE_COMPONENT, Arc::new(component)); + + let cached = cache.get_component_bytes(SIMPLE_COMPONENT); + assert!(cached.is_some()); + assert_eq!(cache.component_len(), 1); + assert_eq!(cache.len(), 0); // modules remain counted separately + + cache.clear(); + assert_eq!(cache.component_len(), 0); + } + + #[test] + fn test_component_cache_capacity_independent() { + let cache = ModuleCache::with_capacity(1); + let engine = component_engine(); + let component = Component::new(&engine, SIMPLE_COMPONENT).unwrap(); + + cache.insert_component_bytes(SIMPLE_COMPONENT, Arc::new(component)); + + // the component cache is full, so another insert is rejected + let component2 = Component::new(&engine, SIMPLE_COMPONENT).unwrap(); + cache.insert_component_bytes(SIMPLE_COMPONENT, Arc::new(component2)); + assert_eq!(cache.component_len(), 1); + + // an unrelated module still fits its own bound + let module = Module::new(&engine, SIMPLE_WASM).unwrap(); + cache.insert(ModuleCache::hash_bytes(SIMPLE_WASM), Arc::new(module)); + assert_eq!(cache.len(), 1); + assert_eq!(cache.component_len(), 1); + } } diff --git a/src/vm/component.rs b/src/vm/component.rs new file mode 100644 index 0000000..dd32781 --- /dev/null +++ b/src/vm/component.rs @@ -0,0 +1,403 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! WASM Component Model script support. +//! +//! Components run on the same [`Runtime`](crate::Runtime) engine and share the +//! same [`Context`] state as core modules. A script component imports the +//! typed `cryptid:wacc/host@1.0.0` interface and exports one of the two script +//! worlds: `unlock-script` exports `for-great-justice` and `lock-script` +//! exports `move-every-zig`. The typed interface carries the same semantics as +//! the raw-ABI imports used by the module path. + +use crate::{error::VmError, vm::Context, Error}; +use std::fmt; +use wasmtime::Store; + +/// Bindings for components that implement the `lock-script` world. +pub(crate) mod lock_world { + wasmtime::component::bindgen!({ + world: "lock-script", + }); +} + +/// Bindings for components that implement the `unlock-script` world. +pub(crate) mod unlock_world { + wasmtime::component::bindgen!({ + world: "unlock-script", + }); +} + +/// The WASM execution model that a script artifact targets. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ScriptKind { + /// A core WebAssembly module: binary version byte `0x01` after the `\0asm` + /// magic, or a `module` token at the start of WAT text. + Module, + /// A WASM component: binary version byte `0x0d` after the `\0asm` magic, + /// or a `component` token at the start of WAT text. + Component, +} + +/// Version byte of a binary core WebAssembly module, following the `\0asm` +/// magic. +const MODULE_VERSION_BYTE: u8 = 0x01; + +/// Version byte of a binary WASM component, following the `\0asm` magic. +const COMPONENT_VERSION_BYTE: u8 = 0x0d; + +/// Magic bytes that begin every binary WASM artifact. +const WASM_MAGIC: [u8; 4] = [0x00, b'a', b's', b'm']; + +impl ScriptKind { + /// Detects the WASM execution model that an encoded script artifact + /// targets. + /// + /// Binary artifacts are recognized by the `\0asm` magic followed by the + /// version byte: `0x01` selects [`ScriptKind::Module`] and `0x0d` selects + /// [`ScriptKind::Component`]; any other version byte yields [`None`]. + /// + /// Text artifacts are recognized by skipping leading whitespace, `;;` line + /// comments, and nested `(; ... ;)` block comments, then taking the leading + /// token: `component` selects [`ScriptKind::Component`] and `module` + /// selects [`ScriptKind::Module`]. Both the bare `module` spelling and the + /// parenthesized `(module ...)` form are accepted. + /// + /// Undetectable input yields [`None`], which leaves the kind up to the + /// caller. The documented builders fail loudly only on detectable content. + #[must_use] + pub fn detect(bytes: &[u8]) -> Option { + if bytes.len() >= 5 && bytes[..4] == WASM_MAGIC { + return match bytes[4] { + MODULE_VERSION_BYTE => Some(Self::Module), + COMPONENT_VERSION_BYTE => Some(Self::Component), + _ => None, + }; + } + Self::detect_text(bytes) + } + + /// Applies the text-artifact rule to non-binary input. + fn detect_text(bytes: &[u8]) -> Option { + let text = std::str::from_utf8(bytes).ok()?; + // strip a byte-order mark so BOM-prefixed WAT text stays detectable + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut rest = text.trim_start(); + + // skip leading whitespace and comments until real content is visible + loop { + if rest.is_empty() { + return None; + } + if rest.starts_with(";;") { + // a line comment runs through its newline + let idx = rest.find('\n')?; + rest = rest[idx + 1..].trim_start(); + continue; + } + if rest.starts_with("(;") { + rest = skip_block_comment(rest)?.trim_start(); + continue; + } + break; + } + + // accept both the bare `module`/`component` spelling and the + // parenthesized `(module ...)`/`(component ...)` form + let token = rest.strip_prefix('(').unwrap_or(rest); + + if starts_token(token, "component") { + return Some(Self::Component); + } + if starts_token(token, "module") { + return Some(Self::Module); + } + None + } +} + +/// Skips a `(; ... ;)` WAT block comment, honoring nested comment blocks. +/// +/// Returns the text that follows the comment, or [`None`] when the comment is +/// unterminated. +fn skip_block_comment(rest: &str) -> Option<&str> { + let bytes = rest.as_bytes(); + let mut depth: usize = 0; + let mut idx: usize = 0; + while idx + 1 < bytes.len() { + if bytes[idx] == b'(' && bytes[idx + 1] == b';' { + depth += 1; + idx += 2; + continue; + } + if bytes[idx] == b';' && bytes[idx + 1] == b')' { + depth -= 1; + idx += 2; + if depth == 0 { + return rest.get(idx..); + } + continue; + } + idx += 1; + } + None +} + +/// Returns true when `text` starts with `token` followed by a token boundary, +/// so `components` or `module_name` do not match the header tokens. +fn starts_token(text: &str, token: &str) -> bool { + match text.strip_prefix(token) { + Some("") => true, + Some(after) => !after + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'), + None => false, + } +} + +impl fmt::Display for ScriptKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Module => "module", + Self::Component => "component", + }) + } +} + +/// An instantiated WASM component script bound to a [`Context`]. +/// +/// Mirrors [`crate::Instance`] for the component path: the component instance +/// stays internal while the store is public so callers read stacks and +/// accumulated log lines exactly like they do for modules. Unlike the module +/// path, a component is instantiated once at build time, so no linker is +/// retained after instantiation. +pub struct ComponentInstance { + instance: wasmtime::component::Instance, + + /// Virtual machine store for state + pub store: Store, +} + +impl ComponentInstance { + pub(crate) const fn new( + instance: wasmtime::component::Instance, + store: Store, + ) -> Self { + Self { instance, store } + } + + /// Executes the component's exported script entry point. + /// + /// The name maps to the script worlds: `for_great_justice` or + /// `for-great-justice` calls the `unlock-script` export, and + /// `move_every_zig` or `move-every-zig` calls the `lock-script` export. + /// The legacy snake-case spellings are accepted for compatibility with the + /// module path. A non-zero export result means success, matching + /// [`crate::Instance::run`]. + pub fn run(&mut self, fname: &str) -> Result { + match fname { + "for_great_justice" | "for-great-justice" => { + let world = unlock_world::UnlockScript::new(&mut self.store, &self.instance) + .map_err(|e| VmError::ExecutionError { + function: fname.to_string(), + message: format!("failed to bind export '{fname}': {e}"), + })?; + let result = world.call_for_great_justice(&mut self.store).map_err(|e| { + VmError::ExecutionError { + function: fname.to_string(), + message: format!("function '{fname}' execution failed: {e}"), + } + })?; + Ok(result != 0) + } + "move_every_zig" | "move-every-zig" => { + let world = + lock_world::LockScript::new(&mut self.store, &self.instance).map_err(|e| { + VmError::ExecutionError { + function: fname.to_string(), + message: format!("failed to bind export '{fname}': {e}"), + } + })?; + let result = world.call_move_every_zig(&mut self.store).map_err(|e| { + VmError::ExecutionError { + function: fname.to_string(), + message: format!("function '{fname}' execution failed: {e}"), + } + })?; + Ok(result != 0) + } + _ => Err(VmError::ExecutionError { + function: fname.to_string(), + message: format!( + "'{fname}' is not a script export; expected 'for_great_justice' or \ + 'move_every_zig' (kebab spellings accepted)" + ), + } + .into()), + } + } + + /// Gets the accumulated log data from the context + #[must_use] + pub fn log(&self) -> Vec { + self.store.data().log.clone() + } +} + +/// Converts a raw-ABI `Val` result into the `bool` result that the typed host +/// interface declares, using the same non-zero-means-success rule as +/// [`crate::Instance::run`]. +fn as_bool(value: wasmtime::Val) -> bool { + value.i32().is_some_and(|raw| raw != 0) +} + +impl unlock_world::cryptid::wacc::host::Host for Context { + fn push(&mut self, key: String) -> bool { + as_bool(Self::push(self, &key)) + } + + fn push_value(&mut self, data: Vec) -> bool { + as_bool(Self::push_value(self, data)) + } + + fn branch(&mut self, key: String) -> String { + Self::branch(self, &key) + } + + fn check_eq(&mut self, key: String) -> bool { + as_bool(Self::check_eq(self, &key)) + } + + fn check_preimage(&mut self, key: String) -> bool { + as_bool(Self::check_preimage(self, &key)) + } + + fn check_preimage_value(&mut self, hash: Vec, key: String) -> bool { + as_bool(Self::check_preimage_value(self, &hash, &key)) + } + + fn check_signature(&mut self, key: String, msg: String) -> bool { + as_bool(Self::check_signature(self, &key, &msg)) + } + + fn log(&mut self, text: String) -> bool { + as_bool(Self::log(self, &text)) + } +} + +impl lock_world::cryptid::wacc::host::Host for Context { + fn push(&mut self, key: String) -> bool { + as_bool(Self::push(self, &key)) + } + + fn push_value(&mut self, data: Vec) -> bool { + as_bool(Self::push_value(self, data)) + } + + fn branch(&mut self, key: String) -> String { + Self::branch(self, &key) + } + + fn check_eq(&mut self, key: String) -> bool { + as_bool(Self::check_eq(self, &key)) + } + + fn check_preimage(&mut self, key: String) -> bool { + as_bool(Self::check_preimage(self, &key)) + } + + fn check_preimage_value(&mut self, hash: Vec, key: String) -> bool { + as_bool(Self::check_preimage_value(self, &hash, &key)) + } + + fn check_signature(&mut self, key: String, msg: String) -> bool { + as_bool(Self::check_signature(self, &key, &msg)) + } + + fn log(&mut self, text: String) -> bool { + as_bool(Self::log(self, &text)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detect_accepts_binary_kinds() { + let module = [0x00, 0x61, 0x73, 0x6d, 0x01]; + assert_eq!(ScriptKind::detect(&module), Some(ScriptKind::Module)); + let component = [0x00, 0x61, 0x73, 0x6d, 0x0d]; + assert_eq!(ScriptKind::detect(&component), Some(ScriptKind::Component)); + } + + #[test] + fn detect_rejects_unknown_binary_versions_and_garbage() { + let unknown_version = [0x00, 0x61, 0x73, 0x6d, 0x02]; + assert_eq!(ScriptKind::detect(&unknown_version), None); + assert_eq!(ScriptKind::detect(b"not wasm bytes"), None); + assert_eq!(ScriptKind::detect(&[]), None); + assert_eq!(ScriptKind::detect(&[0x00, 0x61]), None); + } + + #[test] + fn detect_accepts_text_kinds() { + assert_eq!(ScriptKind::detect(b"(module)"), Some(ScriptKind::Module)); + assert_eq!( + ScriptKind::detect(b"(component)"), + Some(ScriptKind::Component) + ); + assert_eq!(ScriptKind::detect(b"module $m"), Some(ScriptKind::Module)); + assert_eq!( + ScriptKind::detect(b"component $c"), + Some(ScriptKind::Component) + ); + assert_eq!( + ScriptKind::detect(b" \n (module "), + Some(ScriptKind::Module) + ); + } + + #[test] + fn detect_text_skips_leading_comments() { + assert_eq!( + ScriptKind::detect(b";; header\n(component)"), + Some(ScriptKind::Component) + ); + assert_eq!( + ScriptKind::detect(b"(; hi ;) component"), + Some(ScriptKind::Component) + ); + assert_eq!( + ScriptKind::detect(b"(;(;nested;) ;) module $m"), + Some(ScriptKind::Module) + ); + assert_eq!(ScriptKind::detect(b";; unterminated"), None); + assert_eq!(ScriptKind::detect(b"(; unterminated"), None); + assert_eq!(ScriptKind::detect(b";; c\n"), None); + } + + #[test] + fn detect_text_tolerates_a_byte_order_mark() { + let bom_prefixed = "\u{feff}(component)".as_bytes(); + assert_eq!( + ScriptKind::detect(bom_prefixed), + Some(ScriptKind::Component) + ); + } + + #[test] + fn detect_text_enforces_token_boundaries() { + assert_eq!(ScriptKind::detect(b"modulet"), None); + assert_eq!(ScriptKind::detect(b"component-thing"), None); + assert_eq!(ScriptKind::detect(b"components"), None); + assert_eq!(ScriptKind::detect(b"module_name"), None); + assert_eq!(ScriptKind::detect(b""), None); + } + + #[test] + fn kind_display_matches_detection_names() { + assert_eq!(ScriptKind::Module.to_string(), "module"); + assert_eq!(ScriptKind::Component.to_string(), "component"); + } +} diff --git a/src/vm/runtime.rs b/src/vm/runtime.rs index 20fada7..5b11e06 100644 --- a/src/vm/runtime.rs +++ b/src/vm/runtime.rs @@ -2,8 +2,14 @@ //! Reusable Wasmtime compilation state. -use crate::{api, error::VmError, Context, Error}; +use crate::{ + api, + error::VmError, + vm::component::{lock_world, unlock_world}, + Context, Error, +}; use std::sync::{Arc, OnceLock}; +use wasmtime::component::{Component, HasSelf, Linker as ComponentLinker}; use wasmtime::{Config, Engine, Linker, Module}; use super::ModuleCache; @@ -12,9 +18,15 @@ use super::ModuleCache; /// /// The engine, linker definitions, and compiled modules are reusable. Each /// [`crate::Instance`] still owns a separate store, context, and fuel budget. +/// +/// One engine serves both execution models: core WASM modules and WASM +/// components. The component linker registers the typed +/// `cryptid:wacc/host@1.0.0` interface for both script worlds; the worlds +/// import the identical interface set, so either registration satisfies them. pub struct Runtime { engine: Engine, linker: Arc>, + component_linker: Arc>, modules: ModuleCache, } @@ -35,14 +47,32 @@ impl Runtime { pub fn with_cache_capacity(max_entries: usize) -> Result { let mut config = Config::default(); config.consume_fuel(true); + config.wasm_component_model(true); let engine = Engine::new(&config).map_err(Error::from_wasmtime)?; let mut linker = Linker::new(&engine); api::add_to_linker(&engine, &mut linker)?; + // Both script worlds import the same typed `cryptid:wacc/host` items, + // so the second registration overwrites an identical first one; + // `allow_shadowing` makes that deterministic re-registration legal. + let mut component_linker = ComponentLinker::new(&engine); + component_linker.allow_shadowing(true); + unlock_world::UnlockScript::add_to_linker::>( + &mut component_linker, + |context| context, + ) + .map_err(Error::from_wasmtime)?; + lock_world::LockScript::add_to_linker::>( + &mut component_linker, + |context| context, + ) + .map_err(Error::from_wasmtime)?; + Ok(Self { engine, linker: Arc::new(linker), + component_linker: Arc::new(component_linker), modules: ModuleCache::with_capacity(max_entries), }) } @@ -52,6 +82,11 @@ impl Runtime { self.modules.len() } + /// Returns the number of compiled components currently cached. + pub fn cached_component_count(&self) -> usize { + self.modules.component_len() + } + /// Compiles and prepares bytecode for repeated instance construction. pub fn prepare(self: &Arc, bytes: &[u8]) -> Result { Ok(PreparedModule { @@ -68,6 +103,10 @@ impl Runtime { self.linker.as_ref().clone() } + pub(crate) fn component_linker(&self) -> ComponentLinker { + self.component_linker.as_ref().clone() + } + pub(crate) fn compile(&self, bytes: &[u8]) -> Result, Error> { if let Some(module) = self.modules.get_bytes(bytes) { return Ok(module); @@ -80,6 +119,25 @@ impl Runtime { self.modules.insert_bytes(bytes, Arc::clone(&module)); Ok(module) } + + /// Compiles a WASM component for repeated instance construction. + /// + /// Mirrors [`Self::compile`]: components are cached by the digest of their + /// source bytes in their own bounded map. + pub(crate) fn compile_component(&self, bytes: &[u8]) -> Result, Error> { + if let Some(component) = self.modules.get_component_bytes(bytes) { + return Ok(component); + } + + let component = + Component::new(&self.engine, bytes).map_err(|e| VmError::CompilationError { + message: format!("failed to compile WASM component: {e}"), + })?; + let component = Arc::new(component); + self.modules + .insert_component_bytes(bytes, Arc::clone(&component)); + Ok(component) + } } impl Default for Runtime { @@ -145,4 +203,27 @@ mod tests { assert!(Arc::ptr_eq(&runtime, &prepared.runtime)); assert_eq!(runtime.cached_module_count(), 1); } + + const SIMPLE_COMPONENT: &[u8] = b"(component)"; + + #[test] + fn reuses_compiled_component() { + let runtime = Runtime::new().unwrap(); + + let first = runtime.compile_component(SIMPLE_COMPONENT).unwrap(); + let second = runtime.compile_component(SIMPLE_COMPONENT).unwrap(); + + assert!(Arc::ptr_eq(&first, &second)); + assert_eq!(runtime.cached_component_count(), 1); + // component caching leaves the module count untouched + assert_eq!(runtime.cached_module_count(), 0); + } + + #[test] + fn does_not_cache_failed_component_compilation() { + let runtime = Runtime::new().unwrap(); + + assert!(runtime.compile_component(b"not wasm").is_err()); + assert_eq!(runtime.cached_component_count(), 0); + } } diff --git a/tests/component.rs b/tests/component.rs new file mode 100644 index 0000000..213ba31 --- /dev/null +++ b/tests/component.rs @@ -0,0 +1,503 @@ +#![allow( + clippy::string_lit_as_bytes, + clippy::manual_string_new, + clippy::needless_pass_by_value, + clippy::uninlined_format_args, + clippy::needless_collect, + clippy::cast_sign_loss +)] +// SPDX-License-Identifier: Apache-2.0 +use std::{collections::BTreeMap, fs::read, path::PathBuf, sync::Arc}; +use test_log::test; +use tracing::info; +use wacc::error::VmError; +use wacc::storage::{Pairs, Stack}; +use wacc::types::{CheckCount, ContextPath}; +use wacc::vm::{Builder, Context, Value}; +use wacc::{Error, Runtime, ScriptKind}; +use wasmparser::{Parser, Payload}; +use wasmtime::StoreLimitsBuilder; + +const MEMORY_LIMIT: usize = 1 << 22; /* 4MB */ + +/// Inline component that imports the typed `cryptid:wacc/host@1.0.0` `push` +/// function and calls it with the string `/entry/` so the same component +/// exercises a typed guest import and a typed component export. The guest core +/// module shares the canonical-ABI memory with the shim, and the exported +/// entry point is named `export_name`. +fn script_component_wat(export_name: &str) -> Vec { + format!( + r#"(component + (import "cryptid:wacc/host@1.0.0" (instance $host + (export "push" (func (param "key" string) (result bool))) + )) + (alias export $host "push" (func $host_push)) + + ;; canonical ABI backing: the memory the guests and the lowerings share + (core module $shim + (memory (export "memory") 1) + ) + (core instance $shim_inst (instantiate $shim)) + (alias core export $shim_inst "memory" (core memory $mem)) + + ;; guest: calls the lowered host import with the data-segment string + (core module $guest + (import "env" "memory" (memory 1)) + (import "env" "push" (func $push (param i32 i32) (result i32))) + (data (i32.const 0) "/entry/") + (func (export "run") (result i32) + (call $push (i32.const 0) (i32.const 7)) + ) + ) + (core func $host_push_lowered (canon lower (func $host_push) (memory $mem))) + (core instance $guest_inst (instantiate $guest + (with "env" (instance + (export "memory" (memory $mem)) + (export "push" (func $host_push_lowered)) + )) + )) + (alias core export $guest_inst "run" (core func $run)) + (type $exit (func (result s32))) + (func $entry (type $exit) (canon lift (core func $run))) + (export "{export_name}" (func $entry)) +)"# + ) + .into_bytes() +} + +/// Component that imports an interface no linker provides, to exercise +/// instantiation failure mapping. +const UNKNOWN_IMPORT_WAT: &[u8] = br#"(component + (import "wacc:unknown/host@1.0.0" (instance (export "unused" (func)))) +)"#; + +/// Core module with the bytes layout of a simple module that exports `test` +/// and returns 1, used to prove the module path still works on the component +/// enabled engine. +const SIMPLE_MODULE_WAT: &[u8] = br#"(module + (memory (export "memory") 1) + (func (export "test") (result i32) (i32.const 1)) +)"#; + +#[derive(Default, Clone)] +struct Kvp { + pub pairs: BTreeMap, +} + +impl Pairs for Kvp { + /// get a value associated with the key + fn get(&self, key: &str) -> Option { + self.pairs.get(key).cloned() + } + + /// add a key-value pair to the storage, return previous value if overwritten + fn put(&mut self, key: &str, value: &Value) -> Option { + self.pairs.insert(key.to_string(), value.clone()) + } +} + +#[derive(Default, Clone)] +struct Stk { + pub stack: Vec, +} + +impl Stack for Stk { + /// push a value onto the stack + fn push(&mut self, value: Value) { + self.stack.push(value); + } + + /// remove the last top value from the stack + fn pop(&mut self) -> Option { + self.stack.pop() + } + + /// get a reference to the top value on the stack + fn top(&self) -> Option { + self.stack.last().cloned() + } + + /// peek at the item at the given index + fn peek(&self, idx: usize) -> Option { + if idx >= self.stack.len() { + return None; + } + Some(self.stack[self.stack.len() - 1 - idx].clone()) + } + + /// return the number of values on the stack + fn len(&self) -> usize { + self.stack.len() + } + + /// return true if there are no values on the stack + fn is_empty(&self) -> bool { + self.stack.is_empty() + } +} + +/// Builds a [`Context`] whose current KVP holds the `/entry/` path that the +/// inline component's `push` import resolves. +fn make_context() -> Context { + let mut current = Kvp::default(); + current.put( + "/entry/", + &Value::Bin { + hint: String::new(), + data: Arc::from(vec![1, 2, 3].into_boxed_slice()), + }, + ); + + Context { + current: Box::new(current), + proposed: Box::new(Kvp::default()), + pstack: Box::new(Stk::default()), + rstack: Box::new(Stk::default()), + check_count: CheckCount::zero(), + write_idx: 0, + context: ContextPath::root(), + log: Vec::default(), + limiter: StoreLimitsBuilder::new() + .memory_size(MEMORY_LIMIT) + .instances(16) + .memories(8) + .build(), + } +} + +fn build_component(component_wat: &[u8], context: Context) -> wacc::vm::ComponentInstance { + info!("building component of {} bytes", component_wat.len()); + match Builder::new() + .with_context(context) + .with_component_bytes(component_wat) + .try_build_component() + { + Ok(component) => component, + Err(e) => { + println!("component builder failed: {}", e); + panic!() + } + } +} + +/// Loads a built guest component fixture; guests live as separate Cargo +/// projects under `examples/wacc/` and the Makefile copies their components +/// into the crate's `target/components/` directory. +fn load_component(file_name: &str) -> Option> { + let mut pb = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + pb.push("target/components"); + pb.push(file_name); + info!("trying to load: {}", pb.as_os_str().display()); + read(&pb).ok() +} + +/// Builds a [`Context`] for the `abi` guest fixture: `/abi/` resolves in the +/// current KVP and the branch prefix makes the composed key-path distinctive. +fn make_abi_context() -> Context { + let mut current = Kvp::default(); + current.put( + "/abi/", + &Value::Bin { + hint: String::new(), + data: Arc::from(vec![1, 2, 3].into_boxed_slice()), + }, + ); + + Context { + current: Box::new(current), + proposed: Box::new(Kvp::default()), + pstack: Box::new(Stk::default()), + rstack: Box::new(Stk::default()), + check_count: CheckCount::zero(), + write_idx: 0, + context: ContextPath::new("/forks/child/"), + log: Vec::default(), + limiter: StoreLimitsBuilder::new() + .memory_size(MEMORY_LIMIT) + .instances(16) + .memories(8) + .build(), + } +} + +#[test] +fn test_component_unlock_runs_with_both_export_spellings() { + let wat = script_component_wat("for-great-justice"); + + let mut component = build_component(&wat, make_context()); + + // the legacy snake spelling maps onto the kebab world export + assert!(component.run("for_great_justice").unwrap()); + + // the typed push import left one entry-parameter on the parameter stack + let pstack = component.store.data().pstack.top(); + assert!(matches!(pstack, Some(Value::Bin { .. }))); + assert_eq!(component.store.data().pstack.len(), 1); + + // the kebab spelling runs on the already instantiated component + assert!(component.run("for-great-justice").unwrap()); + assert_eq!(component.store.data().pstack.len(), 2); +} + +#[test] +fn test_component_lock_runs_with_both_export_spellings() { + let wat = script_component_wat("move-every-zig"); + + let mut component = build_component(&wat, make_context()); + + assert!(component.run("move_every_zig").unwrap()); + assert_eq!(component.store.data().pstack.len(), 1); + + assert!(component.run("move-every-zig").unwrap()); + assert_eq!(component.store.data().pstack.len(), 2); +} + +#[test] +fn test_component_unknown_export_name_fails() { + let wat = script_component_wat("for-great-justice"); + + let mut component = build_component(&wat, make_context()); + + let result = component.run("no_such_export"); + assert!(matches!( + result, + Err(Error::Vm(VmError::ExecutionError { .. })) + )); +} + +#[test] +fn test_module_builder_rejects_component_bytes() { + let wat = script_component_wat("for-great-justice"); + + let result = Builder::new() + .with_context(make_context()) + .with_bytes(&wat) + .try_build(); + + assert!(matches!( + result, + Err(Error::Vm(VmError::ScriptKindMismatch { + expected: ScriptKind::Module, + actual: ScriptKind::Component, + })) + )); +} + +#[test] +fn test_component_builder_rejects_module_bytes() { + let result = Builder::new() + .with_context(make_context()) + .with_component_bytes(SIMPLE_MODULE_WAT) + .try_build_component(); + + assert!(matches!( + result, + Err(Error::Vm(VmError::ScriptKindMismatch { + expected: ScriptKind::Component, + actual: ScriptKind::Module, + })) + )); +} + +#[test] +fn test_component_compilation_is_cached() { + let runtime = Arc::new(Runtime::new().unwrap()); + let wat = script_component_wat("for-great-justice"); + + let _first = Builder::new() + .with_context(make_context()) + .with_runtime(Arc::clone(&runtime)) + .with_component_bytes(&wat) + .try_build_component() + .unwrap(); + + let _second = Builder::new() + .with_context(make_context()) + .with_runtime(Arc::clone(&runtime)) + .with_component_bytes(&wat) + .try_build_component() + .unwrap(); + + assert_eq!(runtime.cached_component_count(), 1); + // component caching leaves the module count untouched + assert_eq!(runtime.cached_module_count(), 0); +} + +#[test] +fn test_module_path_still_runs_on_shared_engine() { + let mut instance = Builder::new() + .with_context(make_context()) + .with_bytes(SIMPLE_MODULE_WAT) + .try_build() + .unwrap(); + + assert!(instance.run("test").unwrap()); +} + +#[test] +fn test_component_build_fails_without_context() { + let wat = script_component_wat("for-great-justice"); + + let result = Builder::new() + .with_component_bytes(&wat) + .try_build_component(); + + assert!(matches!( + result, + Err(Error::Vm(VmError::MissingContext { .. })) + )); +} + +#[test] +fn test_unknown_import_fails_instantiation() { + let result = Builder::new() + .with_context(make_context()) + .with_component_bytes(UNKNOWN_IMPORT_WAT) + .try_build_component(); + + assert!(matches!( + result, + Err(Error::Vm(VmError::InstantiationError { .. })) + )); +} + +#[test] +fn test_script_kind_detects_wat_component_text() { + // binary components carry the component version byte at index 4; prove + // the detector keeps the binary rule by compiling the wat text component + // and checking the text rule against the same artifact's wat form + let wat = script_component_wat("for-great-justice"); + assert_eq!(ScriptKind::detect(&wat), Some(ScriptKind::Component)); +} + +/// Component whose guest burns fuel in a bounded-counter loop so large it +/// exhausts any practical fuel budget before reaching its exit, so the typed +/// export call traps with the store's fuel limit. +const INFINITE_LOOP_COMPONENT_WAT: &[u8] = br#"(component + (core module $guest + (func (export "run") (result i32) + (local $i i64) + (loop $burn + (local.set $i (i64.add (local.get $i) (i64.const 1))) + (br_if $burn (i64.lt_u (local.get $i) (i64.const 4611686018427387904))) + ) + (i32.const 1) + ) + ) + (core instance $inst (instantiate $guest)) + (alias core export $inst "run" (core func $run)) + (type $exit (func (result s32))) + (func $entry (type $exit) (canon lift (core func $run))) + (export "for-great-justice" (func $entry)) +)"#; + +#[test] +fn test_fuel_exhaustion_traps_on_the_component_path() { + let mut component = build_component(INFINITE_LOOP_COMPONENT_WAT, make_context()); + + let result = component.run("for_great_justice"); + assert!(matches!( + result, + Err(Error::Vm(VmError::ExecutionError { .. })) + )); +} + +#[test] +fn test_abi_guest_fixture_round_trips_the_typed_imports() { + // Skip test if the component fixture is not built (run 'make -C + // examples/wacc/wast guests') + let Some(bytes) = load_component("abi.wasm") else { + eprintln!( + "Skipping test_abi_guest_fixture_round_trips_the_typed_imports: abi.wasm not found" + ); + return; + }; + + let mut component = build_component(&bytes, make_abi_context()); + + assert!(component.run("for_great_justice").unwrap()); + + // push and push-value both landed on the parameter stack: the kvp-backed + // value first, then the raw guest bytes + assert_eq!(component.store.data().pstack.len(), 2); + assert_eq!( + component.store.data().pstack.top(), + Some(Value::Bin { + hint: String::new(), + data: Arc::from(vec![0xAB, 0xCD].into_boxed_slice()) + }) + ); + assert_eq!( + component.store.data().pstack.peek(1), + Some(Value::Bin { + hint: String::new(), + data: Arc::from(vec![1, 2, 3].into_boxed_slice()) + }) + ); + + // the four stateless checks each left a failure marker on the return stack + // and incremented the check counter once + assert_eq!(component.store.data().rstack.len(), 4); + for value in [ + component.store.data().rstack.peek(0), + component.store.data().rstack.peek(1), + component.store.data().rstack.peek(2), + component.store.data().rstack.peek(3), + ] + .into_iter() + .flatten() + { + assert!(matches!(value, Value::Failure { .. })); + } + assert_eq!(component.store.data().check_count.as_usize(), 4); + + // branch returned the composed key-path through the guest realloc path + // and the guest logged it back along with its own line + let log = String::from_utf8(component.log()).unwrap(); + assert!(log.contains("/forks/child//abi/proof"), "log: {log:?}"); + assert!(log.contains("/abi/log-line"), "log: {log:?}"); +} + +/// The guest fixture components, built by `make -C examples/wacc/wast guests`. +const GUEST_FIXTURES: [&str; 5] = ["abi", "unlock", "log", "signature_lock", "signature_first"]; + +/// Checks every built fixture component imports only the typed +/// `cryptid:wacc/host@1.0.0` interface, so the no-WASI property of the guest +/// recipe stays verified. +#[test] +fn test_fixture_components_import_only_the_typed_host_interface() { + let mut checked: usize = 0; + for name in GUEST_FIXTURES { + let Some(bytes) = load_component(&format!("{name}.wasm")) else { + eprintln!( + "Skipping {name}.wasm: fixture not found (run 'make -C examples/wacc/wast guests')" + ); + continue; + }; + + let mut imports: Vec = Vec::new(); + for payload in Parser::new(0).parse_all(&bytes) { + // component-level imports: the fixture guests import the typed + // `cryptid:wacc/host@1.0.0` interface instance and nothing else. + // The core modules embedded inside the component have their own + // import sections and are not part of the guest's host surface. + if let Payload::ComponentImportSection(reader) = payload.unwrap() { + for import in reader { + imports.push(import.unwrap().name.name.to_string()); + } + } + } + + assert!( + imports.iter().all(|module| !module.starts_with("wasi:")), + "{name} imports a WASI interface: {imports:?}" + ); + assert_eq!( + imports, + vec!["cryptid:wacc/host@1.0.0".to_string()], + "{name} unexpected import set" + ); + checked += 1; + } + eprintln!("checked {checked} fixture component(s) for import hygiene"); +} diff --git a/wit/wacc.wit b/wit/wacc.wit new file mode 100644 index 0000000..99fafd5 --- /dev/null +++ b/wit/wacc.wit @@ -0,0 +1,22 @@ +package cryptid:wacc@1.0.0; + +interface host { + push: func(key: string) -> bool; + push-value: func(data: list) -> bool; + branch: func(key: string) -> string; + check-eq: func(key: string) -> bool; + check-preimage: func(key: string) -> bool; + check-preimage-value: func(hash: list, key: string) -> bool; + check-signature: func(key: string, msg: string) -> bool; + log: func(text: string) -> bool; +} + +world unlock-script { + import host; + export for-great-justice: func() -> s32; +} + +world lock-script { + import host; + export move-every-zig: func() -> s32; +} \ No newline at end of file