refactor: cdk_database

This commit is contained in:
thesimplekid
2024-04-14 17:42:36 +01:00
parent 61c80606f6
commit 06373beff4
9 changed files with 722 additions and 469 deletions

View File

@@ -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]

View File

@@ -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"

View File

@@ -0,0 +1,3 @@
pub mod wallet_redb;
pub use wallet_redb::RedbWalletDatabase;

View File

@@ -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<Error> 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<Mutex<Database>>,
}
impl RedbWalletDatabase {
pub fn new(path: &str) -> Result<Self, Error> {
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<MintInfo>,
) -> Result<(), Self::Err> {
let db = self.db.lock().await;
let write_txn = db.begin_write().map_err(Into::<Error>::into)?;
{
let mut table = write_txn
.open_table(MINTS_TABLE)
.map_err(Into::<Error>::into)?;
table
.insert(
mint_url.to_string().as_str(),
serde_json::to_string(&mint_info)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_mint(&self, mint_url: UncheckedUrl) -> Result<Option<MintInfo>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(MINTS_TABLE)
.map_err(Into::<Error>::into)?;
if let Some(mint_info) = table
.get(mint_url.to_string().as_str())
.map_err(Into::<Error>::into)?
{
return Ok(serde_json::from_str(mint_info.value()).map_err(Into::<Error>::into)?);
}
Ok(None)
}
async fn get_mints(&self) -> Result<HashMap<UncheckedUrl, Option<MintInfo>>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(MINTS_TABLE)
.map_err(Into::<Error>::into)?;
let mints = table
.iter()
.map_err(Into::<Error>::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<KeySetInfo>,
) -> Result<(), Self::Err> {
let db = self.db.lock().await;
let write_txn = db.begin_write().map_err(Into::<Error>::into)?;
{
let mut table = write_txn
.open_multimap_table(MINT_KEYSETS_TABLE)
.map_err(Into::<Error>::into)?;
for keyset in keysets {
table
.insert(
mint_url.to_string().as_str(),
serde_json::to_string(&keyset)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_mint_keysets(
&self,
mint_url: UncheckedUrl,
) -> Result<Option<Vec<KeySetInfo>>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_multimap_table(MINT_KEYSETS_TABLE)
.map_err(Into::<Error>::into)?;
let keysets = table
.get(mint_url.to_string().as_str())
.map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MINT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
table
.insert(
quote.id.as_str(),
serde_json::to_string(&quote)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(MINT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
if let Some(mint_info) = table.get(quote_id).map_err(Into::<Error>::into)? {
return Ok(serde_json::from_str(mint_info.value()).map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MINT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
table.remove(quote_id).map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MELT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
table
.insert(
quote.id.as_str(),
serde_json::to_string(&quote)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<MeltQuote>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(MELT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
if let Some(mint_info) = table.get(quote_id).map_err(Into::<Error>::into)? {
return Ok(serde_json::from_str(mint_info.value()).map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MELT_QUOTES_TABLE)
.map_err(Into::<Error>::into)?;
table.remove(quote_id).map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MINT_KEYS_TABLE)
.map_err(Into::<Error>::into)?;
table
.insert(
Id::from(&keys).to_string().as_str(),
serde_json::to_string(&keys)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_keys(&self, id: &Id) -> Result<Option<Keys>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(MINT_KEYS_TABLE)
.map_err(Into::<Error>::into)?;
if let Some(mint_info) = table
.get(id.to_string().as_str())
.map_err(Into::<Error>::into)?
{
return Ok(serde_json::from_str(mint_info.value()).map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_table(MINT_KEYS_TABLE)
.map_err(Into::<Error>::into)?;
table
.remove(id.to_string().as_str())
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_multimap_table(PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
for proof in proofs {
table
.insert(
mint_url.to_string().as_str(),
serde_json::to_string(&proof)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_proofs(&self, mint_url: UncheckedUrl) -> Result<Option<Proofs>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_multimap_table(PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
let proofs = table
.get(mint_url.to_string().as_str())
.map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_multimap_table(PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
for proof in proofs {
table
.remove(
mint_url.to_string().as_str(),
serde_json::to_string(&proof)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
}
write_txn.commit().map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_multimap_table(PENDING_PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
for proof in proofs {
table
.insert(
mint_url.to_string().as_str(),
serde_json::to_string(&proof)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_pending_proofs(
&self,
mint_url: UncheckedUrl,
) -> Result<Option<Proofs>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_multimap_table(PENDING_PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
let proofs = table
.get(mint_url.to_string().as_str())
.map_err(Into::<Error>::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::<Error>::into)?;
{
let mut table = write_txn
.open_multimap_table(PENDING_PROOFS_TABLE)
.map_err(Into::<Error>::into)?;
for proof in proofs {
table
.remove(
mint_url.to_string().as_str(),
serde_json::to_string(&proof)
.map_err(Into::<Error>::into)?
.as_str(),
)
.map_err(Into::<Error>::into)?;
}
}
write_txn.commit().map_err(Into::<Error>::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::<Error>::into)?;
let table = read_txn
.open_table(KEYSET_COUNTER)
.map_err(Into::<Error>::into)?;
let counter = table
.get(keyset_id.to_string().as_str())
.map_err(Into::<Error>::into)?;
current_counter = match counter {
Some(c) => c.value(),
None => 0,
};
}
let write_txn = db.begin_write().map_err(Into::<Error>::into)?;
{
let mut table = write_txn
.open_table(KEYSET_COUNTER)
.map_err(Into::<Error>::into)?;
let new_counter = current_counter + count;
table
.insert(keyset_id.to_string().as_str(), new_counter)
.map_err(Into::<Error>::into)?;
}
write_txn.commit().map_err(Into::<Error>::into)?;
Ok(())
}
async fn get_keyset_counter(&self, keyset_id: &Id) -> Result<Option<u64>, Self::Err> {
let db = self.db.lock().await;
let read_txn = db.begin_read().map_err(Into::<Error>::into)?;
let table = read_txn
.open_table(KEYSET_COUNTER)
.map_err(Into::<Error>::into)?;
let counter = table
.get(keyset_id.to_string().as_str())
.map_err(Into::<Error>::into)?;
Ok(counter.map(|c| c.value()))
}
}

View File

@@ -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<dyn std::error::Error + Send + Sync>),
}
#[async_trait]
pub trait WalletDatabase {
type Err: Into<Error>;
async fn add_mint(
&self,
mint_url: UncheckedUrl,
mint_info: Option<MintInfo>,
) -> Result<(), Self::Err>;
async fn get_mint(&self, mint_url: UncheckedUrl) -> Result<Option<MintInfo>, Self::Err>;
async fn get_mints(&self) -> Result<HashMap<UncheckedUrl, Option<MintInfo>>, Self::Err>;
async fn add_mint_keysets(
&self,
mint_url: UncheckedUrl,
keysets: Vec<KeySetInfo>,
) -> Result<(), Self::Err>;
async fn get_mint_keysets(
&self,
mint_url: UncheckedUrl,
) -> Result<Option<Vec<KeySetInfo>>, Self::Err>;
async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err>;
async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, 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<Option<MeltQuote>, 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<Option<Keys>, 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<Option<Proofs>, 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<Option<Proofs>, 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<Option<u64>, Self::Err>;
}

View File

@@ -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<Mutex<HashMap<UncheckedUrl, Option<MintInfo>>>>,
mint_keysets: Arc<Mutex<HashMap<UncheckedUrl, HashSet<KeySetInfo>>>>,
mint_quotes: Arc<Mutex<HashMap<String, MintQuote>>>,
@@ -18,11 +21,10 @@ pub struct MemoryLocalStore {
mint_keys: Arc<Mutex<HashMap<Id, Keys>>>,
proofs: Arc<Mutex<HashMap<UncheckedUrl, HashSet<Proof>>>>,
pending_proofs: Arc<Mutex<HashMap<UncheckedUrl, HashSet<Proof>>>>,
#[cfg(feature = "nut13")]
keyset_counter: Arc<Mutex<HashMap<Id, u64>>>,
}
impl MemoryLocalStore {
impl WalletMemoryDatabase {
pub fn new(
mint_quotes: Vec<MintQuote>,
melt_quotes: Vec<MeltQuote>,
@@ -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<MintInfo>,
) -> Result<(), Error> {
) -> Result<(), Self::Err> {
self.mints.lock().await.insert(mint_url, mint_info);
Ok(())
}
async fn get_mint(&self, mint_url: UncheckedUrl) -> Result<Option<MintInfo>, Error> {
async fn get_mint(&self, mint_url: UncheckedUrl) -> Result<Option<MintInfo>, 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<Option<u64>, Error> {
Ok(self.keyset_counter.lock().await.get(id).cloned())
}

View File

@@ -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;

View File

@@ -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<Mutex<Database>>,
}
impl RedbLocalStore {
pub fn new(path: &str) -> Result<Self, Error> {
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<MintInfo>,
) -> 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<Option<MintInfo>, 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<HashMap<UncheckedUrl, Option<MintInfo>>, 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<KeySetInfo>,
) -> 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<Option<Vec<KeySetInfo>>, 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(&quote)?.as_str())?;
}
write_txn.commit()?;
Ok(())
}
async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, 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(&quote)?.as_str())?;
}
write_txn.commit()?;
Ok(())
}
async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<MeltQuote>, 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<Option<Keys>, 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<Option<Proofs>, 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<Option<Proofs>, 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<Option<u64>, 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()))
}
}

View File

@@ -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<Error> 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<dyn LocalStore + Send + Sync>,
pub localstore: Arc<dyn WalletDatabase<Err = cdk_database::Error> + Send + Sync>,
mnemonic: Option<Mnemonic>,
}
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<dyn LocalStore + Send + Sync>,
localstore: Arc<dyn WalletDatabase<Err = cdk_database::Error> + Send + Sync>,
mnemonic: Option<Mnemonic>,
) -> Self {
Self {