Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: SDK fix/1403 - Port crypto & shared libs to sdk package #1408

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7,422 changes: 7,422 additions & 0 deletions packages/sdk/lib/Cargo.lock

Large diffs are not rendered by default.

100 changes: 100 additions & 0 deletions packages/sdk/lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
[package]
name = "sdk"
authors = ["Heliax AG <[email protected]>"]
version = "0.1.0"
edition = "2021"
repository = "https://github.com/anoma/namada-interface/"
description = "SDK functionality from Namada protocol"
license = "MIT"

[lib]
crate-type = ["cdylib", "rlib"]

[features]
default = []
dev = []
multicore = ["rayon", "wasm-bindgen-rayon", "namada_sdk/multicore"]
nodejs = []
web = []

[build-dependencies]
namada_tx = { git = "https://github.com/anoma/namada", rev = "49a4a5d3260423df19ead14df82d18a51fa9b157" }

# TODO: Update to use versions from namada!
[dependencies]
aes-gcm = "0.10.1"
argon2 = "0.4.1"
async-trait = {version = "0.1.51"}
bip32 = { version = "0.4.0", features = ["bip39"] }
borsh-ext = { git = "https://github.com/heliaxdev/borsh-ext", tag = "v1.2.0" }
chrono = "0.4.22"
getrandom = { version = "0.2.7", features = ["js"] }
gloo-utils = { version = "0.1.5", features = ["serde"] }
js-sys = "0.3.60"
orion = "0.16.0"
masp_primitives = { git = "https://github.com/anoma/masp", tag = "v1.1.0" }
namada_sdk = { git = "https://github.com/anoma/namada", rev="49a4a5d3260423df19ead14df82d18a51fa9b157", default-features = false }
password-hash = "0.4.2"
rand = "0.8.5"
rayon = { version = "1.5.3", optional = true }
rexie = "0.5"
serde = "^1.0.181"
serde_json = "1.0"
tendermint-config = "0.34.0"
tokio = {version = "1.8.2", features = ["rt"]}
thiserror = "^1"
# wasm-bindgen = "0.2.86"
wasm-bindgen = "=0.2.92"
wasm-bindgen-futures = "0.4.33"
wasm-bindgen-rayon = { version = "1.0", optional = true }
console_error_panic_hook = "0.1.6"
zeroize = "1.6.0"
hex = "0.4.3"
reqwest = "0.11.25"
subtle-encoding = "0.5.1"
tiny-bip39 = { git = "https://github.com/anoma/tiny-bip39", rev = "743d537349c8deab14409ce726b868dcde90fd8e" }
slip10_ed25519 = "0.1.3"

[dependencies.web-sys]
version = "0.3.4"
features = [
'console',
'Document',
'Event',
'EventTarget',
'CustomEvent',
'CustomEventInit',
'Headers',
'Request',
'RequestInit',
'RequestMode',
'Response',
'Window',
]

[dev-dependencies]
wasm-bindgen-test = "0.3.13"

# https://doc.rust-lang.org/cargo/reference/profiles.html
[profile.release]
lto = true

[profile.dev]
opt-level = 3
lto = true

# wasm-pack specific configuration
[package.metadata.wasm-pack.profile.release]
# https://docs.rs/wasm-opt/latest/wasm_opt/
wasm-opt = ['-O4']

[package.metadata.wasm-pack.profile.dev]
wasm-opt = false

[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
omit-default-module-path = true
# We set it to false as it checks if return type from setTimout is a number which is not true in the nodejs environment
debug-js-glue = false

[package.metadata.wasm-pack.profile.release.wasm-bindgen]
omit-default-module-path = true
25 changes: 25 additions & 0 deletions packages/sdk/lib/LICENSE_MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) 2018 Heliax Dev <[email protected]>

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
27 changes: 27 additions & 0 deletions packages/sdk/lib/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# SDK lib

Rust library for wrapping Namada types and functionality and compiling to wasm, as used by Namadillo and Namada Keychain.

## Usage

```bash
# Install wasm-bindgen-cli
cargo install -f wasm-bindgen-cli

# TODO: Fix the following!

# Build wasm
node ./scripts/build.js --multicore --release

# Build wasm to a NodeJS target (for testing)
node ./scripts/build.js --target node
```

## Testing

```bash
cargo test

# Test wasm-specific features
wasm-pack test --node
```
4 changes: 4 additions & 0 deletions packages/sdk/lib/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[toolchain]
channel = "nightly-2024-09-08"
components = ["rustc", "cargo", "rust-std", "rust-docs", "rls", "rust-src", "rust-analysis"]
targets = ['wasm32-unknown-unknown']
99 changes: 99 additions & 0 deletions packages/sdk/lib/src/crypto/aes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use crate::crypto::pointer_types::VecU8Pointer;
use aes_gcm::{
aead::{generic_array::GenericArray, Aead, KeyInit},
Aes256Gcm, Nonce,
};
use thiserror::Error;
use wasm_bindgen::prelude::*;
use zeroize::Zeroize;

#[derive(Debug, Error)]
pub enum AESError {
#[error("Invalid key size! Minimum key size is 32.")]
KeyLengthError,
#[error("Invalid IV! Expected 96 bits (12 bytes)")]
IVSizeError,
}

#[wasm_bindgen]
pub struct AES {
cipher: Aes256Gcm,
iv: [u8; 12],
}

#[wasm_bindgen]
impl AES {
#[wasm_bindgen(constructor)]
pub fn new(key: VecU8Pointer, iv: Vec<u8>) -> Result<AES, String> {
if key.length < 32 {
return Err(format!(
"{} Received {}",
AESError::KeyLengthError,
key.length
));
}
let mut key = GenericArray::from_iter(key.vec.clone().into_iter());
let iv: [u8; 12] = match iv.try_into() {
Ok(iv) => iv,
Err(_) => {
key.zeroize();
return Err(AESError::IVSizeError.to_string());
}
};

let aes = AES {
cipher: Aes256Gcm::new(&key),
iv,
};
key.zeroize();
Ok(aes)
}

pub fn encrypt(&self, mut text: String) -> Result<Vec<u8>, String> {
let nonce = Nonce::from_slice(&self.iv);
let result = self
.cipher
.encrypt(nonce, text.as_ref())
.map_err(|err| err.to_string());
text.zeroize();
result
}

pub fn decrypt(&self, ciphertext: Vec<u8>) -> Result<VecU8Pointer, String> {
let nonce = Nonce::from_slice(&self.iv);
let plaintext = self
.cipher
.decrypt(nonce, ciphertext.as_ref())
.map_err(|err| err.to_string())?;

Ok(VecU8Pointer::new(plaintext))
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::crypto::rng::{ByteSize, Rng};
use wasm_bindgen_test::*;

#[wasm_bindgen_test]
fn can_encrypt_and_decrypt() {
let key = Rng::generate_bytes(Some(ByteSize::N32))
.expect("Generating random bytes should not fail");
let iv = Rng::generate_bytes(Some(ByteSize::N12))
.expect("Generating random bytes should not fail");
let aes = AES::new(VecU8Pointer::new(key), iv).unwrap();
let plaintext = "my secret message";
let encrypted = aes
.encrypt(String::from(plaintext))
.expect("AES should not fail encrypting plaintext");

let decrypted: &[u8] = &aes
.decrypt(encrypted)
.expect("AES should not fail decrypting ciphertext")
.vec;
let decrypted = std::str::from_utf8(decrypted).expect("Should parse as string");

assert_eq!(decrypted, plaintext);
}
}
Loading
Loading