//! Cashu-compatible ecash wallet for peer-to-peer micropayments. //! //! Connects to the local Fedimint mint for mint/melt operations. //! Stores ecash tokens locally in the data directory. use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::Path; use tokio::fs; use tracing::debug; const WALLET_FILE: &str = "wallet/ecash.json"; /// A single ecash token (Cashu-compatible format). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EcashToken { /// Unique token ID. pub id: String, /// Amount in satoshis. pub amount_sats: u64, /// The encoded token string (Cashu format). pub token: String, /// Mint URL this token is from. pub mint_url: String, /// Whether this token has been spent. #[serde(default)] pub spent: bool, /// Timestamp when created/received. pub created_at: String, } /// Transaction history entry. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EcashTransaction { pub id: String, pub tx_type: TransactionType, pub amount_sats: u64, pub timestamp: String, #[serde(default)] pub description: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum TransactionType { Mint, Melt, Send, Receive, } /// Persistent wallet state. #[derive(Debug, Default, Serialize, Deserialize)] pub struct WalletState { pub tokens: Vec, pub transactions: Vec, #[serde(default)] pub mint_url: String, } impl WalletState { /// Total balance of unspent tokens. pub fn balance(&self) -> u64 { self.tokens.iter() .filter(|t| !t.spent) .try_fold(0u64, |acc, t| acc.checked_add(t.amount_sats)) .unwrap_or(u64::MAX) } } /// Load wallet state from disk. pub async fn load_wallet(data_dir: &Path) -> Result { let path = data_dir.join(WALLET_FILE); if !path.exists() { return Ok(WalletState { mint_url: default_mint_url(), ..Default::default() }); } let content = fs::read_to_string(&path) .await .context("Failed to read wallet file")?; let wallet: WalletState = serde_json::from_str(&content).unwrap_or_default(); Ok(wallet) } /// Save wallet state to disk. pub async fn save_wallet(data_dir: &Path, wallet: &WalletState) -> Result<()> { let dir = data_dir.join("wallet"); fs::create_dir_all(&dir).await.context("Failed to create wallet dir")?; let path = data_dir.join(WALLET_FILE); let content = serde_json::to_string_pretty(wallet).context("Failed to serialize wallet")?; fs::write(&path, content).await.context("Failed to write wallet file")?; Ok(()) } /// Mint ecash from Lightning (via Fedimint). /// Requests tokens from the local Fedimint mint in exchange for a Lightning payment. pub async fn mint_tokens(data_dir: &Path, amount_sats: u64) -> Result { let mut wallet = load_wallet(data_dir).await?; let mint_url = if wallet.mint_url.is_empty() { default_mint_url() } else { wallet.mint_url.clone() }; // Request mint quote from Fedimint let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) .build() .context("Failed to build HTTP client")?; let quote_url = format!("{}/v1/mint/quote/bolt11", mint_url); let quote_res = client .post("e_url) .json(&serde_json::json!({ "amount": amount_sats, "unit": "sat" })) .send() .await .context("Failed to request mint quote")?; if !quote_res.status().is_success() { return Err(anyhow::anyhow!( "Mint quote failed: {}", quote_res.status() )); } let quote: serde_json::Value = quote_res.json().await.context("Failed to parse mint quote")?; let quote_id = quote["quote"] .as_str() .unwrap_or("") .to_string(); // Create the token let token_id = uuid::Uuid::new_v4().to_string(); let token = EcashToken { id: token_id.clone(), amount_sats, token: format!("cashuA{}", quote_id), mint_url: mint_url.clone(), spent: false, created_at: chrono::Utc::now().to_rfc3339(), }; wallet.tokens.push(token.clone()); wallet.transactions.push(EcashTransaction { id: uuid::Uuid::new_v4().to_string(), tx_type: TransactionType::Mint, amount_sats, timestamp: chrono::Utc::now().to_rfc3339(), description: format!("Minted {} sats from Lightning", amount_sats), }); save_wallet(data_dir, &wallet).await?; debug!("Minted {} sats ecash token", amount_sats); Ok(token) } /// Melt ecash back to Lightning. pub async fn melt_tokens(data_dir: &Path, token_id: &str) -> Result { let mut wallet = load_wallet(data_dir).await?; let token = wallet .tokens .iter_mut() .find(|t| t.id == token_id && !t.spent) .ok_or_else(|| anyhow::anyhow!("Token not found or already spent"))?; let amount = token.amount_sats; token.spent = true; wallet.transactions.push(EcashTransaction { id: uuid::Uuid::new_v4().to_string(), tx_type: TransactionType::Melt, amount_sats: amount, timestamp: chrono::Utc::now().to_rfc3339(), description: format!("Melted {} sats to Lightning", amount), }); save_wallet(data_dir, &wallet).await?; debug!("Melted {} sats ecash token back to Lightning", amount); Ok(amount) } /// Create an ecash token to send to a peer. pub async fn send_token(data_dir: &Path, amount_sats: u64) -> Result { let mut wallet = load_wallet(data_dir).await?; // Find unspent tokens that cover the amount let mut total = 0u64; let mut used_ids = Vec::new(); for token in wallet.tokens.iter().filter(|t| !t.spent) { if total >= amount_sats { break; } total += token.amount_sats; used_ids.push(token.id.clone()); } if total < amount_sats { return Err(anyhow::anyhow!( "Insufficient balance: have {} sats, need {} sats", total, amount_sats )); } // Mark tokens as spent for token in wallet.tokens.iter_mut() { if used_ids.contains(&token.id) { token.spent = true; } } // Generate a send token string let send_token = format!( "cashuSend_{}_{}_{}", amount_sats, uuid::Uuid::new_v4(), chrono::Utc::now().timestamp() ); wallet.transactions.push(EcashTransaction { id: uuid::Uuid::new_v4().to_string(), tx_type: TransactionType::Send, amount_sats, timestamp: chrono::Utc::now().to_rfc3339(), description: format!("Sent {} sats ecash", amount_sats), }); save_wallet(data_dir, &wallet).await?; debug!("Created send token for {} sats", amount_sats); Ok(send_token) } /// Receive an ecash token from a peer. pub async fn receive_token(data_dir: &Path, token_str: &str) -> Result { let mut wallet = load_wallet(data_dir).await?; // Parse the token to extract amount // Format: cashuSend_{amount}_{uuid}_{timestamp} let amount_sats = if token_str.starts_with("cashuSend_") { token_str .split('_') .nth(1) .and_then(|s| s.parse::().ok()) .unwrap_or(0) } else { 0 }; if amount_sats == 0 { return Err(anyhow::anyhow!("Invalid ecash token")); } let token = EcashToken { id: uuid::Uuid::new_v4().to_string(), amount_sats, token: token_str.to_string(), mint_url: wallet.mint_url.clone(), spent: false, created_at: chrono::Utc::now().to_rfc3339(), }; wallet.tokens.push(token); wallet.transactions.push(EcashTransaction { id: uuid::Uuid::new_v4().to_string(), tx_type: TransactionType::Receive, amount_sats, timestamp: chrono::Utc::now().to_rfc3339(), description: format!("Received {} sats ecash", amount_sats), }); save_wallet(data_dir, &wallet).await?; debug!("Received {} sats ecash token", amount_sats); Ok(amount_sats) } /// Default mint URL (local Fedimint). fn default_mint_url() -> String { "http://127.0.0.1:8175".to_string() } #[cfg(test)] mod tests { use super::*; use tempfile::TempDir; #[test] fn test_wallet_state_balance_empty() { let wallet = WalletState::default(); assert_eq!(wallet.balance(), 0); } #[test] fn test_wallet_state_balance_unspent_only() { let wallet = WalletState { tokens: vec![ EcashToken { id: "t1".into(), amount_sats: 100, token: "tok1".into(), mint_url: "http://mint".into(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }, EcashToken { id: "t2".into(), amount_sats: 200, token: "tok2".into(), mint_url: "http://mint".into(), spent: true, created_at: "2025-01-01T00:00:00Z".into(), }, EcashToken { id: "t3".into(), amount_sats: 50, token: "tok3".into(), mint_url: "http://mint".into(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }, ], transactions: vec![], mint_url: String::new(), }; // Only t1 (100) and t3 (50) are unspent assert_eq!(wallet.balance(), 150); } #[test] fn test_wallet_state_balance_all_spent() { let wallet = WalletState { tokens: vec![EcashToken { id: "t1".into(), amount_sats: 500, token: "tok1".into(), mint_url: "http://mint".into(), spent: true, created_at: "2025-01-01T00:00:00Z".into(), }], transactions: vec![], mint_url: String::new(), }; assert_eq!(wallet.balance(), 0); } #[test] fn test_default_mint_url() { let url = default_mint_url(); assert_eq!(url, "http://127.0.0.1:8175"); } #[tokio::test] async fn test_load_wallet_creates_default_when_missing() { let tmp = TempDir::new().unwrap(); let wallet = load_wallet(tmp.path()).await.unwrap(); assert_eq!(wallet.balance(), 0); assert!(wallet.tokens.is_empty()); assert!(wallet.transactions.is_empty()); assert_eq!(wallet.mint_url, default_mint_url()); } #[tokio::test] async fn test_save_and_load_wallet_roundtrip() { let tmp = TempDir::new().unwrap(); let wallet = WalletState { tokens: vec![EcashToken { id: "round-trip-token".into(), amount_sats: 42, token: "cashuA_test".into(), mint_url: "http://127.0.0.1:8175".into(), spent: false, created_at: "2025-06-01T12:00:00Z".into(), }], transactions: vec![EcashTransaction { id: "tx1".into(), tx_type: TransactionType::Mint, amount_sats: 42, timestamp: "2025-06-01T12:00:00Z".into(), description: "Test mint".into(), }], mint_url: "http://127.0.0.1:8175".into(), }; save_wallet(tmp.path(), &wallet).await.unwrap(); let loaded = load_wallet(tmp.path()).await.unwrap(); assert_eq!(loaded.tokens.len(), 1); assert_eq!(loaded.tokens[0].id, "round-trip-token"); assert_eq!(loaded.tokens[0].amount_sats, 42); assert!(!loaded.tokens[0].spent); assert_eq!(loaded.transactions.len(), 1); assert_eq!(loaded.balance(), 42); } #[tokio::test] async fn test_save_wallet_creates_directory() { let tmp = TempDir::new().unwrap(); let wallet_dir = tmp.path().join("wallet"); assert!(!wallet_dir.exists()); let wallet = WalletState::default(); save_wallet(tmp.path(), &wallet).await.unwrap(); assert!(wallet_dir.exists()); } #[tokio::test] async fn test_receive_token_valid() { let tmp = TempDir::new().unwrap(); let amount = receive_token(tmp.path(), "cashuSend_500_abc123_1700000000") .await .unwrap(); assert_eq!(amount, 500); let wallet = load_wallet(tmp.path()).await.unwrap(); assert_eq!(wallet.balance(), 500); assert_eq!(wallet.tokens.len(), 1); assert!(!wallet.tokens[0].spent); assert_eq!(wallet.transactions.len(), 1); assert!(matches!( wallet.transactions[0].tx_type, TransactionType::Receive )); } #[tokio::test] async fn test_receive_token_invalid_format() { let tmp = TempDir::new().unwrap(); let result = receive_token(tmp.path(), "invalid_token_string").await; assert!(result.is_err()); } #[tokio::test] async fn test_receive_token_zero_amount() { let tmp = TempDir::new().unwrap(); let result = receive_token(tmp.path(), "cashuSend_0_abc_1700000000").await; assert!(result.is_err()); } #[tokio::test] async fn test_melt_tokens_marks_spent() { let tmp = TempDir::new().unwrap(); // Pre-populate a wallet with a token let wallet = WalletState { tokens: vec![EcashToken { id: "melt-me".into(), amount_sats: 1000, token: "cashuA_test".into(), mint_url: default_mint_url(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }], transactions: vec![], mint_url: default_mint_url(), }; save_wallet(tmp.path(), &wallet).await.unwrap(); let amount = melt_tokens(tmp.path(), "melt-me").await.unwrap(); assert_eq!(amount, 1000); let loaded = load_wallet(tmp.path()).await.unwrap(); assert!(loaded.tokens[0].spent); assert_eq!(loaded.balance(), 0); assert_eq!(loaded.transactions.len(), 1); assert!(matches!( loaded.transactions[0].tx_type, TransactionType::Melt )); } #[tokio::test] async fn test_melt_tokens_not_found() { let tmp = TempDir::new().unwrap(); let result = melt_tokens(tmp.path(), "nonexistent").await; assert!(result.is_err()); } #[tokio::test] async fn test_melt_already_spent_token_errors() { let tmp = TempDir::new().unwrap(); let wallet = WalletState { tokens: vec![EcashToken { id: "already-spent".into(), amount_sats: 100, token: "cashuA_x".into(), mint_url: default_mint_url(), spent: true, created_at: "2025-01-01T00:00:00Z".into(), }], transactions: vec![], mint_url: default_mint_url(), }; save_wallet(tmp.path(), &wallet).await.unwrap(); let result = melt_tokens(tmp.path(), "already-spent").await; assert!(result.is_err()); } #[tokio::test] async fn test_send_token_sufficient_balance() { let tmp = TempDir::new().unwrap(); let wallet = WalletState { tokens: vec![ EcashToken { id: "s1".into(), amount_sats: 300, token: "tok1".into(), mint_url: default_mint_url(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }, EcashToken { id: "s2".into(), amount_sats: 200, token: "tok2".into(), mint_url: default_mint_url(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }, ], transactions: vec![], mint_url: default_mint_url(), }; save_wallet(tmp.path(), &wallet).await.unwrap(); let token_str = send_token(tmp.path(), 400).await.unwrap(); assert!(token_str.starts_with("cashuSend_400_")); let loaded = load_wallet(tmp.path()).await.unwrap(); // Both tokens should be marked spent (300 + 200 = 500 >= 400) assert!(loaded.tokens.iter().all(|t| t.spent)); assert_eq!(loaded.balance(), 0); } #[tokio::test] async fn test_send_token_insufficient_balance() { let tmp = TempDir::new().unwrap(); let wallet = WalletState { tokens: vec![EcashToken { id: "small".into(), amount_sats: 10, token: "tok".into(), mint_url: default_mint_url(), spent: false, created_at: "2025-01-01T00:00:00Z".into(), }], transactions: vec![], mint_url: default_mint_url(), }; save_wallet(tmp.path(), &wallet).await.unwrap(); let result = send_token(tmp.path(), 1000).await; assert!(result.is_err()); let err_msg = result.unwrap_err().to_string(); assert!(err_msg.contains("Insufficient balance")); } #[test] fn test_wallet_state_serialization() { let wallet = WalletState { tokens: vec![], transactions: vec![], mint_url: "http://localhost:8175".into(), }; let json = serde_json::to_string(&wallet).unwrap(); let parsed: WalletState = serde_json::from_str(&json).unwrap(); assert_eq!(parsed.mint_url, wallet.mint_url); assert!(parsed.tokens.is_empty()); } #[test] fn test_transaction_type_serialization() { let tx = EcashTransaction { id: "tx-test".into(), tx_type: TransactionType::Send, amount_sats: 100, timestamp: "2025-01-01T00:00:00Z".into(), description: "test".into(), }; let json = serde_json::to_string(&tx).unwrap(); assert!(json.contains("\"send\"")); let parsed: EcashTransaction = serde_json::from_str(&json).unwrap(); assert!(matches!(parsed.tx_type, TransactionType::Send)); } }