use std::collections::BTreeMap;
use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Nonce};
use argon2::{Algorithm, Argon2, Params, Version};
use async_trait::async_trait;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use crate::error::SdkError;
use crate::signer::{LocalSigner, Signer};
use crate::types::{
Address, FalconPubkey, FalconSecret, FalconSignature, Tx, TxHash, FALCON_SECRET_LEN,
};
pub struct Wallet {
signer: LocalSigner,
}
impl Wallet {
pub fn generate() -> Result<Self, SdkError> {
Ok(Self {
signer: LocalSigner::random()?,
})
}
pub fn from_seed(seed: &[u8; 32]) -> Result<Self, SdkError> {
Ok(Self {
signer: LocalSigner::from_seed(seed)?,
})
}
pub fn from_keys(pubkey: FalconPubkey, secret: FalconSecret) -> Result<Self, SdkError> {
Ok(Self {
signer: LocalSigner::from_keys(pubkey, secret)?,
})
}
#[must_use]
pub fn signer(&self) -> &LocalSigner {
&self.signer
}
#[must_use]
pub fn address(&self) -> Address {
self.signer.address()
}
#[must_use]
pub fn pubkey(&self) -> FalconPubkey {
self.signer.pubkey()
}
pub fn to_keystore(&self, account_name: &str, password: &str) -> Result<Keystore, SdkError> {
let mut keystore = Keystore::new();
self.add_to_keystore(&mut keystore, account_name, password)?;
Ok(keystore)
}
pub fn add_to_keystore(
&self,
keystore: &mut Keystore,
account_name: &str,
password: &str,
) -> Result<(), SdkError> {
let entry = encrypt_entry(&self.pubkey(), self.signer.secret(), password)?;
keystore.accounts.insert(account_name.to_string(), entry);
Ok(())
}
pub fn from_keystore(
keystore: &Keystore,
account_name: &str,
password: &str,
) -> Result<Self, SdkError> {
if keystore.version > KEYSTORE_VERSION {
return Err(SdkError::InvalidArgument(format!(
"unsupported keystore version {}",
keystore.version
)));
}
let entry = keystore.accounts.get(account_name).ok_or_else(|| {
SdkError::InvalidArgument(format!("no account named {account_name:?} in keystore"))
})?;
let (pubkey, secret) = decrypt_entry(entry, password)?;
Self::from_keys(pubkey, secret)
}
pub fn from_keystore_json(
json: &str,
account_name: &str,
password: &str,
) -> Result<Self, SdkError> {
if let Ok(keystore) = serde_json::from_str::<Keystore>(json) {
if !keystore.accounts.is_empty() {
return Self::from_keystore(&keystore, account_name, password);
}
}
if let Ok(legacy) = serde_json::from_str::<LegacyKeystore>(json) {
return Self::from_legacy(&legacy, password);
}
Err(SdkError::InvalidArgument(
"unrecognized keystore format (neither canonical vault nor legacy 0.1.0)".into(),
))
}
fn from_legacy(legacy: &LegacyKeystore, password: &str) -> Result<Self, SdkError> {
if legacy.version != 1 {
return Err(SdkError::InvalidArgument(format!(
"unsupported legacy keystore version {}",
legacy.version
)));
}
if legacy.kdf.name != "argon2id" {
return Err(SdkError::InvalidArgument(format!(
"unsupported KDF: {}",
legacy.kdf.name
)));
}
if legacy.cipher.name != "aes-256-gcm" {
return Err(SdkError::InvalidArgument(format!(
"unsupported cipher: {}",
legacy.cipher.name
)));
}
let salt = decode_hex(&legacy.kdf.params.salt, SALT_LEN, "salt")?;
let nonce_bytes = decode_hex(&legacy.cipher.nonce, AES_NONCE_LEN, "nonce")?;
let ciphertext = decode_hex_var(&legacy.cipher.ciphertext, "ciphertext")?;
let pubkey = FalconPubkey::from_hex(&legacy.pubkey)?;
let address = Address::from_hex(&legacy.address)?;
if Address::from_pubkey(&pubkey) != address {
return Err(SdkError::InvalidArgument(
"keystore address does not match pubkey".into(),
));
}
let mut key = derive_key(
password,
&salt,
legacy.kdf.params.m,
legacy.kdf.params.t,
legacy.kdf.params.p,
)?;
let aad = address.to_hex().into_bytes();
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|e| SdkError::Other(format!("AES key init failed: {e}")))?;
let plaintext = cipher
.decrypt(
Nonce::from_slice(&nonce_bytes),
Payload {
msg: &ciphertext,
aad: &aad,
},
)
.map_err(|_| {
SdkError::InvalidArgument(
"decrypt failed — bad password or corrupt keystore".into(),
)
});
key.zeroize();
let secret = secret_from_plaintext(plaintext?)?;
Self::from_keys(pubkey, secret)
}
}
#[async_trait]
impl Signer for Wallet {
fn address(&self) -> Address {
self.signer.address()
}
fn pubkey(&self) -> FalconPubkey {
self.signer.pubkey()
}
async fn sign_hash(&self, hash: &TxHash) -> Result<FalconSignature, SdkError> {
self.signer.sign_hash(hash).await
}
async fn sign_tx(&self, tx: &mut Tx) -> Result<(), SdkError> {
self.signer.sign_tx(tx).await
}
}
impl std::fmt::Debug for Wallet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Wallet")
.field("address", &self.signer.address())
.field("pubkey", &self.signer.pubkey())
.finish()
}
}
pub const KEYSTORE_VERSION: u32 = 1;
pub const ARGON2_MEMORY_KB: u32 = 64 * 1024;
pub const ARGON2_ITERATIONS: u32 = 3;
pub const ARGON2_PARALLELISM: u32 = 4;
pub const ARGON2_MAX_MEMORY_KB: u32 = 1_048_576;
pub const ARGON2_MAX_ITERATIONS: u32 = 16;
pub const ARGON2_MAX_PARALLELISM: u32 = 16;
const AES_KEY_LEN: usize = 32;
const AES_NONCE_LEN: usize = 12;
const SALT_LEN: usize = 16;
fn default_cipher_aes() -> String {
"aes-256-gcm".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Keystore {
pub version: u32,
#[serde(default)]
pub accounts: BTreeMap<String, KeystoreEntry>,
}
impl Default for Keystore {
fn default() -> Self {
Self::new()
}
}
impl Keystore {
#[must_use]
pub fn new() -> Self {
Self {
version: KEYSTORE_VERSION,
accounts: BTreeMap::new(),
}
}
#[must_use]
pub fn account_names(&self) -> Vec<&str> {
self.accounts.keys().map(String::as_str).collect()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeystoreEntry {
pub address: String,
pub pubkey: String,
pub ciphertext: String,
pub salt: String,
pub nonce: String,
#[serde(default = "default_cipher_aes")]
pub cipher: String,
pub kdf: KdfParams,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KdfParams {
pub name: String,
pub memory_kb: u32,
pub iterations: u32,
pub parallelism: u32,
}
impl KdfParams {
#[must_use]
pub fn current() -> Self {
Self {
name: "argon2id".into(),
memory_kb: ARGON2_MEMORY_KB,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
}
}
}
fn encrypt_entry(
pubkey: &FalconPubkey,
secret: &FalconSecret,
password: &str,
) -> Result<KeystoreEntry, SdkError> {
let mut rng = rand::thread_rng();
let mut salt = [0u8; SALT_LEN];
rng.fill_bytes(&mut salt);
let mut nonce_bytes = [0u8; AES_NONCE_LEN];
rng.fill_bytes(&mut nonce_bytes);
let mut key = derive_key(
password,
&salt,
ARGON2_MEMORY_KB,
ARGON2_ITERATIONS,
ARGON2_PARALLELISM,
)?;
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|e| SdkError::Other(format!("AES key init failed: {e}")))?;
let ciphertext = cipher
.encrypt(Nonce::from_slice(&nonce_bytes), &secret.as_bytes()[..])
.map_err(|e| SdkError::Other(format!("AES encrypt failed: {e}")))?;
key.zeroize();
let address = Address::from_pubkey(pubkey);
Ok(KeystoreEntry {
address: address.to_hex(),
pubkey: pubkey.to_hex(),
ciphertext: format!("0x{}", hex::encode(&ciphertext)),
salt: format!("0x{}", hex::encode(salt)),
nonce: format!("0x{}", hex::encode(nonce_bytes)),
cipher: default_cipher_aes(),
kdf: KdfParams::current(),
})
}
fn decrypt_entry(
entry: &KeystoreEntry,
password: &str,
) -> Result<(FalconPubkey, FalconSecret), SdkError> {
if entry.kdf.name != "argon2id" {
return Err(SdkError::InvalidArgument(format!(
"unsupported KDF: {}",
entry.kdf.name
)));
}
if entry.kdf.memory_kb > ARGON2_MAX_MEMORY_KB
|| entry.kdf.iterations > ARGON2_MAX_ITERATIONS
|| entry.kdf.parallelism > ARGON2_MAX_PARALLELISM
{
return Err(SdkError::InvalidArgument(
"keystore KDF parameters exceed the accepted upper bound".into(),
));
}
let salt = decode_hex(&entry.salt, SALT_LEN, "salt")?;
let nonce_bytes = decode_hex(&entry.nonce, AES_NONCE_LEN, "nonce")?;
let ciphertext = decode_hex_var(&entry.ciphertext, "ciphertext")?;
let pubkey = FalconPubkey::from_hex(&entry.pubkey)?;
let address = Address::from_hex(&entry.address)?;
if Address::from_pubkey(&pubkey) != address {
return Err(SdkError::InvalidArgument(
"keystore address does not match pubkey".into(),
));
}
let mut key = derive_key(
password,
&salt,
entry.kdf.memory_kb,
entry.kdf.iterations,
entry.kdf.parallelism,
)?;
if entry.cipher != "aes-256-gcm" {
key.zeroize();
return Err(SdkError::InvalidArgument(format!(
"unsupported cipher suite: {}",
entry.cipher
)));
}
let plaintext = aes_decrypt(&key, &nonce_bytes, &ciphertext);
key.zeroize();
let secret = secret_from_plaintext(plaintext?)?;
Ok((pubkey, secret))
}
fn aes_decrypt(
key: &[u8; AES_KEY_LEN],
nonce: &[u8],
ciphertext: &[u8],
) -> Result<Vec<u8>, SdkError> {
let cipher = Aes256Gcm::new_from_slice(key)
.map_err(|e| SdkError::Other(format!("AES key init failed: {e}")))?;
cipher
.decrypt(Nonce::from_slice(nonce), ciphertext)
.map_err(|_| {
SdkError::InvalidArgument("decrypt failed — bad password or corrupt keystore".into())
})
}
fn secret_from_plaintext(plaintext: Vec<u8>) -> Result<FalconSecret, SdkError> {
if plaintext.len() != FALCON_SECRET_LEN {
return Err(SdkError::InvalidArgument(format!(
"decrypted secret is {} bytes, expected {FALCON_SECRET_LEN}",
plaintext.len()
)));
}
let mut sk_bytes = [0u8; FALCON_SECRET_LEN];
sk_bytes.copy_from_slice(&plaintext);
let mut zeroable = plaintext;
zeroable.zeroize();
Ok(FalconSecret::new(sk_bytes))
}
fn derive_key(
password: &str,
salt: &[u8],
m_kib: u32,
t: u32,
p: u32,
) -> Result<[u8; AES_KEY_LEN], SdkError> {
let params = Params::new(m_kib, t, p, Some(AES_KEY_LEN))
.map_err(|e| SdkError::InvalidArgument(format!("argon2 params invalid: {e}")))?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; AES_KEY_LEN];
argon2
.hash_password_into(password.as_bytes(), salt, &mut key)
.map_err(|e| SdkError::Other(format!("argon2 KDF failed: {e}")))?;
Ok(key)
}
fn decode_hex(s: &str, expected_len: usize, label: &str) -> Result<Vec<u8>, SdkError> {
let stripped = s.trim_start_matches("0x");
let bytes = hex::decode(stripped)
.map_err(|e| SdkError::InvalidArgument(format!("bad {label} hex: {e}")))?;
if bytes.len() != expected_len {
return Err(SdkError::InvalidArgument(format!(
"{label}: expected {expected_len} bytes, got {}",
bytes.len()
)));
}
Ok(bytes)
}
fn decode_hex_var(s: &str, label: &str) -> Result<Vec<u8>, SdkError> {
let stripped = s.trim_start_matches("0x");
hex::decode(stripped).map_err(|e| SdkError::InvalidArgument(format!("bad {label} hex: {e}")))
}
#[derive(Deserialize)]
struct LegacyKeystore {
version: u32,
address: String,
pubkey: String,
kdf: LegacyKdf,
cipher: LegacyCipher,
}
#[derive(Deserialize)]
struct LegacyKdf {
name: String,
params: LegacyArgon2Params,
}
#[derive(Deserialize)]
struct LegacyArgon2Params {
m: u32,
t: u32,
p: u32,
salt: String,
}
#[derive(Deserialize)]
struct LegacyCipher {
name: String,
nonce: String,
ciphertext: String,
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::tx::{tx_hash, TxBuilder};
#[test]
fn wallet_drop_wipes_secret() {
assert!(core::mem::needs_drop::<Wallet>());
assert!(core::mem::needs_drop::<LocalSigner>());
assert!(core::mem::needs_drop::<FalconSecret>());
for _ in 0..16 {
let w = Wallet::generate().unwrap();
let _addr = w.address();
drop(w);
}
}
#[tokio::test]
async fn wallet_signs_a_tx_end_to_end() {
let wallet = Wallet::generate().unwrap();
let to = Address::new([0x55; 32]);
let mut tx = TxBuilder::new()
.from(wallet.address())
.transfer(to, 1_500_000_000)
.build()
.unwrap();
let pre = tx_hash(&tx);
wallet.sign_tx(&mut tx).await.unwrap();
let post = tx_hash(&tx);
assert_eq!(pre, post, "signature must not affect tx_hash");
assert!(!tx.signature.is_empty());
}
#[test]
fn keystore_round_trip() {
let wallet = Wallet::generate().unwrap();
let address = wallet.address();
let pubkey = wallet.pubkey();
let pw = "correct horse battery staple";
let ks = wallet.to_keystore("acct", pw).unwrap();
let restored = Wallet::from_keystore(&ks, "acct", pw).unwrap();
assert_eq!(restored.address(), address);
assert_eq!(restored.pubkey(), pubkey);
}
#[test]
fn keystore_uses_canonical_params_and_shape() {
let wallet = Wallet::generate().unwrap();
let ks = wallet.to_keystore("acct", "pw").unwrap();
assert_eq!(ks.version, KEYSTORE_VERSION);
let entry = ks.accounts.get("acct").unwrap();
assert_eq!(entry.cipher, "aes-256-gcm");
assert_eq!(entry.kdf.name, "argon2id");
assert_eq!(entry.kdf.memory_kb, 65_536);
assert_eq!(entry.kdf.iterations, 3);
assert_eq!(entry.kdf.parallelism, 4);
assert!(entry.salt.starts_with("0x"));
assert!(entry.nonce.starts_with("0x"));
assert!(entry.ciphertext.starts_with("0x"));
}
#[test]
fn keystore_wrong_password_fails() {
let wallet = Wallet::generate().unwrap();
let ks = wallet.to_keystore("acct", "right password").unwrap();
let err = Wallet::from_keystore(&ks, "acct", "wrong password").unwrap_err();
assert!(matches!(err, SdkError::InvalidArgument(_)));
}
#[test]
fn keystore_unknown_account_fails() {
let wallet = Wallet::generate().unwrap();
let ks = wallet.to_keystore("acct", "pw").unwrap();
assert!(Wallet::from_keystore(&ks, "nope", "pw").is_err());
}
#[test]
fn keystore_json_round_trip() {
let wallet = Wallet::generate().unwrap();
let ks = wallet.to_keystore("acct", "pw").unwrap();
let json = serde_json::to_string(&ks).unwrap();
let restored = Wallet::from_keystore_json(&json, "acct", "pw").unwrap();
assert_eq!(restored.address(), wallet.address());
}
#[test]
fn multi_account_vault() {
let a = Wallet::generate().unwrap();
let b = Wallet::generate().unwrap();
let mut ks = a.to_keystore("a", "pw").unwrap();
b.add_to_keystore(&mut ks, "b", "pw").unwrap();
assert_eq!(ks.account_names().len(), 2);
assert_eq!(
Wallet::from_keystore(&ks, "a", "pw").unwrap().address(),
a.address()
);
assert_eq!(
Wallet::from_keystore(&ks, "b", "pw").unwrap().address(),
b.address()
);
}
#[test]
fn keystore_different_writes_differ() {
let wallet = Wallet::generate().unwrap();
let a = wallet.to_keystore("x", "pw").unwrap();
let b = wallet.to_keystore("x", "pw").unwrap();
let ea = a.accounts.get("x").unwrap();
let eb = b.accounts.get("x").unwrap();
assert_ne!(ea.ciphertext, eb.ciphertext);
assert_ne!(ea.salt, eb.salt);
assert_ne!(ea.nonce, eb.nonce);
}
#[test]
fn rejects_above_clamp_kdf() {
let wallet = Wallet::generate().unwrap();
let mut ks = wallet.to_keystore("acct", "pw").unwrap();
ks.accounts.get_mut("acct").unwrap().kdf.memory_kb = 2_097_152;
let err = Wallet::from_keystore(&ks, "acct", "pw").unwrap_err();
assert!(matches!(err, SdkError::InvalidArgument(ref m) if m.contains("upper bound")));
}
#[test]
fn accepts_below_floor_keystore() {
let wallet = Wallet::generate().unwrap();
let pw = "pw";
let (m, t, p) = (8 * 1024, 1, 1);
let mut salt = [0u8; SALT_LEN];
let mut nonce = [0u8; AES_NONCE_LEN];
rand::thread_rng().fill_bytes(&mut salt);
rand::thread_rng().fill_bytes(&mut nonce);
let key = derive_key(pw, &salt, m, t, p).unwrap();
let cipher = Aes256Gcm::new_from_slice(&key).unwrap();
let ct = cipher
.encrypt(
Nonce::from_slice(&nonce),
&wallet.signer().secret().as_bytes()[..],
)
.unwrap();
let addr = wallet.address();
let entry = KeystoreEntry {
address: addr.to_hex(),
pubkey: wallet.pubkey().to_hex(),
ciphertext: format!("0x{}", hex::encode(&ct)),
salt: format!("0x{}", hex::encode(salt)),
nonce: format!("0x{}", hex::encode(nonce)),
cipher: "aes-256-gcm".into(),
kdf: KdfParams {
name: "argon2id".into(),
memory_kb: m,
iterations: t,
parallelism: p,
},
};
let mut ks = Keystore::new();
ks.accounts.insert("acct".into(), entry);
let restored = Wallet::from_keystore(&ks, "acct", pw).unwrap();
assert_eq!(restored.address(), addr);
}
#[test]
fn unsupported_version_rejected() {
let wallet = Wallet::generate().unwrap();
let mut ks = wallet.to_keystore("acct", "pw").unwrap();
ks.version = 999;
assert!(Wallet::from_keystore(&ks, "acct", "pw").is_err());
}
}