SPB Git

Repository Public Apache-2.0

lib.rs 5.0 KB 144 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-wasm/src/lib.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! WebAssembly packaging of the SPB Quantum Crypto C ABI.42//!43//! The module built from this crate (`wasm32-unknown-unknown`) exports:44//!45//! * every `spb_pqc_*` function of `include/spb_pqc.h`, unchanged;46//! * `spb_pqc_wasm_init()` — installs the randomness bridge; call once after instantiation;47//! * `spb_pqc_alloc(len)` / `spb_pqc_free(ptr, len)` — buffers inside the linear48//!   memory for passing arguments; `free` wipes before releasing;49//! * `memory`.50//!51//! and imports exactly one function, `spb_pqc_host.random_fill(ptr, len) -> i32`,52//! which the host must implement with `crypto.getRandomValues` and which must53//! return `0` only when all `len` bytes were written. Without it, or if it54//! reports a failure, every randomised operation fails closed with55//! `SPB_PQC_ERR_RANDOM_FAILURE`.56//!57//! Limits: a Rust panic traps the instance (WebAssembly has no unwinding here);58//! the JavaScript wrapper turns the trap into an error and discards the59//! instance. Linear memory is visible to all JavaScript in the same realm.60#![allow(unsafe_code)]61#![allow(clippy::missing_safety_doc)]6263// Link the C ABI: its `#[no_mangle]` functions become exports of this module.64pub use spb_pqc::*;6566use std::alloc::{alloc_zeroed, dealloc, Layout};6768#[cfg(target_arch = "wasm32")]69mod host {70    #[link(wasm_import_module = "spb_pqc_host")]71    extern "C" {72        /// Fills `len` bytes at `ptr` from the host CSPRNG; returns 0 on success.73        pub fn random_fill(ptr: *mut u8, len: usize) -> i32;74    }7576    pub fn bridge(buf: &mut [u8]) -> bool {77        if buf.is_empty() {78            return true;79        }80        // SAFETY: `buf` is a live region of the module's linear memory.81        unsafe { random_fill(buf.as_mut_ptr(), buf.len()) == 0 }82    }83}8485/// Installs the CSPRNG bridge. Idempotent; returns 0.86#[no_mangle]87pub extern "C" fn spb_pqc_wasm_init() -> i32 {88    #[cfg(target_arch = "wasm32")]89    {90        let _ = spb_pqc_core::random::install_host_bridge(host::bridge);91    }92    093}9495const ALIGN: usize = 8;9697/// Allocates `len` zeroed bytes in the module's memory. Returns null when98/// `len` is 0 or the allocation fails.99#[no_mangle]100pub extern "C" fn spb_pqc_alloc(len: usize) -> *mut u8 {101    if len == 0 {102        return core::ptr::null_mut();103    }104    match Layout::from_size_align(len, ALIGN) {105        // SAFETY: the layout has a non-zero size.106        Ok(layout) => unsafe { alloc_zeroed(layout) },107        Err(_) => core::ptr::null_mut(),108    }109}110111/// Wipes and releases a buffer obtained from [`spb_pqc_alloc`] with the same `len`.112#[no_mangle]113pub unsafe extern "C" fn spb_pqc_free(ptr: *mut u8, len: usize) {114    if ptr.is_null() || len == 0 {115        return;116    }117    if let Ok(layout) = Layout::from_size_align(len, ALIGN) {118        // SAFETY: `ptr` was returned by `spb_pqc_alloc(len)` and not freed yet.119        unsafe {120            spb_pqc_core::ct::wipe(core::slice::from_raw_parts_mut(ptr, len));121            dealloc(ptr, layout);122        }123    }124}125126#[cfg(test)]127mod tests {128    use super::*;129130    #[test]131    fn alloc_free_round_trip() {132        assert!(spb_pqc_alloc(0).is_null());133        let p = spb_pqc_alloc(64);134        assert!(!p.is_null());135        unsafe {136            assert!(core::slice::from_raw_parts(p, 64).iter().all(|&b| b == 0));137            *p = 7;138            spb_pqc_free(p, 64);139            spb_pqc_free(core::ptr::null_mut(), 64);140        }141        assert_eq!(spb_pqc_wasm_init(), 0);142    }143}144
Files main
Menu

Theme