watcher/watchlet/src/wallet/manager.rs
2025-09-18 18:55:38 +02:00

53 lines
1.4 KiB
Rust

use age::secrecy::SecretString;
use shared::blockchain_core::{validator::Validator, SignedTransaction, Transaction};
use super::{
wallet::{ Wallet, WalletError },
storage::WalletStorage,
};
pub struct WalletManager<S: WalletStorage> {
storage: S,
wallet: Option<Wallet>
}
impl<S: WalletStorage> WalletManager<S> {
pub fn new(storage: S) -> Self {
Self {
storage,
wallet: None,
}
}
pub fn create_wallet(&mut self, passphrase: SecretString) -> Result<&Wallet, S::Error> {
let wallet = Wallet::new();
self.storage.save(&wallet, passphrase)?;
self.wallet = Some(wallet);
Ok(self.wallet.as_ref().unwrap())
}
pub fn load_wallet(&mut self, passphrase: SecretString) -> Result<&Wallet, S::Error> {
let wallet = self.storage.load(passphrase)?;
self.wallet = Some(wallet);
Ok(self.wallet.as_ref().unwrap())
}
pub fn wallet(&self) -> Option<&Wallet> {
self.wallet.as_ref()
}
pub fn sign_transaction(&self, transaction: Transaction) -> Result<SignedTransaction, WalletError> {
match &self.wallet {
Some(wallet) => Ok(wallet.sign(transaction)?),
None => Err(WalletError::NoPrivateKeyProvided),
}
}
pub fn verify_transaction(&self, transaction: SignedTransaction) -> Result<(), WalletError> {
match &self.wallet {
Some(_wallet) => Ok(Validator::verify_signature(&transaction)?),
None => Err(WalletError::NoPrivateKeyProvided),
}
}
}