diff --git a/Cargo.toml b/Cargo.toml index d9e8beb4..33c0e04b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "crates/cdk", + "crates/cdk-redb", ] resolver = "2" @@ -21,6 +22,9 @@ keywords = ["bitcoin", "e-cash", "cashu"] [workspace.dependencies] tokio = { version = "1.32", default-features = false } +cdk = { path = "./crates/cdk", default-features = false } +thiserror = "1.0.50" +async-trait = "0.1.74" [profile] diff --git a/crates/cdk-redb/Cargo.toml b/crates/cdk-redb/Cargo.toml new file mode 100644 index 00000000..db184f96 --- /dev/null +++ b/crates/cdk-redb/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "cdk-redb" +version = "0.1.0" +edition = "2021" +license.workspace = true +homepage.workspace = true +repository.workspace = true +rust-version.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +async-trait.workspace = true +cdk.workspace = true +redb = "2.0.0" +tokio.workspace = true +thiserror.workspace = true +serde_json = "1.0.96" diff --git a/crates/cdk-redb/src/lib.rs b/crates/cdk-redb/src/lib.rs new file mode 100644 index 00000000..567166b4 --- /dev/null +++ b/crates/cdk-redb/src/lib.rs @@ -0,0 +1,3 @@ +pub mod wallet_redb; + +pub use wallet_redb::RedbWalletDatabase; diff --git a/crates/cdk-redb/src/wallet_redb.rs b/crates/cdk-redb/src/wallet_redb.rs new file mode 100644 index 00000000..7a6e2163 --- /dev/null +++ b/crates/cdk-redb/src/wallet_redb.rs @@ -0,0 +1,589 @@ +use std::collections::HashMap; +use std::num::ParseIntError; +use std::str::FromStr; +use std::sync::Arc; + +use async_trait::async_trait; +use cdk::cdk_database::{self, WalletDatabase}; +use cdk::nuts::{Id, KeySetInfo, Keys, MintInfo, Proofs}; +use cdk::types::{MeltQuote, MintQuote}; +use cdk::url::UncheckedUrl; +use redb::{Database, MultimapTableDefinition, ReadableTable, TableDefinition}; +use thiserror::Error; +use tokio::sync::Mutex; + +#[derive(Debug, Error)] +pub enum Error { + #[error(transparent)] + Redb(#[from] redb::Error), + #[error(transparent)] + Database(#[from] redb::DatabaseError), + #[error(transparent)] + Transaction(#[from] redb::TransactionError), + #[error(transparent)] + Commit(#[from] redb::CommitError), + #[error(transparent)] + Table(#[from] redb::TableError), + #[error(transparent)] + Storage(#[from] redb::StorageError), + #[error(transparent)] + Serde(#[from] serde_json::Error), + #[error(transparent)] + ParseInt(#[from] ParseIntError), +} + +impl From for cdk_database::Error { + fn from(e: Error) -> Self { + Self::Database(Box::new(e)) + } +} + +const MINTS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mints_table"); +const MINT_KEYSETS_TABLE: MultimapTableDefinition<&str, &str> = + MultimapTableDefinition::new("mint_keysets"); +const MINT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_quotes"); +const MELT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("melt_quotes"); +const MINT_KEYS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_keys"); +const PROOFS_TABLE: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("proofs"); +const PENDING_PROOFS_TABLE: MultimapTableDefinition<&str, &str> = + MultimapTableDefinition::new("pending_proofs"); +const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config"); +const KEYSET_COUNTER: TableDefinition<&str, u64> = TableDefinition::new("keyset_counter"); + +const DATABASE_VERSION: u64 = 0; + +#[derive(Debug, Clone)] +pub struct RedbWalletDatabase { + db: Arc>, +} + +impl RedbWalletDatabase { + pub fn new(path: &str) -> Result { + let db = Database::create(path)?; + + let write_txn = db.begin_write()?; + + // Check database version + { + let _ = write_txn.open_table(CONFIG_TABLE)?; + let mut table = write_txn.open_table(CONFIG_TABLE)?; + + let db_version = table.get("db_version")?.map(|v| v.value().to_owned()); + + match db_version { + Some(db_version) => { + let current_file_version = u64::from_str(&db_version)?; + if current_file_version.ne(&DATABASE_VERSION) { + // Database needs to be upgraded + todo!() + } + let _ = write_txn.open_table(KEYSET_COUNTER)?; + } + None => { + // Open all tables to init a new db + let _ = write_txn.open_table(MINTS_TABLE)?; + let _ = write_txn.open_multimap_table(MINT_KEYSETS_TABLE)?; + let _ = write_txn.open_table(MINT_QUOTES_TABLE)?; + let _ = write_txn.open_table(MELT_QUOTES_TABLE)?; + let _ = write_txn.open_table(MINT_KEYS_TABLE)?; + let _ = write_txn.open_multimap_table(PROOFS_TABLE)?; + let _ = write_txn.open_table(KEYSET_COUNTER)?; + table.insert("db_version", "0")?; + } + } + } + write_txn.commit()?; + + Ok(Self { + db: Arc::new(Mutex::new(db)), + }) + } +} + +#[async_trait] +impl WalletDatabase for RedbWalletDatabase { + type Err = cdk_database::Error; + + async fn add_mint( + &self, + mint_url: UncheckedUrl, + mint_info: Option, + ) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MINTS_TABLE) + .map_err(Into::::into)?; + table + .insert( + mint_url.to_string().as_str(), + serde_json::to_string(&mint_info) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_mint(&self, mint_url: UncheckedUrl) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(MINTS_TABLE) + .map_err(Into::::into)?; + + if let Some(mint_info) = table + .get(mint_url.to_string().as_str()) + .map_err(Into::::into)? + { + return Ok(serde_json::from_str(mint_info.value()).map_err(Into::::into)?); + } + + Ok(None) + } + + async fn get_mints(&self) -> Result>, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(MINTS_TABLE) + .map_err(Into::::into)?; + + let mints = table + .iter() + .map_err(Into::::into)? + .flatten() + .map(|(mint, mint_info)| { + ( + UncheckedUrl::from_str(mint.value()).unwrap(), + serde_json::from_str(mint_info.value()).ok(), + ) + }) + .collect(); + + Ok(mints) + } + + async fn add_mint_keysets( + &self, + mint_url: UncheckedUrl, + keysets: Vec, + ) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_multimap_table(MINT_KEYSETS_TABLE) + .map_err(Into::::into)?; + + for keyset in keysets { + table + .insert( + mint_url.to_string().as_str(), + serde_json::to_string(&keyset) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_mint_keysets( + &self, + mint_url: UncheckedUrl, + ) -> Result>, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_multimap_table(MINT_KEYSETS_TABLE) + .map_err(Into::::into)?; + + let keysets = table + .get(mint_url.to_string().as_str()) + .map_err(Into::::into)? + .flatten() + .flat_map(|k| serde_json::from_str(k.value())) + .collect(); + + Ok(keysets) + } + + async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MINT_QUOTES_TABLE) + .map_err(Into::::into)?; + table + .insert( + quote.id.as_str(), + serde_json::to_string("e) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_mint_quote(&self, quote_id: &str) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(MINT_QUOTES_TABLE) + .map_err(Into::::into)?; + + if let Some(mint_info) = table.get(quote_id).map_err(Into::::into)? { + return Ok(serde_json::from_str(mint_info.value()).map_err(Into::::into)?); + } + + Ok(None) + } + + async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MINT_QUOTES_TABLE) + .map_err(Into::::into)?; + table.remove(quote_id).map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn add_melt_quote(&self, quote: MeltQuote) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MELT_QUOTES_TABLE) + .map_err(Into::::into)?; + table + .insert( + quote.id.as_str(), + serde_json::to_string("e) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_melt_quote(&self, quote_id: &str) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(MELT_QUOTES_TABLE) + .map_err(Into::::into)?; + + if let Some(mint_info) = table.get(quote_id).map_err(Into::::into)? { + return Ok(serde_json::from_str(mint_info.value()).map_err(Into::::into)?); + } + + Ok(None) + } + + async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MELT_QUOTES_TABLE) + .map_err(Into::::into)?; + table.remove(quote_id).map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn add_keys(&self, keys: Keys) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MINT_KEYS_TABLE) + .map_err(Into::::into)?; + table + .insert( + Id::from(&keys).to_string().as_str(), + serde_json::to_string(&keys) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_keys(&self, id: &Id) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(MINT_KEYS_TABLE) + .map_err(Into::::into)?; + + if let Some(mint_info) = table + .get(id.to_string().as_str()) + .map_err(Into::::into)? + { + return Ok(serde_json::from_str(mint_info.value()).map_err(Into::::into)?); + } + + Ok(None) + } + + async fn remove_keys(&self, id: &Id) -> Result<(), Self::Err> { + let db = self.db.lock().await; + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_table(MINT_KEYS_TABLE) + .map_err(Into::::into)?; + + table + .remove(id.to_string().as_str()) + .map_err(Into::::into)?; + } + + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn add_proofs(&self, mint_url: UncheckedUrl, proofs: Proofs) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_multimap_table(PROOFS_TABLE) + .map_err(Into::::into)?; + + for proof in proofs { + table + .insert( + mint_url.to_string().as_str(), + serde_json::to_string(&proof) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_proofs(&self, mint_url: UncheckedUrl) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_multimap_table(PROOFS_TABLE) + .map_err(Into::::into)?; + + let proofs = table + .get(mint_url.to_string().as_str()) + .map_err(Into::::into)? + .flatten() + .flat_map(|k| serde_json::from_str(k.value())) + .collect(); + + Ok(proofs) + } + + async fn remove_proofs( + &self, + mint_url: UncheckedUrl, + proofs: &Proofs, + ) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_multimap_table(PROOFS_TABLE) + .map_err(Into::::into)?; + + for proof in proofs { + table + .remove( + mint_url.to_string().as_str(), + serde_json::to_string(&proof) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn add_pending_proofs( + &self, + mint_url: UncheckedUrl, + proofs: Proofs, + ) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_multimap_table(PENDING_PROOFS_TABLE) + .map_err(Into::::into)?; + + for proof in proofs { + table + .insert( + mint_url.to_string().as_str(), + serde_json::to_string(&proof) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_pending_proofs( + &self, + mint_url: UncheckedUrl, + ) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_multimap_table(PENDING_PROOFS_TABLE) + .map_err(Into::::into)?; + + let proofs = table + .get(mint_url.to_string().as_str()) + .map_err(Into::::into)? + .flatten() + .flat_map(|k| serde_json::from_str(k.value())) + .collect(); + + Ok(proofs) + } + + async fn remove_pending_proofs( + &self, + mint_url: UncheckedUrl, + proofs: &Proofs, + ) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let write_txn = db.begin_write().map_err(Into::::into)?; + + { + let mut table = write_txn + .open_multimap_table(PENDING_PROOFS_TABLE) + .map_err(Into::::into)?; + + for proof in proofs { + table + .remove( + mint_url.to_string().as_str(), + serde_json::to_string(&proof) + .map_err(Into::::into)? + .as_str(), + ) + .map_err(Into::::into)?; + } + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn increment_keyset_counter(&self, keyset_id: &Id, count: u64) -> Result<(), Self::Err> { + let db = self.db.lock().await; + + let current_counter; + { + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(KEYSET_COUNTER) + .map_err(Into::::into)?; + let counter = table + .get(keyset_id.to_string().as_str()) + .map_err(Into::::into)?; + + current_counter = match counter { + Some(c) => c.value(), + None => 0, + }; + } + + let write_txn = db.begin_write().map_err(Into::::into)?; + { + let mut table = write_txn + .open_table(KEYSET_COUNTER) + .map_err(Into::::into)?; + let new_counter = current_counter + count; + + table + .insert(keyset_id.to_string().as_str(), new_counter) + .map_err(Into::::into)?; + } + write_txn.commit().map_err(Into::::into)?; + + Ok(()) + } + + async fn get_keyset_counter(&self, keyset_id: &Id) -> Result, Self::Err> { + let db = self.db.lock().await; + let read_txn = db.begin_read().map_err(Into::::into)?; + let table = read_txn + .open_table(KEYSET_COUNTER) + .map_err(Into::::into)?; + + let counter = table + .get(keyset_id.to_string().as_str()) + .map_err(Into::::into)?; + + Ok(counter.map(|c| c.value())) + } +} diff --git a/crates/cdk/src/cdk_database/mod.rs b/crates/cdk/src/cdk_database/mod.rs new file mode 100644 index 00000000..2cc90855 --- /dev/null +++ b/crates/cdk/src/cdk_database/mod.rs @@ -0,0 +1,73 @@ +//! CDK Database + +use std::collections::HashMap; + +use async_trait::async_trait; +use thiserror::Error; + +use crate::nuts::{Id, KeySetInfo, Keys, MintInfo, Proofs}; +use crate::types::{MeltQuote, MintQuote}; +use crate::url::UncheckedUrl; + +pub mod wallet_memory; + +#[derive(Debug, Error)] +pub enum Error { + #[error(transparent)] + Database(Box), +} + +#[async_trait] +pub trait WalletDatabase { + type Err: Into; + + async fn add_mint( + &self, + mint_url: UncheckedUrl, + mint_info: Option, + ) -> Result<(), Self::Err>; + async fn get_mint(&self, mint_url: UncheckedUrl) -> Result, Self::Err>; + async fn get_mints(&self) -> Result>, Self::Err>; + + async fn add_mint_keysets( + &self, + mint_url: UncheckedUrl, + keysets: Vec, + ) -> Result<(), Self::Err>; + async fn get_mint_keysets( + &self, + mint_url: UncheckedUrl, + ) -> Result>, Self::Err>; + async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err>; + async fn get_mint_quote(&self, quote_id: &str) -> Result, Self::Err>; + async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err>; + + async fn add_melt_quote(&self, quote: MeltQuote) -> Result<(), Self::Err>; + async fn get_melt_quote(&self, quote_id: &str) -> Result, Self::Err>; + async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Self::Err>; + + async fn add_keys(&self, keys: Keys) -> Result<(), Self::Err>; + async fn get_keys(&self, id: &Id) -> Result, Self::Err>; + async fn remove_keys(&self, id: &Id) -> Result<(), Self::Err>; + + async fn add_proofs(&self, mint_url: UncheckedUrl, proof: Proofs) -> Result<(), Self::Err>; + async fn get_proofs(&self, mint_url: UncheckedUrl) -> Result, Self::Err>; + async fn remove_proofs(&self, mint_url: UncheckedUrl, proofs: &Proofs) + -> Result<(), Self::Err>; + + async fn add_pending_proofs( + &self, + mint_url: UncheckedUrl, + proof: Proofs, + ) -> Result<(), Self::Err>; + async fn get_pending_proofs(&self, mint_url: UncheckedUrl) + -> Result, Self::Err>; + async fn remove_pending_proofs( + &self, + mint_url: UncheckedUrl, + proofs: &Proofs, + ) -> Result<(), Self::Err>; + + async fn increment_keyset_counter(&self, keyset_id: &Id, count: u64) -> Result<(), Self::Err>; + async fn get_keyset_counter(&self, keyset_id: &Id) -> Result, Self::Err>; +} diff --git a/crates/cdk/src/wallet/localstore/memory.rs b/crates/cdk/src/cdk_database/wallet_memory.rs similarity index 95% rename from crates/cdk/src/wallet/localstore/memory.rs rename to crates/cdk/src/cdk_database/wallet_memory.rs index 93e48ea6..011c70ea 100644 --- a/crates/cdk/src/wallet/localstore/memory.rs +++ b/crates/cdk/src/cdk_database/wallet_memory.rs @@ -1,16 +1,19 @@ +//! Memory Database + use std::collections::{HashMap, HashSet}; use std::sync::Arc; use async_trait::async_trait; use tokio::sync::Mutex; -use super::{Error, LocalStore}; +use super::WalletDatabase; +use crate::cdk_database::Error; use crate::nuts::{Id, KeySetInfo, Keys, MintInfo, Proof, Proofs}; use crate::types::{MeltQuote, MintQuote}; use crate::url::UncheckedUrl; #[derive(Default, Debug, Clone)] -pub struct MemoryLocalStore { +pub struct WalletMemoryDatabase { mints: Arc>>>, mint_keysets: Arc>>>, mint_quotes: Arc>>, @@ -18,11 +21,10 @@ pub struct MemoryLocalStore { mint_keys: Arc>>, proofs: Arc>>>, pending_proofs: Arc>>>, - #[cfg(feature = "nut13")] keyset_counter: Arc>>, } -impl MemoryLocalStore { +impl WalletMemoryDatabase { pub fn new( mint_quotes: Vec, melt_quotes: Vec, @@ -43,24 +45,25 @@ impl MemoryLocalStore { )), proofs: Arc::new(Mutex::new(HashMap::new())), pending_proofs: Arc::new(Mutex::new(HashMap::new())), - #[cfg(feature = "nut13")] keyset_counter: Arc::new(Mutex::new(keyset_counter)), } } } #[async_trait] -impl LocalStore for MemoryLocalStore { +impl WalletDatabase for WalletMemoryDatabase { + type Err = Error; + async fn add_mint( &self, mint_url: UncheckedUrl, mint_info: Option, - ) -> Result<(), Error> { + ) -> Result<(), Self::Err> { self.mints.lock().await.insert(mint_url, mint_info); Ok(()) } - async fn get_mint(&self, mint_url: UncheckedUrl) -> Result, Error> { + async fn get_mint(&self, mint_url: UncheckedUrl) -> Result, Self::Err> { Ok(self.mints.lock().await.get(&mint_url).cloned().flatten()) } @@ -211,7 +214,6 @@ impl LocalStore for MemoryLocalStore { Ok(()) } - #[cfg(feature = "nut13")] async fn increment_keyset_counter(&self, keyset_id: &Id, count: u64) -> Result<(), Error> { let keyset_counter = self.keyset_counter.lock().await; let current_counter = keyset_counter.get(keyset_id).unwrap_or(&0); @@ -222,7 +224,6 @@ impl LocalStore for MemoryLocalStore { Ok(()) } - #[cfg(feature = "nut13")] async fn get_keyset_counter(&self, id: &Id) -> Result, Error> { Ok(self.keyset_counter.lock().await.get(id).cloned()) } diff --git a/crates/cdk/src/lib.rs b/crates/cdk/src/lib.rs index 043c5c54..aa62108a 100644 --- a/crates/cdk/src/lib.rs +++ b/crates/cdk/src/lib.rs @@ -7,6 +7,7 @@ pub use bitcoin::secp256k1; pub use lightning_invoice::{self, Bolt11Invoice}; pub mod amount; +pub mod cdk_database; #[cfg(feature = "wallet")] pub mod client; pub mod dhke; diff --git a/crates/cdk/src/wallet/localstore/redb_store.rs b/crates/cdk/src/wallet/localstore/redb_store.rs deleted file mode 100644 index d1ea2780..00000000 --- a/crates/cdk/src/wallet/localstore/redb_store.rs +++ /dev/null @@ -1,452 +0,0 @@ -use std::collections::HashMap; -use std::str::FromStr; -use std::sync::Arc; - -use async_trait::async_trait; -use redb::{Database, MultimapTableDefinition, ReadableTable, TableDefinition}; -use tokio::sync::Mutex; - -use super::{Error, LocalStore}; -use crate::nuts::{Id, KeySetInfo, Keys, MintInfo, Proofs}; -use crate::types::{MeltQuote, MintQuote}; -use crate::url::UncheckedUrl; - -const MINTS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mints_table"); -const MINT_KEYSETS_TABLE: MultimapTableDefinition<&str, &str> = - MultimapTableDefinition::new("mint_keysets"); -const MINT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_quotes"); -const MELT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("melt_quotes"); -const MINT_KEYS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_keys"); -const PROOFS_TABLE: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("proofs"); -const PENDING_PROOFS_TABLE: MultimapTableDefinition<&str, &str> = - MultimapTableDefinition::new("pending_proofs"); -const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config"); -#[cfg(feature = "nut13")] -const KEYSET_COUNTER: TableDefinition<&str, u64> = TableDefinition::new("keyset_counter"); - -const DATABASE_VERSION: u64 = 0; - -#[derive(Debug, Clone)] -pub struct RedbLocalStore { - db: Arc>, -} - -impl RedbLocalStore { - pub fn new(path: &str) -> Result { - let db = Database::create(path)?; - - let write_txn = db.begin_write()?; - - // Check database version - { - let _ = write_txn.open_table(CONFIG_TABLE)?; - let mut table = write_txn.open_table(CONFIG_TABLE)?; - - let db_version = table.get("db_version")?.map(|v| v.value().to_owned()); - - match db_version { - Some(db_version) => { - let current_file_version = u64::from_str(&db_version)?; - if current_file_version.ne(&DATABASE_VERSION) { - // Database needs to be upgraded - todo!() - } - #[cfg(feature = "nut13")] - let _ = write_txn.open_table(KEYSET_COUNTER)?; - } - None => { - // Open all tables to init a new db - let _ = write_txn.open_table(MINTS_TABLE)?; - let _ = write_txn.open_multimap_table(MINT_KEYSETS_TABLE)?; - let _ = write_txn.open_table(MINT_QUOTES_TABLE)?; - let _ = write_txn.open_table(MELT_QUOTES_TABLE)?; - let _ = write_txn.open_table(MINT_KEYS_TABLE)?; - let _ = write_txn.open_multimap_table(PROOFS_TABLE)?; - #[cfg(feature = "nut13")] - let _ = write_txn.open_table(KEYSET_COUNTER)?; - table.insert("db_version", "0")?; - } - } - } - write_txn.commit()?; - - Ok(Self { - db: Arc::new(Mutex::new(db)), - }) - } -} - -#[async_trait] -impl LocalStore for RedbLocalStore { - async fn add_mint( - &self, - mint_url: UncheckedUrl, - mint_info: Option, - ) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MINTS_TABLE)?; - table.insert( - mint_url.to_string().as_str(), - serde_json::to_string(&mint_info)?.as_str(), - )?; - } - write_txn.commit()?; - - Ok(()) - } - - async fn get_mint(&self, mint_url: UncheckedUrl) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(MINTS_TABLE)?; - - if let Some(mint_info) = table.get(mint_url.to_string().as_str())? { - return Ok(serde_json::from_str(mint_info.value())?); - } - - Ok(None) - } - - async fn get_mints(&self) -> Result>, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(MINTS_TABLE)?; - - let mints = table - .iter()? - .flatten() - .map(|(mint, mint_info)| { - ( - UncheckedUrl::from_str(mint.value()).unwrap(), - serde_json::from_str(mint_info.value()).ok(), - ) - }) - .collect(); - - Ok(mints) - } - - async fn add_mint_keysets( - &self, - mint_url: UncheckedUrl, - keysets: Vec, - ) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_multimap_table(MINT_KEYSETS_TABLE)?; - - for keyset in keysets { - table.insert( - mint_url.to_string().as_str(), - serde_json::to_string(&keyset)?.as_str(), - )?; - } - } - write_txn.commit()?; - - Ok(()) - } - - async fn get_mint_keysets( - &self, - mint_url: UncheckedUrl, - ) -> Result>, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_multimap_table(MINT_KEYSETS_TABLE)?; - - let keysets = table - .get(mint_url.to_string().as_str())? - .flatten() - .flat_map(|k| serde_json::from_str(k.value())) - .collect(); - - Ok(keysets) - } - - async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MINT_QUOTES_TABLE)?; - table.insert(quote.id.as_str(), serde_json::to_string("e)?.as_str())?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn get_mint_quote(&self, quote_id: &str) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(MINT_QUOTES_TABLE)?; - - if let Some(mint_info) = table.get(quote_id)? { - return Ok(serde_json::from_str(mint_info.value())?); - } - - Ok(None) - } - - async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MINT_QUOTES_TABLE)?; - table.remove(quote_id)?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn add_melt_quote(&self, quote: MeltQuote) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MELT_QUOTES_TABLE)?; - table.insert(quote.id.as_str(), serde_json::to_string("e)?.as_str())?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn get_melt_quote(&self, quote_id: &str) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(MELT_QUOTES_TABLE)?; - - if let Some(mint_info) = table.get(quote_id)? { - return Ok(serde_json::from_str(mint_info.value())?); - } - - Ok(None) - } - - async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MELT_QUOTES_TABLE)?; - table.remove(quote_id)?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn add_keys(&self, keys: Keys) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MINT_KEYS_TABLE)?; - table.insert( - Id::from(&keys).to_string().as_str(), - serde_json::to_string(&keys)?.as_str(), - )?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn get_keys(&self, id: &Id) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(MINT_KEYS_TABLE)?; - - if let Some(mint_info) = table.get(id.to_string().as_str())? { - return Ok(serde_json::from_str(mint_info.value())?); - } - - Ok(None) - } - - async fn remove_keys(&self, id: &Id) -> Result<(), Error> { - let db = self.db.lock().await; - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_table(MINT_KEYS_TABLE)?; - - table.remove(id.to_string().as_str())?; - } - - write_txn.commit()?; - - Ok(()) - } - - async fn add_proofs(&self, mint_url: UncheckedUrl, proofs: Proofs) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_multimap_table(PROOFS_TABLE)?; - - for proof in proofs { - table.insert( - mint_url.to_string().as_str(), - serde_json::to_string(&proof)?.as_str(), - )?; - } - } - write_txn.commit()?; - - Ok(()) - } - - async fn get_proofs(&self, mint_url: UncheckedUrl) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_multimap_table(PROOFS_TABLE)?; - - let proofs = table - .get(mint_url.to_string().as_str())? - .flatten() - .flat_map(|k| serde_json::from_str(k.value())) - .collect(); - - Ok(proofs) - } - - async fn remove_proofs(&self, mint_url: UncheckedUrl, proofs: &Proofs) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_multimap_table(PROOFS_TABLE)?; - - for proof in proofs { - table.remove( - mint_url.to_string().as_str(), - serde_json::to_string(&proof)?.as_str(), - )?; - } - } - write_txn.commit()?; - - Ok(()) - } - - async fn add_pending_proofs( - &self, - mint_url: UncheckedUrl, - proofs: Proofs, - ) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_multimap_table(PENDING_PROOFS_TABLE)?; - - for proof in proofs { - table.insert( - mint_url.to_string().as_str(), - serde_json::to_string(&proof)?.as_str(), - )?; - } - } - write_txn.commit()?; - - Ok(()) - } - - async fn get_pending_proofs(&self, mint_url: UncheckedUrl) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_multimap_table(PENDING_PROOFS_TABLE)?; - - let proofs = table - .get(mint_url.to_string().as_str())? - .flatten() - .flat_map(|k| serde_json::from_str(k.value())) - .collect(); - - Ok(proofs) - } - - async fn remove_pending_proofs( - &self, - mint_url: UncheckedUrl, - proofs: &Proofs, - ) -> Result<(), Error> { - let db = self.db.lock().await; - - let write_txn = db.begin_write()?; - - { - let mut table = write_txn.open_multimap_table(PENDING_PROOFS_TABLE)?; - - for proof in proofs { - table.remove( - mint_url.to_string().as_str(), - serde_json::to_string(&proof)?.as_str(), - )?; - } - } - write_txn.commit()?; - - Ok(()) - } - - #[cfg(feature = "nut13")] - async fn increment_keyset_counter(&self, keyset_id: &Id, count: u64) -> Result<(), Error> { - let db = self.db.lock().await; - - let current_counter; - { - let read_txn = db.begin_read()?; - let table = read_txn.open_table(KEYSET_COUNTER)?; - let counter = table.get(keyset_id.to_string().as_str())?; - - current_counter = match counter { - Some(c) => c.value(), - None => 0, - }; - } - - let write_txn = db.begin_write()?; - { - let mut table = write_txn.open_table(KEYSET_COUNTER)?; - let new_counter = current_counter + count; - - table.insert(keyset_id.to_string().as_str(), new_counter)?; - } - write_txn.commit()?; - - Ok(()) - } - - #[cfg(feature = "nut13")] - async fn get_keyset_counter(&self, keyset_id: &Id) -> Result, Error> { - let db = self.db.lock().await; - let read_txn = db.begin_read()?; - let table = read_txn.open_table(KEYSET_COUNTER)?; - - let counter = table.get(keyset_id.to_string().as_str())?; - - Ok(counter.map(|c| c.value())) - } -} diff --git a/crates/cdk/src/wallet/mod.rs b/crates/cdk/src/wallet/mod.rs index 297da318..1485f607 100644 --- a/crates/cdk/src/wallet/mod.rs +++ b/crates/cdk/src/wallet/mod.rs @@ -6,10 +6,11 @@ use std::str::FromStr; use std::sync::Arc; use bip39::Mnemonic; -use localstore::LocalStore; use thiserror::Error; use tracing::{debug, warn}; +use crate::cdk_database::wallet_memory::WalletMemoryDatabase; +use crate::cdk_database::{self, WalletDatabase}; use crate::client::HttpClient; use crate::dhke::{construct_proofs, hash_to_curve, unblind_message}; use crate::nuts::{ @@ -22,8 +23,6 @@ use crate::url::UncheckedUrl; use crate::util::unix_time; use crate::{Amount, Bolt11Invoice}; -pub mod localstore; - #[derive(Debug, Error)] pub enum Error { /// Insufficient Funds @@ -36,8 +35,6 @@ pub enum Error { #[error("No active keyset")] NoActiveKeyset, #[error(transparent)] - LocalStore(#[from] localstore::Error), - #[error(transparent)] Cashu(#[from] crate::error::Error), #[error("Could not verify Dleq")] CouldNotVerifyDleq, @@ -61,21 +58,40 @@ pub enum Error { /// NUT11 Error #[error(transparent)] NUT11(#[from] crate::nuts::nut11::Error), + /// Database Error + #[error(transparent)] + Database(#[from] crate::cdk_database::Error), #[error("`{0}`")] Custom(String), } +impl From for cdk_database::Error { + fn from(e: Error) -> Self { + Self::Database(Box::new(e)) + } +} + #[derive(Clone)] pub struct Wallet { pub client: HttpClient, - pub localstore: Arc, + pub localstore: Arc + Send + Sync>, mnemonic: Option, } +impl Default for Wallet { + fn default() -> Self { + Self { + localstore: Arc::new(WalletMemoryDatabase::default()), + client: HttpClient::default(), + mnemonic: None, + } + } +} + impl Wallet { pub async fn new( client: HttpClient, - localstore: Arc, + localstore: Arc + Send + Sync>, mnemonic: Option, ) -> Self { Self {