From aaee9811368343da50c4fdddbb88ddbfb9cad4f5 Mon Sep 17 00:00:00 2001 From: Luther Blissett Date: Fri, 14 Oct 2022 00:59:37 +0200 Subject: [PATCH] sdk: Add initial state query draft. The current implenmentation is able to scan the nullifier set. --- src/sdk/src/error.rs | 18 ++++++++++++++++++ src/sdk/src/lib.rs | 3 +++ src/sdk/src/state.rs | 24 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/sdk/src/state.rs diff --git a/src/sdk/src/error.rs b/src/sdk/src/error.rs index 1940a3cc1..0e46e2f71 100644 --- a/src/sdk/src/error.rs +++ b/src/sdk/src/error.rs @@ -13,6 +13,12 @@ pub enum ContractError { #[error("Internal error")] Internal, + + #[error("IO error: {0}")] + IoError(String), + + #[error("Error checking if nullifier exists")] + NullifierExistCheck, } /// Builtin return values occupy the upper 32 bits @@ -25,11 +31,15 @@ macro_rules! to_builtin { pub const CUSTOM_ZERO: u64 = to_builtin!(1); pub const INTERNAL_ERROR: u64 = to_builtin!(2); +pub const IO_ERROR: u64 = to_builtin!(3); +pub const NULLIFIER_EXIST_CHECK: u64 = to_builtin!(4); impl From for u64 { fn from(err: ContractError) -> Self { match err { ContractError::Internal => INTERNAL_ERROR, + ContractError::IoError(_) => IO_ERROR, + ContractError::NullifierExistCheck => NULLIFIER_EXIST_CHECK, ContractError::Custom(error) => { if error == 0 { CUSTOM_ZERO @@ -46,7 +56,15 @@ impl From for ContractError { match error { CUSTOM_ZERO => Self::Custom(0), INTERNAL_ERROR => Self::Internal, + IO_ERROR => Self::IoError("Unknown".to_string()), + NULLIFIER_EXIST_CHECK => Self::NullifierExistCheck, _ => Self::Custom(error as u32), } } } + +impl From for ContractError { + fn from(err: std::io::Error) -> Self { + Self::IoError(format!("{}", err)) + } +} diff --git a/src/sdk/src/lib.rs b/src/sdk/src/lib.rs index 95368d6eb..79b39a999 100644 --- a/src/sdk/src/lib.rs +++ b/src/sdk/src/lib.rs @@ -9,3 +9,6 @@ pub mod log; /// Crypto-related definitions pub mod crypto; + +/// Functions for state queries +pub mod state; diff --git a/src/sdk/src/state.rs b/src/sdk/src/state.rs new file mode 100644 index 000000000..bd3b03ef8 --- /dev/null +++ b/src/sdk/src/state.rs @@ -0,0 +1,24 @@ +use super::{crypto::Nullifier, error::ContractError}; + +pub fn nullifier_exists(nullifier: &Nullifier) -> Result { + #[cfg(target_arch = "wasm32")] + unsafe { + // Convert to bytes, and pass pointer to first byte in slice to the function. + let nf = nullifier.to_bytes(); + return match nullifier_exists_(&nf as *const u8, 32) { + 0 => Ok(false), + 1 => Ok(true), + -1 => Err(ContractError::NullifierExistCheck), + -2 => Err(ContractError::Internal), + _ => unreachable!(), + } + } + + #[cfg(not(target_arch = "wasm32"))] + todo!("nullifier_exists({:?}", nullifier); +} + +#[cfg(target_arch = "wasm32")] +extern "C" { + fn nullifier_exists_(ptr: *const u8, len: u32) -> i32; +}