123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673 |
- //! SQLite Storage for CDK
- use std::cmp::Ordering;
- use std::collections::HashMap;
- use std::path::Path;
- use std::str::FromStr;
- use std::sync::Arc;
- use async_trait::async_trait;
- use cdk::cdk_database::MintDatabase;
- use cdk::dhke::hash_to_curve;
- use cdk::mint::{MintKeySetInfo, MintQuote};
- use cdk::nuts::{
- BlindSignature, CurrencyUnit, Id, MeltQuoteState, MintQuoteState, Proof, Proofs, PublicKey,
- State,
- };
- use cdk::{cdk_database, mint};
- use migrations::migrate_01_to_02;
- use redb::{Database, ReadableTable, TableDefinition};
- use tokio::sync::Mutex;
- use super::error::Error;
- use crate::migrations::migrate_00_to_01;
- use crate::mint::migrations::migrate_02_to_03;
- mod migrations;
- const ACTIVE_KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("active_keysets");
- const KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("keysets");
- const MINT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_quotes");
- const MELT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("melt_quotes");
- const PROOFS_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs");
- const PROOFS_STATE_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs_state");
- const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config");
- // Key is hex blinded_message B_ value is blinded_signature
- const BLINDED_SIGNATURES: TableDefinition<[u8; 33], &str> =
- TableDefinition::new("blinded_signatures");
- const DATABASE_VERSION: u32 = 3;
- /// Mint Redbdatabase
- #[derive(Debug, Clone)]
- pub struct MintRedbDatabase {
- db: Arc<Mutex<Database>>,
- }
- impl MintRedbDatabase {
- /// Create new [`MintRedbDatabase`]
- pub fn new(path: &Path) -> Result<Self, Error> {
- {
- // Check database version
- let db = Arc::new(Database::create(path)?);
- // Check database version
- let read_txn = db.begin_read()?;
- let table = read_txn.open_table(CONFIG_TABLE);
- let db_version = match table {
- Ok(table) => table.get("db_version")?.map(|v| v.value().to_owned()),
- Err(_) => None,
- };
- match db_version {
- Some(db_version) => {
- let mut current_file_version = u32::from_str(&db_version)?;
- match current_file_version.cmp(&DATABASE_VERSION) {
- Ordering::Less => {
- tracing::info!(
- "Database needs to be upgraded at {} current is {}",
- current_file_version,
- DATABASE_VERSION
- );
- if current_file_version == 0 {
- current_file_version = migrate_00_to_01(Arc::clone(&db))?;
- }
- if current_file_version == 1 {
- current_file_version = migrate_01_to_02(Arc::clone(&db))?;
- }
- if current_file_version == 2 {
- current_file_version = migrate_02_to_03(Arc::clone(&db))?;
- }
- if current_file_version != DATABASE_VERSION {
- tracing::warn!(
- "Database upgrade did not complete at {} current is {}",
- current_file_version,
- DATABASE_VERSION
- );
- return Err(Error::UnknownDatabaseVersion);
- }
- let write_txn = db.begin_write()?;
- {
- let mut table = write_txn.open_table(CONFIG_TABLE)?;
- table
- .insert("db_version", DATABASE_VERSION.to_string().as_str())?;
- }
- write_txn.commit()?;
- }
- Ordering::Equal => {
- tracing::info!("Database is at current version {}", DATABASE_VERSION);
- }
- Ordering::Greater => {
- tracing::warn!(
- "Database upgrade did not complete at {} current is {}",
- current_file_version,
- DATABASE_VERSION
- );
- return Err(Error::UnknownDatabaseVersion);
- }
- }
- }
- None => {
- let write_txn = db.begin_write()?;
- {
- let mut table = write_txn.open_table(CONFIG_TABLE)?;
- // Open all tables to init a new db
- let _ = write_txn.open_table(ACTIVE_KEYSETS_TABLE)?;
- let _ = write_txn.open_table(KEYSETS_TABLE)?;
- let _ = write_txn.open_table(MINT_QUOTES_TABLE)?;
- let _ = write_txn.open_table(MELT_QUOTES_TABLE)?;
- let _ = write_txn.open_table(PROOFS_TABLE)?;
- let _ = write_txn.open_table(PROOFS_STATE_TABLE)?;
- let _ = write_txn.open_table(BLINDED_SIGNATURES)?;
- table.insert("db_version", DATABASE_VERSION.to_string().as_str())?;
- }
- write_txn.commit()?;
- }
- }
- drop(db);
- }
- let db = Database::create(path)?;
- Ok(Self {
- db: Arc::new(Mutex::new(db)),
- })
- }
- }
- #[async_trait]
- impl MintDatabase for MintRedbDatabase {
- type Err = cdk_database::Error;
- async fn set_active_keyset(&self, unit: CurrencyUnit, id: Id) -> Result<(), Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(ACTIVE_KEYSETS_TABLE)
- .map_err(Error::from)?;
- table
- .insert(unit.to_string().as_str(), id.to_string().as_str())
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn get_active_keyset_id(&self, unit: &CurrencyUnit) -> Result<Option<Id>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(ACTIVE_KEYSETS_TABLE)
- .map_err(Error::from)?;
- if let Some(id) = table.get(unit.to_string().as_str()).map_err(Error::from)? {
- return Ok(Some(Id::from_str(id.value()).map_err(Error::from)?));
- }
- Ok(None)
- }
- async fn get_active_keysets(&self) -> Result<HashMap<CurrencyUnit, Id>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(ACTIVE_KEYSETS_TABLE)
- .map_err(Error::from)?;
- let mut active_keysets = HashMap::new();
- for (unit, id) in (table.iter().map_err(Error::from)?).flatten() {
- let unit = CurrencyUnit::from_str(unit.value())?;
- let id = Id::from_str(id.value()).map_err(Error::from)?;
- active_keysets.insert(unit, id);
- }
- Ok(active_keysets)
- }
- async fn add_keyset_info(&self, keyset: MintKeySetInfo) -> Result<(), Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
- table
- .insert(
- keyset.id.to_string().as_str(),
- serde_json::to_string(&keyset)
- .map_err(Error::from)?
- .as_str(),
- )
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn get_keyset_info(&self, keyset_id: &Id) -> Result<Option<MintKeySetInfo>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
- match table
- .get(keyset_id.to_string().as_str())
- .map_err(Error::from)?
- {
- Some(keyset) => Ok(serde_json::from_str(keyset.value()).map_err(Error::from)?),
- None => Ok(None),
- }
- }
- async fn get_keyset_infos(&self) -> Result<Vec<MintKeySetInfo>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
- let mut keysets = Vec::new();
- for (_id, keyset) in (table.iter().map_err(Error::from)?).flatten() {
- let keyset = serde_json::from_str(keyset.value()).map_err(Error::from)?;
- keysets.push(keyset)
- }
- 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(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table
- .insert(
- quote.id.as_str(),
- serde_json::to_string("e).map_err(Error::from)?.as_str(),
- )
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- 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(Error::from)?;
- let table = read_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- match table.get(quote_id).map_err(Error::from)? {
- Some(quote) => Ok(serde_json::from_str(quote.value()).map_err(Error::from)?),
- None => Ok(None),
- }
- }
- async fn update_mint_quote_state(
- &self,
- quote_id: &str,
- state: MintQuoteState,
- ) -> Result<MintQuoteState, Self::Err> {
- let db = self.db.lock().await;
- let mut mint_quote: MintQuote;
- {
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- let quote_guard = table
- .get(quote_id)
- .map_err(Error::from)?
- .ok_or(Error::UnknownMintInfo)?;
- let quote = quote_guard.value();
- mint_quote = serde_json::from_str(quote).map_err(Error::from)?;
- }
- let current_state = mint_quote.state;
- mint_quote.state = state;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table
- .insert(
- quote_id,
- serde_json::to_string(&mint_quote)
- .map_err(Error::from)?
- .as_str(),
- )
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(current_state)
- }
- async fn get_mint_quote_by_request(
- &self,
- request: &str,
- ) -> Result<Option<MintQuote>, Self::Err> {
- let quotes = self.get_mint_quotes().await?;
- let quote = quotes
- .into_iter()
- .filter(|q| q.request.eq(request))
- .collect::<Vec<MintQuote>>()
- .first()
- .cloned();
- Ok(quote)
- }
- async fn get_mint_quote_by_request_lookup_id(
- &self,
- request_lookup_id: &str,
- ) -> Result<Option<MintQuote>, Self::Err> {
- let quotes = self.get_mint_quotes().await?;
- let quote = quotes
- .into_iter()
- .filter(|q| q.request_lookup_id.eq(request_lookup_id))
- .collect::<Vec<MintQuote>>()
- .first()
- .cloned();
- Ok(quote)
- }
- async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- let mut quotes = Vec::new();
- for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
- let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
- quotes.push(quote)
- }
- Ok(quotes)
- }
- 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(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MINT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table.remove(quote_id).map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn add_melt_quote(&self, quote: mint::MeltQuote) -> Result<(), Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table
- .insert(
- quote.id.as_str(),
- serde_json::to_string("e).map_err(Error::from)?.as_str(),
- )
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<mint::MeltQuote>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- let quote = table.get(quote_id).map_err(Error::from)?;
- Ok(quote.map(|q| serde_json::from_str(q.value()).unwrap()))
- }
- async fn update_melt_quote_state(
- &self,
- quote_id: &str,
- state: MeltQuoteState,
- ) -> Result<MeltQuoteState, Self::Err> {
- let db = self.db.lock().await;
- let mut melt_quote: mint::MeltQuote;
- {
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- let quote_guard = table
- .get(quote_id)
- .map_err(Error::from)?
- .ok_or(Error::UnknownMintInfo)?;
- let quote = quote_guard.value();
- melt_quote = serde_json::from_str(quote).map_err(Error::from)?;
- }
- let current_state = melt_quote.state;
- melt_quote.state = state;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table
- .insert(
- quote_id,
- serde_json::to_string(&melt_quote)
- .map_err(Error::from)?
- .as_str(),
- )
- .map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(current_state)
- }
- async fn get_melt_quotes(&self) -> Result<Vec<mint::MeltQuote>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- let mut quotes = Vec::new();
- for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
- let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
- quotes.push(quote)
- }
- Ok(quotes)
- }
- 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(Error::from)?;
- {
- let mut table = write_txn
- .open_table(MELT_QUOTES_TABLE)
- .map_err(Error::from)?;
- table.remove(quote_id).map_err(Error::from)?;
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn add_proofs(&self, proofs: Proofs) -> Result<(), Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
- for proof in proofs {
- let y: PublicKey = hash_to_curve(&proof.secret.to_bytes()).map_err(Error::from)?;
- if table.get(y.to_bytes()).map_err(Error::from)?.is_none() {
- table
- .insert(
- y.to_bytes(),
- serde_json::to_string(&proof).map_err(Error::from)?.as_str(),
- )
- .map_err(Error::from)?;
- }
- }
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
- let mut proofs = Vec::with_capacity(ys.len());
- for y in ys {
- match table.get(y.to_bytes()).map_err(Error::from)? {
- Some(proof) => proofs.push(Some(
- serde_json::from_str(proof.value()).map_err(Error::from)?,
- )),
- None => proofs.push(None),
- }
- }
- Ok(proofs)
- }
- async fn get_proofs_states(&self, ys: &[PublicKey]) -> Result<Vec<Option<State>>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(PROOFS_STATE_TABLE)
- .map_err(Error::from)?;
- let mut states = Vec::with_capacity(ys.len());
- for y in ys {
- match table.get(y.to_bytes()).map_err(Error::from)? {
- Some(state) => states.push(Some(
- serde_json::from_str(state.value()).map_err(Error::from)?,
- )),
- None => states.push(None),
- }
- }
- Ok(states)
- }
- async fn update_proofs_states(
- &self,
- ys: &[PublicKey],
- proofs_state: State,
- ) -> Result<Vec<Option<State>>, Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- let mut states = Vec::with_capacity(ys.len());
- let state_str = serde_json::to_string(&proofs_state).map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(PROOFS_STATE_TABLE)
- .map_err(Error::from)?;
- for y in ys {
- let current_state;
- {
- match table.get(y.to_bytes()).map_err(Error::from)? {
- Some(state) => {
- current_state =
- Some(serde_json::from_str(state.value()).map_err(Error::from)?)
- }
- None => current_state = None,
- }
- }
- states.push(current_state);
- if current_state != Some(State::Spent) {
- table
- .insert(y.to_bytes(), state_str.as_str())
- .map_err(Error::from)?;
- }
- }
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(states)
- }
- async fn add_blind_signatures(
- &self,
- blinded_messages: &[PublicKey],
- blind_signatures: &[BlindSignature],
- ) -> Result<(), Self::Err> {
- let db = self.db.lock().await;
- let write_txn = db.begin_write().map_err(Error::from)?;
- {
- let mut table = write_txn
- .open_table(BLINDED_SIGNATURES)
- .map_err(Error::from)?;
- for (blinded_message, blind_signature) in blinded_messages.iter().zip(blind_signatures)
- {
- table
- .insert(
- blinded_message.to_bytes(),
- serde_json::to_string(&blind_signature)
- .map_err(Error::from)?
- .as_str(),
- )
- .map_err(Error::from)?;
- }
- }
- write_txn.commit().map_err(Error::from)?;
- Ok(())
- }
- async fn get_blinded_signatures(
- &self,
- blinded_messages: &[PublicKey],
- ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
- let db = self.db.lock().await;
- let read_txn = db.begin_read().map_err(Error::from)?;
- let table = read_txn
- .open_table(BLINDED_SIGNATURES)
- .map_err(Error::from)?;
- let mut signatures = Vec::with_capacity(blinded_messages.len());
- for blinded_message in blinded_messages {
- match table.get(blinded_message.to_bytes()).map_err(Error::from)? {
- Some(blind_signature) => signatures.push(Some(
- serde_json::from_str(blind_signature.value()).map_err(Error::from)?,
- )),
- None => signatures.push(None),
- }
- }
- Ok(signatures)
- }
- }
|