279 lines
8.2 KiB
Rust
Raw Normal View History

//! 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<EcashToken>,
pub transactions: Vec<EcashTransaction>,
#[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).map(|t| t.amount_sats).sum()
}
}
/// Load wallet state from disk.
pub async fn load_wallet(data_dir: &Path) -> Result<WalletState> {
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<EcashToken> {
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(&quote_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<u64> {
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<String> {
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<u64> {
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::<u64>().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()
}