| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719 |
- //! SQL database implementation of the Mint
- //!
- //! This is a generic SQL implementation for the mint storage layer. Any database can be plugged in
- //! as long as standard ANSI SQL is used, as Postgres and SQLite would understand it.
- //!
- //! This implementation also has a rudimentary but standard migration and versioning system.
- //!
- //! The trait expects an asynchronous interaction, but it also provides tools to spawn blocking
- //! clients in a pool and expose them to an asynchronous environment, making them compatible with
- //! Mint.
- use std::collections::HashMap;
- use std::fmt::Debug;
- use std::str::FromStr;
- use std::sync::Arc;
- use async_trait::async_trait;
- use bitcoin::bip32::DerivationPath;
- use cdk_common::database::mint::{validate_kvstore_params, SagaDatabase, SagaTransaction};
- use cdk_common::database::{
- self, ConversionError, DbTransactionFinalizer, Error, MintDatabase, MintKeyDatabaseTransaction,
- MintKeysDatabase, MintProofsDatabase, MintQuotesDatabase, MintQuotesTransaction,
- MintSignatureTransaction, MintSignaturesDatabase,
- };
- use cdk_common::mint::{
- self, IncomingPayment, Issuance, MeltPaymentRequest, MeltQuote, MintKeySetInfo, MintQuote,
- Operation,
- };
- use cdk_common::nut00::ProofsMethods;
- use cdk_common::payment::PaymentIdentifier;
- use cdk_common::quote_id::QuoteId;
- use cdk_common::secret::Secret;
- use cdk_common::state::{check_melt_quote_state_transition, check_state_transition};
- use cdk_common::util::unix_time;
- use cdk_common::{
- Amount, BlindSignature, BlindSignatureDleq, BlindedMessage, CurrencyUnit, Id, MeltQuoteState,
- PaymentMethod, Proof, Proofs, PublicKey, SecretKey, State,
- };
- use lightning_invoice::Bolt11Invoice;
- use migrations::MIGRATIONS;
- use tracing::instrument;
- use crate::common::migrate;
- use crate::database::{ConnectionWithTransaction, DatabaseExecutor};
- use crate::pool::{DatabasePool, Pool, PooledResource};
- use crate::stmt::{query, Column};
- use crate::{
- column_as_nullable_number, column_as_nullable_string, column_as_number, column_as_string,
- unpack_into,
- };
- #[cfg(feature = "auth")]
- mod auth;
- #[rustfmt::skip]
- mod migrations {
- include!(concat!(env!("OUT_DIR"), "/migrations_mint.rs"));
- }
- #[cfg(feature = "auth")]
- pub use auth::SQLMintAuthDatabase;
- #[cfg(feature = "prometheus")]
- use cdk_prometheus::METRICS;
- /// Mint SQL Database
- #[derive(Debug, Clone)]
- pub struct SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- pool: Arc<Pool<RM>>,
- }
- /// SQL Transaction Writer
- pub struct SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- inner: ConnectionWithTransaction<RM::Connection, PooledResource<RM>>,
- }
- #[inline(always)]
- async fn get_current_states<C>(
- conn: &C,
- ys: &[PublicKey],
- ) -> Result<HashMap<PublicKey, State>, Error>
- where
- C: DatabaseExecutor + Send + Sync,
- {
- if ys.is_empty() {
- return Ok(Default::default());
- }
- query(r#"SELECT y, state FROM proof WHERE y IN (:ys)"#)?
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .fetch_all(conn)
- .await?
- .into_iter()
- .map(|row| {
- Ok((
- column_as_string!(&row[0], PublicKey::from_hex, PublicKey::from_slice),
- column_as_string!(&row[1], State::from_str),
- ))
- })
- .collect::<Result<HashMap<_, _>, _>>()
- }
- impl<RM> SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- /// Creates a new instance
- pub async fn new<X>(db: X) -> Result<Self, Error>
- where
- X: Into<RM::Config>,
- {
- let pool = Pool::new(db.into());
- Self::migrate(pool.get().map_err(|e| Error::Database(Box::new(e)))?).await?;
- Ok(Self { pool })
- }
- /// Migrate
- async fn migrate(conn: PooledResource<RM>) -> Result<(), Error> {
- let tx = ConnectionWithTransaction::new(conn).await?;
- migrate(&tx, RM::Connection::name(), MIGRATIONS).await?;
- tx.commit().await?;
- Ok(())
- }
- }
- #[async_trait]
- impl<RM> database::MintProofsTransaction<'_> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn add_proofs(
- &mut self,
- proofs: Proofs,
- quote_id: Option<QuoteId>,
- operation: &Operation,
- ) -> Result<(), Self::Err> {
- let current_time = unix_time();
- // Check any previous proof, this query should return None in order to proceed storing
- // Any result here would error
- match query(r#"SELECT state FROM proof WHERE y IN (:ys) LIMIT 1 FOR UPDATE"#)?
- .bind_vec(
- "ys",
- proofs
- .iter()
- .map(|y| y.y().map(|y| y.to_bytes().to_vec()))
- .collect::<Result<_, _>>()?,
- )
- .pluck(&self.inner)
- .await?
- .map(|state| Ok::<_, Error>(column_as_string!(&state, State::from_str)))
- .transpose()?
- {
- Some(State::Spent) => Err(database::Error::AttemptUpdateSpentProof),
- Some(_) => Err(database::Error::Duplicate),
- None => Ok(()), // no previous record
- }?;
- for proof in proofs {
- query(
- r#"
- INSERT INTO proof
- (y, amount, keyset_id, secret, c, witness, state, quote_id, created_time, operation_kind, operation_id)
- VALUES
- (:y, :amount, :keyset_id, :secret, :c, :witness, :state, :quote_id, :created_time, :operation_kind, :operation_id)
- "#,
- )?
- .bind("y", proof.y()?.to_bytes().to_vec())
- .bind("amount", proof.amount.to_i64())
- .bind("keyset_id", proof.keyset_id.to_string())
- .bind("secret", proof.secret.to_string())
- .bind("c", proof.c.to_bytes().to_vec())
- .bind(
- "witness",
- proof.witness.map(|w| serde_json::to_string(&w).unwrap()),
- )
- .bind("state", "UNSPENT".to_string())
- .bind("quote_id", quote_id.clone().map(|q| q.to_string()))
- .bind("created_time", current_time as i64)
- .bind("operation_kind", operation.kind())
- .bind("operation_id", operation.id().to_string())
- .execute(&self.inner)
- .await?;
- }
- Ok(())
- }
- async fn update_proofs_states(
- &mut self,
- ys: &[PublicKey],
- new_state: State,
- ) -> Result<Vec<Option<State>>, Self::Err> {
- let mut current_states = get_current_states(&self.inner, ys).await?;
- if current_states.len() != ys.len() {
- tracing::warn!(
- "Attempted to update state of non-existent proof {} {}",
- current_states.len(),
- ys.len()
- );
- return Err(database::Error::ProofNotFound);
- }
- for state in current_states.values() {
- check_state_transition(*state, new_state)?;
- }
- query(r#"UPDATE proof SET state = :new_state WHERE y IN (:ys)"#)?
- .bind("new_state", new_state.to_string())
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .execute(&self.inner)
- .await?;
- if new_state == State::Spent {
- query(
- r#"
- INSERT INTO keyset_amounts (keyset_id, total_issued, total_redeemed)
- SELECT keyset_id, 0, COALESCE(SUM(amount), 0)
- FROM proof
- WHERE y IN (:ys)
- GROUP BY keyset_id
- ON CONFLICT (keyset_id)
- DO UPDATE SET total_redeemed = keyset_amounts.total_redeemed + EXCLUDED.total_redeemed
- "#,
- )?
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .execute(&self.inner)
- .await?;
- }
- Ok(ys.iter().map(|y| current_states.remove(y)).collect())
- }
- async fn remove_proofs(
- &mut self,
- ys: &[PublicKey],
- _quote_id: Option<QuoteId>,
- ) -> Result<(), Self::Err> {
- if ys.is_empty() {
- return Ok(());
- }
- let total_deleted = query(
- r#"
- DELETE FROM proof WHERE y IN (:ys) AND state NOT IN (:exclude_state)
- "#,
- )?
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .bind_vec("exclude_state", vec![State::Spent.to_string()])
- .execute(&self.inner)
- .await?;
- if total_deleted != ys.len() {
- // Query current states to provide detailed logging
- let current_states = get_current_states(&self.inner, ys).await?;
- let missing_count = ys.len() - current_states.len();
- let spent_count = current_states
- .values()
- .filter(|s| **s == State::Spent)
- .count();
- if missing_count > 0 {
- tracing::warn!(
- "remove_proofs: {} of {} proofs do not exist in database (already removed?)",
- missing_count,
- ys.len()
- );
- }
- if spent_count > 0 {
- tracing::warn!(
- "remove_proofs: {} of {} proofs are in Spent state and cannot be removed",
- spent_count,
- ys.len()
- );
- }
- tracing::debug!(
- "remove_proofs details: requested={}, deleted={}, missing={}, spent={}",
- ys.len(),
- total_deleted,
- missing_count,
- spent_count
- );
- return Err(Self::Err::AttemptRemoveSpentProof);
- }
- Ok(())
- }
- async fn get_proof_ys_by_quote_id(
- &self,
- quote_id: &QuoteId,
- ) -> Result<Vec<PublicKey>, Self::Err> {
- Ok(query(
- r#"
- SELECT
- amount,
- keyset_id,
- secret,
- c,
- witness
- FROM
- proof
- WHERE
- quote_id = :quote_id
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(&self.inner)
- .await?
- .into_iter()
- .map(sql_row_to_proof)
- .collect::<Result<Vec<Proof>, _>>()?
- .ys()?)
- }
- }
- #[async_trait]
- impl<RM> database::MintTransaction<'_, Error> for SQLTransaction<RM> where RM: DatabasePool + 'static
- {}
- #[async_trait]
- impl<RM> DbTransactionFinalizer for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn commit(self: Box<Self>) -> Result<(), Error> {
- let result = self.inner.commit().await;
- #[cfg(feature = "prometheus")]
- {
- let success = result.is_ok();
- METRICS.record_mint_operation("transaction_commit", success);
- METRICS.record_mint_operation_histogram("transaction_commit", success, 1.0);
- }
- Ok(result?)
- }
- async fn rollback(self: Box<Self>) -> Result<(), Error> {
- let result = self.inner.rollback().await;
- #[cfg(feature = "prometheus")]
- {
- let success = result.is_ok();
- METRICS.record_mint_operation("transaction_rollback", success);
- METRICS.record_mint_operation_histogram("transaction_rollback", success, 1.0);
- }
- Ok(result?)
- }
- }
- #[inline(always)]
- async fn get_mint_quote_payments<C>(
- conn: &C,
- quote_id: &QuoteId,
- ) -> Result<Vec<IncomingPayment>, Error>
- where
- C: DatabaseExecutor + Send + Sync,
- {
- // Get payment IDs and timestamps from the mint_quote_payments table
- query(
- r#"
- SELECT
- payment_id,
- timestamp,
- amount
- FROM
- mint_quote_payments
- WHERE
- quote_id=:quote_id
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(conn)
- .await?
- .into_iter()
- .map(|row| {
- let amount: u64 = column_as_number!(row[2].clone());
- let time: u64 = column_as_number!(row[1].clone());
- Ok(IncomingPayment::new(
- amount.into(),
- column_as_string!(&row[0]),
- time,
- ))
- })
- .collect()
- }
- #[inline(always)]
- async fn get_mint_quote_issuance<C>(conn: &C, quote_id: &QuoteId) -> Result<Vec<Issuance>, Error>
- where
- C: DatabaseExecutor + Send + Sync,
- {
- // Get payment IDs and timestamps from the mint_quote_payments table
- query(
- r#"
- SELECT amount, timestamp
- FROM mint_quote_issued
- WHERE quote_id=:quote_id
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(conn)
- .await?
- .into_iter()
- .map(|row| {
- let time: u64 = column_as_number!(row[1].clone());
- Ok(Issuance::new(
- Amount::from_i64(column_as_number!(row[0].clone()))
- .expect("Is amount when put into db"),
- time,
- ))
- })
- .collect()
- }
- // Inline helper functions that work with both connections and transactions
- #[inline]
- async fn get_mint_quote_inner<T>(
- executor: &T,
- quote_id: &QuoteId,
- for_update: bool,
- ) -> Result<Option<MintQuote>, Error>
- where
- T: DatabaseExecutor,
- {
- let payments = get_mint_quote_payments(executor, quote_id).await?;
- let issuance = get_mint_quote_issuance(executor, quote_id).await?;
- let for_update_clause = if for_update { "FOR UPDATE" } else { "" };
- let query_str = format!(
- r#"
- SELECT
- id,
- amount,
- unit,
- request,
- expiry,
- request_lookup_id,
- pubkey,
- created_time,
- amount_paid,
- amount_issued,
- payment_method,
- request_lookup_id_kind
- FROM
- mint_quote
- WHERE id = :id
- {for_update_clause}
- "#
- );
- query(&query_str)?
- .bind("id", quote_id.to_string())
- .fetch_one(executor)
- .await?
- .map(|row| sql_row_to_mint_quote(row, payments, issuance))
- .transpose()
- }
- #[inline]
- async fn get_mint_quote_by_request_inner<T>(
- executor: &T,
- request: &str,
- for_update: bool,
- ) -> Result<Option<MintQuote>, Error>
- where
- T: DatabaseExecutor,
- {
- let for_update_clause = if for_update { "FOR UPDATE" } else { "" };
- let query_str = format!(
- r#"
- SELECT
- id,
- amount,
- unit,
- request,
- expiry,
- request_lookup_id,
- pubkey,
- created_time,
- amount_paid,
- amount_issued,
- payment_method,
- request_lookup_id_kind
- FROM
- mint_quote
- WHERE request = :request
- {for_update_clause}
- "#
- );
- let mut mint_quote = query(&query_str)?
- .bind("request", request.to_string())
- .fetch_one(executor)
- .await?
- .map(|row| sql_row_to_mint_quote(row, vec![], vec![]))
- .transpose()?;
- if let Some(quote) = mint_quote.as_mut() {
- let payments = get_mint_quote_payments(executor, "e.id).await?;
- let issuance = get_mint_quote_issuance(executor, "e.id).await?;
- quote.issuance = issuance;
- quote.payments = payments;
- }
- Ok(mint_quote)
- }
- #[inline]
- async fn get_mint_quote_by_request_lookup_id_inner<T>(
- executor: &T,
- request_lookup_id: &PaymentIdentifier,
- for_update: bool,
- ) -> Result<Option<MintQuote>, Error>
- where
- T: DatabaseExecutor,
- {
- let for_update_clause = if for_update { "FOR UPDATE" } else { "" };
- let query_str = format!(
- r#"
- SELECT
- id,
- amount,
- unit,
- request,
- expiry,
- request_lookup_id,
- pubkey,
- created_time,
- amount_paid,
- amount_issued,
- payment_method,
- request_lookup_id_kind
- FROM
- mint_quote
- WHERE request_lookup_id = :request_lookup_id
- AND request_lookup_id_kind = :request_lookup_id_kind
- {for_update_clause}
- "#
- );
- let mut mint_quote = query(&query_str)?
- .bind("request_lookup_id", request_lookup_id.to_string())
- .bind("request_lookup_id_kind", request_lookup_id.kind())
- .fetch_one(executor)
- .await?
- .map(|row| sql_row_to_mint_quote(row, vec![], vec![]))
- .transpose()?;
- if let Some(quote) = mint_quote.as_mut() {
- let payments = get_mint_quote_payments(executor, "e.id).await?;
- let issuance = get_mint_quote_issuance(executor, "e.id).await?;
- quote.issuance = issuance;
- quote.payments = payments;
- }
- Ok(mint_quote)
- }
- #[inline]
- async fn get_melt_quote_inner<T>(
- executor: &T,
- quote_id: &QuoteId,
- for_update: bool,
- ) -> Result<Option<mint::MeltQuote>, Error>
- where
- T: DatabaseExecutor,
- {
- let for_update_clause = if for_update { "FOR UPDATE" } else { "" };
- let query_str = format!(
- r#"
- SELECT
- id,
- unit,
- amount,
- request,
- fee_reserve,
- expiry,
- state,
- payment_preimage,
- request_lookup_id,
- created_time,
- paid_time,
- payment_method,
- options,
- request_lookup_id_kind
- FROM
- melt_quote
- WHERE
- id=:id
- {for_update_clause}
- "#
- );
- query(&query_str)?
- .bind("id", quote_id.to_string())
- .fetch_one(executor)
- .await?
- .map(sql_row_to_melt_quote)
- .transpose()
- }
- #[async_trait]
- impl<RM> MintKeyDatabaseTransaction<'_, Error> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- async fn add_keyset_info(&mut self, keyset: MintKeySetInfo) -> Result<(), Error> {
- query(
- r#"
- INSERT INTO
- keyset (
- id, unit, active, valid_from, valid_to, derivation_path,
- amounts, input_fee_ppk, derivation_path_index
- )
- VALUES (
- :id, :unit, :active, :valid_from, :valid_to, :derivation_path,
- :amounts, :input_fee_ppk, :derivation_path_index
- )
- ON CONFLICT(id) DO UPDATE SET
- unit = excluded.unit,
- active = excluded.active,
- valid_from = excluded.valid_from,
- valid_to = excluded.valid_to,
- derivation_path = excluded.derivation_path,
- amounts = excluded.amounts,
- input_fee_ppk = excluded.input_fee_ppk,
- derivation_path_index = excluded.derivation_path_index
- "#,
- )?
- .bind("id", keyset.id.to_string())
- .bind("unit", keyset.unit.to_string())
- .bind("active", keyset.active)
- .bind("valid_from", keyset.valid_from as i64)
- .bind("valid_to", keyset.final_expiry.map(|v| v as i64))
- .bind("derivation_path", keyset.derivation_path.to_string())
- .bind("amounts", serde_json::to_string(&keyset.amounts).ok())
- .bind("input_fee_ppk", keyset.input_fee_ppk as i64)
- .bind("derivation_path_index", keyset.derivation_path_index)
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn set_active_keyset(&mut self, unit: CurrencyUnit, id: Id) -> Result<(), Error> {
- query(r#"UPDATE keyset SET active=FALSE WHERE unit = :unit"#)?
- .bind("unit", unit.to_string())
- .execute(&self.inner)
- .await?;
- query(r#"UPDATE keyset SET active=TRUE WHERE unit = :unit AND id = :id"#)?
- .bind("unit", unit.to_string())
- .bind("id", id.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- }
- #[async_trait]
- impl<RM> MintKeysDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn begin_transaction<'a>(
- &'a self,
- ) -> Result<Box<dyn MintKeyDatabaseTransaction<'a, Error> + Send + Sync + 'a>, Error> {
- let tx = SQLTransaction {
- inner: ConnectionWithTransaction::new(
- self.pool.get().map_err(|e| Error::Database(Box::new(e)))?,
- )
- .await?,
- };
- Ok(Box::new(tx))
- }
- async fn get_active_keyset_id(&self, unit: &CurrencyUnit) -> Result<Option<Id>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(
- query(r#" SELECT id FROM keyset WHERE active = :active AND unit = :unit"#)?
- .bind("active", true)
- .bind("unit", unit.to_string())
- .pluck(&*conn)
- .await?
- .map(|id| match id {
- Column::Text(text) => Ok(Id::from_str(&text)?),
- Column::Blob(id) => Ok(Id::from_bytes(&id)?),
- _ => Err(Error::InvalidKeysetId),
- })
- .transpose()?,
- )
- }
- async fn get_active_keysets(&self) -> Result<HashMap<CurrencyUnit, Id>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(
- query(r#"SELECT id, unit FROM keyset WHERE active = :active"#)?
- .bind("active", true)
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|row| {
- Ok((
- column_as_string!(&row[1], CurrencyUnit::from_str),
- column_as_string!(&row[0], Id::from_str, Id::from_bytes),
- ))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?,
- )
- }
- async fn get_keyset_info(&self, id: &Id) -> Result<Option<MintKeySetInfo>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"SELECT
- id,
- unit,
- active,
- valid_from,
- valid_to,
- derivation_path,
- derivation_path_index,
- amounts,
- input_fee_ppk
- FROM
- keyset
- WHERE id=:id"#,
- )?
- .bind("id", id.to_string())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_keyset_info)
- .transpose()?)
- }
- async fn get_keyset_infos(&self) -> Result<Vec<MintKeySetInfo>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"SELECT
- id,
- unit,
- active,
- valid_from,
- valid_to,
- derivation_path,
- derivation_path_index,
- amounts,
- input_fee_ppk
- FROM
- keyset
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_keyset_info)
- .collect::<Result<Vec<_>, _>>()?)
- }
- }
- #[async_trait]
- impl<RM> MintQuotesTransaction<'_> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn add_melt_request(
- &mut self,
- quote_id: &QuoteId,
- inputs_amount: Amount,
- inputs_fee: Amount,
- ) -> Result<(), Self::Err> {
- // Insert melt_request
- query(
- r#"
- INSERT INTO melt_request
- (quote_id, inputs_amount, inputs_fee)
- VALUES
- (:quote_id, :inputs_amount, :inputs_fee)
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .bind("inputs_amount", inputs_amount.to_i64())
- .bind("inputs_fee", inputs_fee.to_i64())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn add_blinded_messages(
- &mut self,
- quote_id: Option<&QuoteId>,
- blinded_messages: &[BlindedMessage],
- operation: &Operation,
- ) -> Result<(), Self::Err> {
- let current_time = unix_time();
- // Insert blinded_messages directly into blind_signature with c = NULL
- // Let the database constraint handle duplicate detection
- for message in blinded_messages {
- match query(
- r#"
- INSERT INTO blind_signature
- (blinded_message, amount, keyset_id, c, quote_id, created_time, operation_kind, operation_id)
- VALUES
- (:blinded_message, :amount, :keyset_id, NULL, :quote_id, :created_time, :operation_kind, :operation_id)
- "#,
- )?
- .bind(
- "blinded_message",
- message.blinded_secret.to_bytes().to_vec(),
- )
- .bind("amount", message.amount.to_i64())
- .bind("keyset_id", message.keyset_id.to_string())
- .bind("quote_id", quote_id.map(|q| q.to_string()))
- .bind("created_time", current_time as i64)
- .bind("operation_kind", operation.kind())
- .bind("operation_id", operation.id().to_string())
- .execute(&self.inner)
- .await
- {
- Ok(_) => continue,
- Err(database::Error::Duplicate) => {
- // Primary key constraint violation - blinded message already exists
- // This could be either:
- // 1. Already signed (c IS NOT NULL) - definitely an error
- // 2. Already pending (c IS NULL) - also an error
- return Err(database::Error::Duplicate);
- }
- Err(err) => return Err(err),
- }
- }
- Ok(())
- }
- async fn delete_blinded_messages(
- &mut self,
- blinded_secrets: &[PublicKey],
- ) -> Result<(), Self::Err> {
- if blinded_secrets.is_empty() {
- return Ok(());
- }
- // Delete blinded messages from blind_signature table where c IS NULL
- // (only delete unsigned blinded messages)
- query(
- r#"
- DELETE FROM blind_signature
- WHERE blinded_message IN (:blinded_secrets) AND c IS NULL
- "#,
- )?
- .bind_vec(
- "blinded_secrets",
- blinded_secrets
- .iter()
- .map(|secret| secret.to_bytes().to_vec())
- .collect(),
- )
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn get_melt_request_and_blinded_messages(
- &mut self,
- quote_id: &QuoteId,
- ) -> Result<Option<database::mint::MeltRequestInfo>, Self::Err> {
- let melt_request_row = query(
- r#"
- SELECT inputs_amount, inputs_fee
- FROM melt_request
- WHERE quote_id = :quote_id
- FOR UPDATE
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_one(&self.inner)
- .await?;
- if let Some(row) = melt_request_row {
- let inputs_amount: u64 = column_as_number!(row[0].clone());
- let inputs_fee: u64 = column_as_number!(row[1].clone());
- // Get blinded messages from blind_signature table where c IS NULL
- let blinded_messages_rows = query(
- r#"
- SELECT blinded_message, keyset_id, amount
- FROM blind_signature
- WHERE quote_id = :quote_id AND c IS NULL
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(&self.inner)
- .await?;
- let blinded_messages: Result<Vec<BlindedMessage>, Error> = blinded_messages_rows
- .into_iter()
- .map(|row| -> Result<BlindedMessage, Error> {
- let blinded_message_key =
- column_as_string!(&row[0], PublicKey::from_hex, PublicKey::from_slice);
- let keyset_id = column_as_string!(&row[1], Id::from_str, Id::from_bytes);
- let amount: u64 = column_as_number!(row[2].clone());
- Ok(BlindedMessage {
- blinded_secret: blinded_message_key,
- keyset_id,
- amount: Amount::from(amount),
- witness: None, // Not storing witness in database currently
- })
- })
- .collect();
- let blinded_messages = blinded_messages?;
- Ok(Some(database::mint::MeltRequestInfo {
- inputs_amount: Amount::from(inputs_amount),
- inputs_fee: Amount::from(inputs_fee),
- change_outputs: blinded_messages,
- }))
- } else {
- Ok(None)
- }
- }
- async fn delete_melt_request(&mut self, quote_id: &QuoteId) -> Result<(), Self::Err> {
- // Delete from melt_request table
- query(
- r#"
- DELETE FROM melt_request
- WHERE quote_id = :quote_id
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .execute(&self.inner)
- .await?;
- // Also delete blinded messages (where c IS NULL) from blind_signature table
- query(
- r#"
- DELETE FROM blind_signature
- WHERE quote_id = :quote_id AND c IS NULL
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn increment_mint_quote_amount_paid(
- &mut self,
- quote_id: &QuoteId,
- amount_paid: Amount,
- payment_id: String,
- ) -> Result<Amount, Self::Err> {
- if amount_paid == Amount::ZERO {
- tracing::warn!("Amount payments of zero amount should not be recorded.");
- return Err(Error::Duplicate);
- }
- // Check if payment_id already exists in mint_quote_payments
- let exists = query(
- r#"
- SELECT payment_id
- FROM mint_quote_payments
- WHERE payment_id = :payment_id
- FOR UPDATE
- "#,
- )?
- .bind("payment_id", payment_id.clone())
- .fetch_one(&self.inner)
- .await?;
- if exists.is_some() {
- tracing::error!("Payment ID already exists: {}", payment_id);
- return Err(database::Error::Duplicate);
- }
- // Get current amount_paid from quote
- let current_amount = query(
- r#"
- SELECT amount_paid
- FROM mint_quote
- WHERE id = :quote_id
- FOR UPDATE
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_one(&self.inner)
- .await
- .inspect_err(|err| {
- tracing::error!("SQLite could not get mint quote amount_paid: {}", err);
- })?;
- let current_amount_paid = if let Some(current_amount) = current_amount {
- let amount: u64 = column_as_number!(current_amount[0].clone());
- Amount::from(amount)
- } else {
- Amount::ZERO
- };
- // Calculate new amount_paid with overflow check
- let new_amount_paid = current_amount_paid
- .checked_add(amount_paid)
- .ok_or_else(|| database::Error::AmountOverflow)?;
- tracing::debug!(
- "Mint quote {} amount paid was {} is now {}.",
- quote_id,
- current_amount_paid,
- new_amount_paid
- );
- // Update the amount_paid
- query(
- r#"
- UPDATE mint_quote
- SET amount_paid = :amount_paid
- WHERE id = :quote_id
- "#,
- )?
- .bind("amount_paid", new_amount_paid.to_i64())
- .bind("quote_id", quote_id.to_string())
- .execute(&self.inner)
- .await
- .inspect_err(|err| {
- tracing::error!("SQLite could not update mint quote amount_paid: {}", err);
- })?;
- // Add payment_id to mint_quote_payments table
- query(
- r#"
- INSERT INTO mint_quote_payments
- (quote_id, payment_id, amount, timestamp)
- VALUES (:quote_id, :payment_id, :amount, :timestamp)
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .bind("payment_id", payment_id)
- .bind("amount", amount_paid.to_i64())
- .bind("timestamp", unix_time() as i64)
- .execute(&self.inner)
- .await
- .map_err(|err| {
- tracing::error!("SQLite could not insert payment ID: {}", err);
- err
- })?;
- Ok(new_amount_paid)
- }
- #[instrument(skip_all)]
- async fn increment_mint_quote_amount_issued(
- &mut self,
- quote_id: &QuoteId,
- amount_issued: Amount,
- ) -> Result<Amount, Self::Err> {
- // Get current amount_issued from quote
- let current_amounts = query(
- r#"
- SELECT amount_issued, amount_paid
- FROM mint_quote
- WHERE id = :quote_id
- FOR UPDATE
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_one(&self.inner)
- .await
- .inspect_err(|err| {
- tracing::error!("SQLite could not get mint quote amount_issued: {}", err);
- })?
- .ok_or(Error::QuoteNotFound)?;
- let new_amount_issued = {
- // Make sure the db protects issuing not paid quotes
- unpack_into!(
- let (current_amount_issued, current_amount_paid) = current_amounts
- );
- let current_amount_issued: u64 = column_as_number!(current_amount_issued);
- let current_amount_paid: u64 = column_as_number!(current_amount_paid);
- let current_amount_issued = Amount::from(current_amount_issued);
- let current_amount_paid = Amount::from(current_amount_paid);
- // Calculate new amount_issued with overflow check
- let new_amount_issued = current_amount_issued
- .checked_add(amount_issued)
- .ok_or_else(|| database::Error::AmountOverflow)?;
- current_amount_paid
- .checked_sub(new_amount_issued)
- .ok_or(Error::Internal("Over-issued not allowed".to_owned()))?;
- new_amount_issued
- };
- // Update the amount_issued
- query(
- r#"
- UPDATE mint_quote
- SET amount_issued = :amount_issued
- WHERE id = :quote_id
- "#,
- )?
- .bind("amount_issued", new_amount_issued.to_i64())
- .bind("quote_id", quote_id.to_string())
- .execute(&self.inner)
- .await
- .inspect_err(|err| {
- tracing::error!("SQLite could not update mint quote amount_issued: {}", err);
- })?;
- let current_time = unix_time();
- query(
- r#"
- INSERT INTO mint_quote_issued
- (quote_id, amount, timestamp)
- VALUES (:quote_id, :amount, :timestamp);
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .bind("amount", amount_issued.to_i64())
- .bind("timestamp", current_time as i64)
- .execute(&self.inner)
- .await?;
- Ok(new_amount_issued)
- }
- #[instrument(skip_all)]
- async fn add_mint_quote(&mut self, quote: MintQuote) -> Result<(), Self::Err> {
- query(
- r#"
- INSERT INTO mint_quote (
- id, amount, unit, request, expiry, request_lookup_id, pubkey, created_time, payment_method, request_lookup_id_kind
- )
- VALUES (
- :id, :amount, :unit, :request, :expiry, :request_lookup_id, :pubkey, :created_time, :payment_method, :request_lookup_id_kind
- )
- "#,
- )?
- .bind("id", quote.id.to_string())
- .bind("amount", quote.amount.map(|a| a.to_i64()))
- .bind("unit", quote.unit.to_string())
- .bind("request", quote.request)
- .bind("expiry", quote.expiry as i64)
- .bind(
- "request_lookup_id",
- quote.request_lookup_id.to_string(),
- )
- .bind("pubkey", quote.pubkey.map(|p| p.to_string()))
- .bind("created_time", quote.created_time as i64)
- .bind("payment_method", quote.payment_method.to_string())
- .bind("request_lookup_id_kind", quote.request_lookup_id.kind())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn add_melt_quote(&mut self, quote: mint::MeltQuote) -> Result<(), Self::Err> {
- // Now insert the new quote
- query(
- r#"
- INSERT INTO melt_quote
- (
- id, unit, amount, request, fee_reserve, state,
- expiry, payment_preimage, request_lookup_id,
- created_time, paid_time, options, request_lookup_id_kind, payment_method
- )
- VALUES
- (
- :id, :unit, :amount, :request, :fee_reserve, :state,
- :expiry, :payment_preimage, :request_lookup_id,
- :created_time, :paid_time, :options, :request_lookup_id_kind, :payment_method
- )
- "#,
- )?
- .bind("id", quote.id.to_string())
- .bind("unit", quote.unit.to_string())
- .bind("amount", quote.amount.to_i64())
- .bind("request", serde_json::to_string("e.request)?)
- .bind("fee_reserve", quote.fee_reserve.to_i64())
- .bind("state", quote.state.to_string())
- .bind("expiry", quote.expiry as i64)
- .bind("payment_preimage", quote.payment_preimage)
- .bind(
- "request_lookup_id",
- quote.request_lookup_id.as_ref().map(|id| id.to_string()),
- )
- .bind("created_time", quote.created_time as i64)
- .bind("paid_time", quote.paid_time.map(|t| t as i64))
- .bind(
- "options",
- quote.options.map(|o| serde_json::to_string(&o).ok()),
- )
- .bind(
- "request_lookup_id_kind",
- quote.request_lookup_id.map(|id| id.kind()),
- )
- .bind("payment_method", quote.payment_method.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn update_melt_quote_request_lookup_id(
- &mut self,
- quote_id: &QuoteId,
- new_request_lookup_id: &PaymentIdentifier,
- ) -> Result<(), Self::Err> {
- query(r#"UPDATE melt_quote SET request_lookup_id = :new_req_id, request_lookup_id_kind = :new_kind WHERE id = :id"#)?
- .bind("new_req_id", new_request_lookup_id.to_string())
- .bind("new_kind",new_request_lookup_id.kind() )
- .bind("id", quote_id.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn update_melt_quote_state(
- &mut self,
- quote_id: &QuoteId,
- state: MeltQuoteState,
- payment_proof: Option<String>,
- ) -> Result<(MeltQuoteState, mint::MeltQuote), Self::Err> {
- let mut quote = query(
- r#"
- SELECT
- id,
- unit,
- amount,
- request,
- fee_reserve,
- expiry,
- state,
- payment_preimage,
- request_lookup_id,
- created_time,
- paid_time,
- payment_method,
- options,
- request_lookup_id_kind
- FROM
- melt_quote
- WHERE
- id=:id
- "#,
- )?
- .bind("id", quote_id.to_string())
- .fetch_one(&self.inner)
- .await?
- .map(sql_row_to_melt_quote)
- .transpose()?
- .ok_or(Error::QuoteNotFound)?;
- check_melt_quote_state_transition(quote.state, state)?;
- // When transitioning to Pending, lock all quotes with the same lookup_id
- // and check if any are already pending or paid
- if state == MeltQuoteState::Pending {
- if let Some(ref lookup_id) = quote.request_lookup_id {
- // Lock all quotes with the same lookup_id to prevent race conditions
- let locked_quotes: Vec<(String, String)> = query(
- r#"
- SELECT id, state
- FROM melt_quote
- WHERE request_lookup_id = :lookup_id
- FOR UPDATE
- "#,
- )?
- .bind("lookup_id", lookup_id.to_string())
- .fetch_all(&self.inner)
- .await?
- .into_iter()
- .map(|row| {
- unpack_into!(let (id, state) = row);
- Ok((column_as_string!(id), column_as_string!(state)))
- })
- .collect::<Result<Vec<_>, Error>>()?;
- // Check if any other quote with the same lookup_id is pending or paid
- let has_conflict = locked_quotes.iter().any(|(id, state)| {
- id != "e_id.to_string()
- && (state == &MeltQuoteState::Pending.to_string()
- || state == &MeltQuoteState::Paid.to_string())
- });
- if has_conflict {
- tracing::warn!(
- "Cannot transition quote {} to Pending: another quote with lookup_id {} is already pending or paid",
- quote_id,
- lookup_id
- );
- return Err(Error::Duplicate);
- }
- }
- }
- let rec = if state == MeltQuoteState::Paid {
- let current_time = unix_time();
- query(r#"UPDATE melt_quote SET state = :state, paid_time = :paid_time, payment_preimage = :payment_preimage WHERE id = :id"#)?
- .bind("state", state.to_string())
- .bind("paid_time", current_time as i64)
- .bind("payment_preimage", payment_proof)
- .bind("id", quote_id.to_string())
- .execute(&self.inner)
- .await
- } else {
- query(r#"UPDATE melt_quote SET state = :state WHERE id = :id"#)?
- .bind("state", state.to_string())
- .bind("id", quote_id.to_string())
- .execute(&self.inner)
- .await
- };
- match rec {
- Ok(_) => {}
- Err(err) => {
- tracing::error!("SQLite Could not update melt quote");
- return Err(err);
- }
- };
- let old_state = quote.state;
- quote.state = state;
- if state == MeltQuoteState::Unpaid || state == MeltQuoteState::Failed {
- self.delete_melt_request(quote_id).await?;
- }
- Ok((old_state, quote))
- }
- async fn get_mint_quote(&mut self, quote_id: &QuoteId) -> Result<Option<MintQuote>, Self::Err> {
- get_mint_quote_inner(&self.inner, quote_id, true).await
- }
- async fn get_melt_quote(
- &mut self,
- quote_id: &QuoteId,
- ) -> Result<Option<mint::MeltQuote>, Self::Err> {
- get_melt_quote_inner(&self.inner, quote_id, true).await
- }
- async fn get_mint_quote_by_request(
- &mut self,
- request: &str,
- ) -> Result<Option<MintQuote>, Self::Err> {
- get_mint_quote_by_request_inner(&self.inner, request, true).await
- }
- async fn get_mint_quote_by_request_lookup_id(
- &mut self,
- request_lookup_id: &PaymentIdentifier,
- ) -> Result<Option<MintQuote>, Self::Err> {
- get_mint_quote_by_request_lookup_id_inner(&self.inner, request_lookup_id, true).await
- }
- }
- #[async_trait]
- impl<RM> MintQuotesDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn get_mint_quote(&self, quote_id: &QuoteId) -> Result<Option<MintQuote>, Self::Err> {
- #[cfg(feature = "prometheus")]
- METRICS.inc_in_flight_requests("get_mint_quote");
- #[cfg(feature = "prometheus")]
- let start_time = std::time::Instant::now();
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let result = get_mint_quote_inner(&*conn, quote_id, false).await;
- #[cfg(feature = "prometheus")]
- {
- let success = result.is_ok();
- METRICS.record_mint_operation("get_mint_quote", success);
- METRICS.record_mint_operation_histogram(
- "get_mint_quote",
- success,
- start_time.elapsed().as_secs_f64(),
- );
- METRICS.dec_in_flight_requests("get_mint_quote");
- }
- result
- }
- async fn get_mint_quote_by_request(
- &self,
- request: &str,
- ) -> Result<Option<MintQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- get_mint_quote_by_request_inner(&*conn, request, false).await
- }
- async fn get_mint_quote_by_request_lookup_id(
- &self,
- request_lookup_id: &PaymentIdentifier,
- ) -> Result<Option<MintQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- get_mint_quote_by_request_lookup_id_inner(&*conn, request_lookup_id, false).await
- }
- async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mut mint_quotes = query(
- r#"
- SELECT
- id,
- amount,
- unit,
- request,
- expiry,
- request_lookup_id,
- pubkey,
- created_time,
- amount_paid,
- amount_issued,
- payment_method,
- request_lookup_id_kind
- FROM
- mint_quote
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|row| sql_row_to_mint_quote(row, vec![], vec![]))
- .collect::<Result<Vec<_>, _>>()?;
- for quote in mint_quotes.as_mut_slice() {
- let payments = get_mint_quote_payments(&*conn, "e.id).await?;
- let issuance = get_mint_quote_issuance(&*conn, "e.id).await?;
- quote.issuance = issuance;
- quote.payments = payments;
- }
- Ok(mint_quotes)
- }
- async fn get_melt_quote(
- &self,
- quote_id: &QuoteId,
- ) -> Result<Option<mint::MeltQuote>, Self::Err> {
- #[cfg(feature = "prometheus")]
- METRICS.inc_in_flight_requests("get_melt_quote");
- #[cfg(feature = "prometheus")]
- let start_time = std::time::Instant::now();
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let result = get_melt_quote_inner(&*conn, quote_id, false).await;
- #[cfg(feature = "prometheus")]
- {
- let success = result.is_ok();
- METRICS.record_mint_operation("get_melt_quote", success);
- METRICS.record_mint_operation_histogram(
- "get_melt_quote",
- success,
- start_time.elapsed().as_secs_f64(),
- );
- METRICS.dec_in_flight_requests("get_melt_quote");
- }
- result
- }
- async fn get_melt_quotes(&self) -> Result<Vec<mint::MeltQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- id,
- unit,
- amount,
- request,
- fee_reserve,
- expiry,
- state,
- payment_preimage,
- request_lookup_id,
- created_time,
- paid_time,
- payment_method,
- options,
- request_lookup_id_kind
- FROM
- melt_quote
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_melt_quote)
- .collect::<Result<Vec<_>, _>>()?)
- }
- }
- #[async_trait]
- impl<RM> MintProofsDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mut proofs = query(
- r#"
- SELECT
- amount,
- keyset_id,
- secret,
- c,
- witness,
- y
- FROM
- proof
- WHERE
- y IN (:ys)
- "#,
- )?
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|mut row| {
- Ok((
- column_as_string!(
- row.pop().ok_or(Error::InvalidDbResponse)?,
- PublicKey::from_hex,
- PublicKey::from_slice
- ),
- sql_row_to_proof(row)?,
- ))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?;
- Ok(ys.iter().map(|y| proofs.remove(y)).collect())
- }
- async fn get_proof_ys_by_quote_id(
- &self,
- quote_id: &QuoteId,
- ) -> Result<Vec<PublicKey>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- amount,
- keyset_id,
- secret,
- c,
- witness
- FROM
- proof
- WHERE
- quote_id = :quote_id
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_proof)
- .collect::<Result<Vec<Proof>, _>>()?
- .ys()?)
- }
- async fn get_proofs_states(&self, ys: &[PublicKey]) -> Result<Vec<Option<State>>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mut current_states = get_current_states(&*conn, ys).await?;
- Ok(ys.iter().map(|y| current_states.remove(y)).collect())
- }
- async fn get_proofs_by_keyset_id(
- &self,
- keyset_id: &Id,
- ) -> Result<(Proofs, Vec<Option<State>>), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- keyset_id,
- amount,
- secret,
- c,
- witness,
- state
- FROM
- proof
- WHERE
- keyset_id=:keyset_id
- "#,
- )?
- .bind("keyset_id", keyset_id.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_proof_with_state)
- .collect::<Result<Vec<_>, _>>()?
- .into_iter()
- .unzip())
- }
- /// Get total proofs redeemed by keyset id
- async fn get_total_redeemed(&self) -> Result<HashMap<Id, Amount>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- SELECT
- keyset_id,
- total_redeemed as amount
- FROM
- keyset_amounts
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_hashmap_amount)
- .collect()
- }
- }
- #[async_trait]
- impl<RM> MintSignatureTransaction<'_> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn add_blind_signatures(
- &mut self,
- blinded_messages: &[PublicKey],
- blind_signatures: &[BlindSignature],
- quote_id: Option<QuoteId>,
- ) -> Result<(), Self::Err> {
- let current_time = unix_time();
- if blinded_messages.len() != blind_signatures.len() {
- return Err(database::Error::Internal(
- "Mismatched array lengths for blinded messages and blind signatures".to_string(),
- ));
- }
- // Select all existing rows for the given blinded messages at once
- let mut existing_rows = query(
- r#"
- SELECT blinded_message, c, dleq_e, dleq_s
- FROM blind_signature
- WHERE blinded_message IN (:blinded_messages)
- FOR UPDATE
- "#,
- )?
- .bind_vec(
- "blinded_messages",
- blinded_messages
- .iter()
- .map(|message| message.to_bytes().to_vec())
- .collect(),
- )
- .fetch_all(&self.inner)
- .await?
- .into_iter()
- .map(|mut row| {
- Ok((
- column_as_string!(&row.remove(0), PublicKey::from_hex, PublicKey::from_slice),
- (row[0].clone(), row[1].clone(), row[2].clone()),
- ))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?;
- // Iterate over the provided blinded messages and signatures
- for (message, signature) in blinded_messages.iter().zip(blind_signatures) {
- match existing_rows.remove(message) {
- None => {
- // Unknown blind message: Insert new row with all columns
- query(
- r#"
- INSERT INTO blind_signature
- (blinded_message, amount, keyset_id, c, quote_id, dleq_e, dleq_s, created_time, signed_time)
- VALUES
- (:blinded_message, :amount, :keyset_id, :c, :quote_id, :dleq_e, :dleq_s, :created_time, :signed_time)
- "#,
- )?
- .bind("blinded_message", message.to_bytes().to_vec())
- .bind("amount", u64::from(signature.amount) as i64)
- .bind("keyset_id", signature.keyset_id.to_string())
- .bind("c", signature.c.to_bytes().to_vec())
- .bind("quote_id", quote_id.as_ref().map(|q| q.to_string()))
- .bind(
- "dleq_e",
- signature.dleq.as_ref().map(|dleq| dleq.e.to_secret_hex()),
- )
- .bind(
- "dleq_s",
- signature.dleq.as_ref().map(|dleq| dleq.s.to_secret_hex()),
- )
- .bind("created_time", current_time as i64)
- .bind("signed_time", current_time as i64)
- .execute(&self.inner)
- .await?;
- query(
- r#"
- INSERT INTO keyset_amounts (keyset_id, total_issued, total_redeemed)
- VALUES (:keyset_id, :amount, 0)
- ON CONFLICT (keyset_id)
- DO UPDATE SET total_issued = keyset_amounts.total_issued + EXCLUDED.total_issued
- "#,
- )?
- .bind("amount", u64::from(signature.amount) as i64)
- .bind("keyset_id", signature.keyset_id.to_string())
- .execute(&self.inner)
- .await?;
- }
- Some((c, _dleq_e, _dleq_s)) => {
- // Blind message exists: check if c is NULL
- match c {
- Column::Null => {
- // Blind message with no c: Update with missing columns c, dleq_e, dleq_s
- query(
- r#"
- UPDATE blind_signature
- SET c = :c, dleq_e = :dleq_e, dleq_s = :dleq_s, signed_time = :signed_time, amount = :amount
- WHERE blinded_message = :blinded_message
- "#,
- )?
- .bind("c", signature.c.to_bytes().to_vec())
- .bind(
- "dleq_e",
- signature.dleq.as_ref().map(|dleq| dleq.e.to_secret_hex()),
- )
- .bind(
- "dleq_s",
- signature.dleq.as_ref().map(|dleq| dleq.s.to_secret_hex()),
- )
- .bind("blinded_message", message.to_bytes().to_vec())
- .bind("signed_time", current_time as i64)
- .bind("amount", u64::from(signature.amount) as i64)
- .execute(&self.inner)
- .await?;
- query(
- r#"
- INSERT INTO keyset_amounts (keyset_id, total_issued, total_redeemed)
- VALUES (:keyset_id, :amount, 0)
- ON CONFLICT (keyset_id)
- DO UPDATE SET total_issued = keyset_amounts.total_issued + EXCLUDED.total_issued
- "#,
- )?
- .bind("amount", u64::from(signature.amount) as i64)
- .bind("keyset_id", signature.keyset_id.to_string())
- .execute(&self.inner)
- .await?;
- }
- _ => {
- // Blind message already has c: Error
- tracing::error!(
- "Attempting to add signature to message already signed {}",
- message
- );
- return Err(database::Error::Duplicate);
- }
- }
- }
- }
- }
- debug_assert!(
- existing_rows.is_empty(),
- "Unexpected existing rows remain: {:?}",
- existing_rows.keys().collect::<Vec<_>>()
- );
- if !existing_rows.is_empty() {
- tracing::error!("Did not check all existing rows");
- return Err(Error::Internal(
- "Did not check all existing rows".to_string(),
- ));
- }
- Ok(())
- }
- async fn get_blind_signatures(
- &mut self,
- blinded_messages: &[PublicKey],
- ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
- let mut blinded_signatures = query(
- r#"SELECT
- keyset_id,
- amount,
- c,
- dleq_e,
- dleq_s,
- blinded_message
- FROM
- blind_signature
- WHERE blinded_message IN (:b) AND c IS NOT NULL
- "#,
- )?
- .bind_vec(
- "b",
- blinded_messages
- .iter()
- .map(|b| b.to_bytes().to_vec())
- .collect(),
- )
- .fetch_all(&self.inner)
- .await?
- .into_iter()
- .map(|mut row| {
- Ok((
- column_as_string!(
- &row.pop().ok_or(Error::InvalidDbResponse)?,
- PublicKey::from_hex,
- PublicKey::from_slice
- ),
- sql_row_to_blind_signature(row)?,
- ))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?;
- Ok(blinded_messages
- .iter()
- .map(|y| blinded_signatures.remove(y))
- .collect())
- }
- }
- #[async_trait]
- impl<RM> MintSignaturesDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn get_blind_signatures(
- &self,
- blinded_messages: &[PublicKey],
- ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mut blinded_signatures = query(
- r#"SELECT
- keyset_id,
- amount,
- c,
- dleq_e,
- dleq_s,
- blinded_message
- FROM
- blind_signature
- WHERE blinded_message IN (:b) AND c IS NOT NULL
- "#,
- )?
- .bind_vec(
- "b",
- blinded_messages
- .iter()
- .map(|b_| b_.to_bytes().to_vec())
- .collect(),
- )
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|mut row| {
- Ok((
- column_as_string!(
- &row.pop().ok_or(Error::InvalidDbResponse)?,
- PublicKey::from_hex,
- PublicKey::from_slice
- ),
- sql_row_to_blind_signature(row)?,
- ))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?;
- Ok(blinded_messages
- .iter()
- .map(|y| blinded_signatures.remove(y))
- .collect())
- }
- async fn get_blind_signatures_for_keyset(
- &self,
- keyset_id: &Id,
- ) -> Result<Vec<BlindSignature>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- keyset_id,
- amount,
- c,
- dleq_e,
- dleq_s
- FROM
- blind_signature
- WHERE
- keyset_id=:keyset_id AND c IS NOT NULL
- "#,
- )?
- .bind("keyset_id", keyset_id.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_blind_signature)
- .collect::<Result<Vec<BlindSignature>, _>>()?)
- }
- /// Get [`BlindSignature`]s for quote
- async fn get_blind_signatures_for_quote(
- &self,
- quote_id: &QuoteId,
- ) -> Result<Vec<BlindSignature>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- keyset_id,
- amount,
- c,
- dleq_e,
- dleq_s
- FROM
- blind_signature
- WHERE
- quote_id=:quote_id AND c IS NOT NULL
- "#,
- )?
- .bind("quote_id", quote_id.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_blind_signature)
- .collect::<Result<Vec<BlindSignature>, _>>()?)
- }
- /// Get total proofs redeemed by keyset id
- async fn get_total_issued(&self) -> Result<HashMap<Id, Amount>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- SELECT
- keyset_id,
- total_issued as amount
- FROM
- keyset_amounts
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_hashmap_amount)
- .collect()
- }
- }
- #[async_trait]
- impl<RM> database::MintKVStoreTransaction<'_, Error> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- async fn kv_read(
- &mut self,
- primary_namespace: &str,
- secondary_namespace: &str,
- key: &str,
- ) -> Result<Option<Vec<u8>>, Error> {
- // Validate parameters according to KV store requirements
- validate_kvstore_params(primary_namespace, secondary_namespace, key)?;
- Ok(query(
- r#"
- SELECT value
- FROM kv_store
- WHERE primary_namespace = :primary_namespace
- AND secondary_namespace = :secondary_namespace
- AND key = :key
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .bind("key", key.to_owned())
- .pluck(&self.inner)
- .await?
- .and_then(|col| match col {
- Column::Blob(data) => Some(data),
- _ => None,
- }))
- }
- async fn kv_write(
- &mut self,
- primary_namespace: &str,
- secondary_namespace: &str,
- key: &str,
- value: &[u8],
- ) -> Result<(), Error> {
- // Validate parameters according to KV store requirements
- validate_kvstore_params(primary_namespace, secondary_namespace, key)?;
- let current_time = unix_time();
- query(
- r#"
- INSERT INTO kv_store
- (primary_namespace, secondary_namespace, key, value, created_time, updated_time)
- VALUES (:primary_namespace, :secondary_namespace, :key, :value, :created_time, :updated_time)
- ON CONFLICT(primary_namespace, secondary_namespace, key)
- DO UPDATE SET
- value = excluded.value,
- updated_time = excluded.updated_time
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .bind("key", key.to_owned())
- .bind("value", value.to_vec())
- .bind("created_time", current_time as i64)
- .bind("updated_time", current_time as i64)
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn kv_remove(
- &mut self,
- primary_namespace: &str,
- secondary_namespace: &str,
- key: &str,
- ) -> Result<(), Error> {
- // Validate parameters according to KV store requirements
- validate_kvstore_params(primary_namespace, secondary_namespace, key)?;
- query(
- r#"
- DELETE FROM kv_store
- WHERE primary_namespace = :primary_namespace
- AND secondary_namespace = :secondary_namespace
- AND key = :key
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .bind("key", key.to_owned())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn kv_list(
- &mut self,
- primary_namespace: &str,
- secondary_namespace: &str,
- ) -> Result<Vec<String>, Error> {
- // Validate namespace parameters according to KV store requirements
- cdk_common::database::mint::validate_kvstore_string(primary_namespace)?;
- cdk_common::database::mint::validate_kvstore_string(secondary_namespace)?;
- // Check empty namespace rules
- if primary_namespace.is_empty() && !secondary_namespace.is_empty() {
- return Err(Error::KVStoreInvalidKey(
- "If primary_namespace is empty, secondary_namespace must also be empty".to_string(),
- ));
- }
- Ok(query(
- r#"
- SELECT key
- FROM kv_store
- WHERE primary_namespace = :primary_namespace
- AND secondary_namespace = :secondary_namespace
- ORDER BY key
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .fetch_all(&self.inner)
- .await?
- .into_iter()
- .map(|row| Ok(column_as_string!(&row[0])))
- .collect::<Result<Vec<_>, Error>>()?)
- }
- }
- #[async_trait]
- impl<RM> database::MintKVStoreDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn kv_read(
- &self,
- primary_namespace: &str,
- secondary_namespace: &str,
- key: &str,
- ) -> Result<Option<Vec<u8>>, Error> {
- // Validate parameters according to KV store requirements
- validate_kvstore_params(primary_namespace, secondary_namespace, key)?;
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT value
- FROM kv_store
- WHERE primary_namespace = :primary_namespace
- AND secondary_namespace = :secondary_namespace
- AND key = :key
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .bind("key", key.to_owned())
- .pluck(&*conn)
- .await?
- .and_then(|col| match col {
- Column::Blob(data) => Some(data),
- _ => None,
- }))
- }
- async fn kv_list(
- &self,
- primary_namespace: &str,
- secondary_namespace: &str,
- ) -> Result<Vec<String>, Error> {
- // Validate namespace parameters according to KV store requirements
- cdk_common::database::mint::validate_kvstore_string(primary_namespace)?;
- cdk_common::database::mint::validate_kvstore_string(secondary_namespace)?;
- // Check empty namespace rules
- if primary_namespace.is_empty() && !secondary_namespace.is_empty() {
- return Err(Error::KVStoreInvalidKey(
- "If primary_namespace is empty, secondary_namespace must also be empty".to_string(),
- ));
- }
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT key
- FROM kv_store
- WHERE primary_namespace = :primary_namespace
- AND secondary_namespace = :secondary_namespace
- ORDER BY key
- "#,
- )?
- .bind("primary_namespace", primary_namespace.to_owned())
- .bind("secondary_namespace", secondary_namespace.to_owned())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|row| Ok(column_as_string!(&row[0])))
- .collect::<Result<Vec<_>, Error>>()?)
- }
- }
- #[async_trait]
- impl<RM> database::MintKVStore for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- async fn begin_transaction<'a>(
- &'a self,
- ) -> Result<Box<dyn database::MintKVStoreTransaction<'a, Self::Err> + Send + Sync + 'a>, Error>
- {
- Ok(Box::new(SQLTransaction {
- inner: ConnectionWithTransaction::new(
- self.pool.get().map_err(|e| Error::Database(Box::new(e)))?,
- )
- .await?,
- }))
- }
- }
- #[async_trait]
- impl<RM> SagaTransaction<'_> for SQLTransaction<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn get_saga(
- &mut self,
- operation_id: &uuid::Uuid,
- ) -> Result<Option<mint::Saga>, Self::Err> {
- Ok(query(
- r#"
- SELECT
- operation_id,
- operation_kind,
- state,
- blinded_secrets,
- input_ys,
- quote_id,
- created_at,
- updated_at
- FROM
- saga_state
- WHERE
- operation_id = :operation_id
- FOR UPDATE
- "#,
- )?
- .bind("operation_id", operation_id.to_string())
- .fetch_one(&self.inner)
- .await?
- .map(sql_row_to_saga)
- .transpose()?)
- }
- async fn add_saga(&mut self, saga: &mint::Saga) -> Result<(), Self::Err> {
- let current_time = unix_time();
- let blinded_secrets_json = serde_json::to_string(&saga.blinded_secrets)
- .map_err(|e| Error::Internal(format!("Failed to serialize blinded_secrets: {e}")))?;
- let input_ys_json = serde_json::to_string(&saga.input_ys)
- .map_err(|e| Error::Internal(format!("Failed to serialize input_ys: {e}")))?;
- query(
- r#"
- INSERT INTO saga_state
- (operation_id, operation_kind, state, blinded_secrets, input_ys, quote_id, created_at, updated_at)
- VALUES
- (:operation_id, :operation_kind, :state, :blinded_secrets, :input_ys, :quote_id, :created_at, :updated_at)
- "#,
- )?
- .bind("operation_id", saga.operation_id.to_string())
- .bind("operation_kind", saga.operation_kind.to_string())
- .bind("state", saga.state.state())
- .bind("blinded_secrets", blinded_secrets_json)
- .bind("input_ys", input_ys_json)
- .bind("quote_id", saga.quote_id.as_deref())
- .bind("created_at", saga.created_at as i64)
- .bind("updated_at", current_time as i64)
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn update_saga(
- &mut self,
- operation_id: &uuid::Uuid,
- new_state: mint::SagaStateEnum,
- ) -> Result<(), Self::Err> {
- let current_time = unix_time();
- query(
- r#"
- UPDATE saga_state
- SET state = :state, updated_at = :updated_at
- WHERE operation_id = :operation_id
- "#,
- )?
- .bind("state", new_state.state())
- .bind("updated_at", current_time as i64)
- .bind("operation_id", operation_id.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- async fn delete_saga(&mut self, operation_id: &uuid::Uuid) -> Result<(), Self::Err> {
- query(
- r#"
- DELETE FROM saga_state
- WHERE operation_id = :operation_id
- "#,
- )?
- .bind("operation_id", operation_id.to_string())
- .execute(&self.inner)
- .await?;
- Ok(())
- }
- }
- #[async_trait]
- impl<RM> SagaDatabase for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = Error;
- async fn get_incomplete_sagas(
- &self,
- operation_kind: mint::OperationKind,
- ) -> Result<Vec<mint::Saga>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- operation_id,
- operation_kind,
- state,
- blinded_secrets,
- input_ys,
- quote_id,
- created_at,
- updated_at
- FROM
- saga_state
- WHERE
- operation_kind = :operation_kind
- ORDER BY created_at ASC
- "#,
- )?
- .bind("operation_kind", operation_kind.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_saga)
- .collect::<Result<Vec<_>, _>>()?)
- }
- }
- #[async_trait]
- impl<RM> MintDatabase<Error> for SQLMintDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- async fn begin_transaction<'a>(
- &'a self,
- ) -> Result<Box<dyn database::MintTransaction<'a, Error> + Send + Sync + 'a>, Error> {
- let tx = SQLTransaction {
- inner: ConnectionWithTransaction::new(
- self.pool.get().map_err(|e| Error::Database(Box::new(e)))?,
- )
- .await?,
- };
- Ok(Box::new(tx))
- }
- }
- fn sql_row_to_keyset_info(row: Vec<Column>) -> Result<MintKeySetInfo, Error> {
- unpack_into!(
- let (
- id,
- unit,
- active,
- valid_from,
- valid_to,
- derivation_path,
- derivation_path_index,
- amounts,
- row_keyset_ppk
- ) = row
- );
- let amounts = column_as_nullable_string!(amounts)
- .and_then(|str| serde_json::from_str(&str).ok())
- .ok_or_else(|| Error::Database("amounts field is required".to_string().into()))?;
- Ok(MintKeySetInfo {
- id: column_as_string!(id, Id::from_str, Id::from_bytes),
- unit: column_as_string!(unit, CurrencyUnit::from_str),
- active: matches!(active, Column::Integer(1)),
- valid_from: column_as_number!(valid_from),
- derivation_path: column_as_string!(derivation_path, DerivationPath::from_str),
- derivation_path_index: column_as_nullable_number!(derivation_path_index),
- amounts,
- input_fee_ppk: column_as_number!(row_keyset_ppk),
- final_expiry: column_as_nullable_number!(valid_to),
- })
- }
- #[instrument(skip_all)]
- fn sql_row_to_mint_quote(
- row: Vec<Column>,
- payments: Vec<IncomingPayment>,
- issueances: Vec<Issuance>,
- ) -> Result<MintQuote, Error> {
- unpack_into!(
- let (
- id, amount, unit, request, expiry, request_lookup_id,
- pubkey, created_time, amount_paid, amount_issued, payment_method, request_lookup_id_kind
- ) = row
- );
- let request_str = column_as_string!(&request);
- let request_lookup_id = column_as_nullable_string!(&request_lookup_id).unwrap_or_else(|| {
- Bolt11Invoice::from_str(&request_str)
- .map(|invoice| invoice.payment_hash().to_string())
- .unwrap_or_else(|_| request_str.clone())
- });
- let request_lookup_id_kind = column_as_string!(request_lookup_id_kind);
- let pubkey = column_as_nullable_string!(&pubkey)
- .map(|pk| PublicKey::from_hex(&pk))
- .transpose()?;
- let id = column_as_string!(id);
- let amount: Option<u64> = column_as_nullable_number!(amount);
- let amount_paid: u64 = column_as_number!(amount_paid);
- let amount_issued: u64 = column_as_number!(amount_issued);
- let payment_method = column_as_string!(payment_method, PaymentMethod::from_str);
- Ok(MintQuote::new(
- Some(QuoteId::from_str(&id)?),
- request_str,
- column_as_string!(unit, CurrencyUnit::from_str),
- amount.map(Amount::from),
- column_as_number!(expiry),
- PaymentIdentifier::new(&request_lookup_id_kind, &request_lookup_id)
- .map_err(|_| ConversionError::MissingParameter("Payment id".to_string()))?,
- pubkey,
- amount_paid.into(),
- amount_issued.into(),
- payment_method,
- column_as_number!(created_time),
- payments,
- issueances,
- ))
- }
- fn sql_row_to_melt_quote(row: Vec<Column>) -> Result<mint::MeltQuote, Error> {
- unpack_into!(
- let (
- id,
- unit,
- amount,
- request,
- fee_reserve,
- expiry,
- state,
- payment_preimage,
- request_lookup_id,
- created_time,
- paid_time,
- payment_method,
- options,
- request_lookup_id_kind
- ) = row
- );
- let id = column_as_string!(id);
- let amount: u64 = column_as_number!(amount);
- let fee_reserve: u64 = column_as_number!(fee_reserve);
- let expiry = column_as_number!(expiry);
- let payment_preimage = column_as_nullable_string!(payment_preimage);
- let options = column_as_nullable_string!(options);
- let options = options.and_then(|o| serde_json::from_str(&o).ok());
- let created_time: i64 = column_as_number!(created_time);
- let paid_time = column_as_nullable_number!(paid_time);
- let payment_method = PaymentMethod::from_str(&column_as_string!(payment_method))?;
- let state =
- MeltQuoteState::from_str(&column_as_string!(&state)).map_err(ConversionError::from)?;
- let unit = column_as_string!(unit);
- let request = column_as_string!(request);
- let request_lookup_id_kind = column_as_nullable_string!(request_lookup_id_kind);
- let request_lookup_id = column_as_nullable_string!(&request_lookup_id).or_else(|| {
- Bolt11Invoice::from_str(&request)
- .ok()
- .map(|invoice| invoice.payment_hash().to_string())
- });
- let request_lookup_id = if let (Some(id_kind), Some(request_lookup_id)) =
- (request_lookup_id_kind, request_lookup_id)
- {
- Some(
- PaymentIdentifier::new(&id_kind, &request_lookup_id)
- .map_err(|_| ConversionError::MissingParameter("Payment id".to_string()))?,
- )
- } else {
- None
- };
- let request = match serde_json::from_str(&request) {
- Ok(req) => req,
- Err(err) => {
- tracing::debug!(
- "Melt quote from pre migrations defaulting to bolt11 {}.",
- err
- );
- let bolt11 = Bolt11Invoice::from_str(&request).unwrap();
- MeltPaymentRequest::Bolt11 { bolt11 }
- }
- };
- Ok(MeltQuote {
- id: QuoteId::from_str(&id)?,
- unit: CurrencyUnit::from_str(&unit)?,
- amount: Amount::from(amount),
- request,
- fee_reserve: Amount::from(fee_reserve),
- state,
- expiry,
- payment_preimage,
- request_lookup_id,
- options,
- created_time: created_time as u64,
- paid_time,
- payment_method,
- })
- }
- fn sql_row_to_proof(row: Vec<Column>) -> Result<Proof, Error> {
- unpack_into!(
- let (
- amount,
- keyset_id,
- secret,
- c,
- witness
- ) = row
- );
- let amount: u64 = column_as_number!(amount);
- Ok(Proof {
- amount: Amount::from(amount),
- keyset_id: column_as_string!(keyset_id, Id::from_str),
- secret: column_as_string!(secret, Secret::from_str),
- c: column_as_string!(c, PublicKey::from_hex, PublicKey::from_slice),
- witness: column_as_nullable_string!(witness).and_then(|w| serde_json::from_str(&w).ok()),
- dleq: None,
- })
- }
- fn sql_row_to_hashmap_amount(row: Vec<Column>) -> Result<(Id, Amount), Error> {
- unpack_into!(
- let (
- keyset_id, amount
- ) = row
- );
- let amount: u64 = column_as_number!(amount);
- Ok((
- column_as_string!(keyset_id, Id::from_str, Id::from_bytes),
- Amount::from(amount),
- ))
- }
- fn sql_row_to_proof_with_state(row: Vec<Column>) -> Result<(Proof, Option<State>), Error> {
- unpack_into!(
- let (
- keyset_id, amount, secret, c, witness, state
- ) = row
- );
- let amount: u64 = column_as_number!(amount);
- let state = column_as_nullable_string!(state).and_then(|s| State::from_str(&s).ok());
- Ok((
- Proof {
- amount: Amount::from(amount),
- keyset_id: column_as_string!(keyset_id, Id::from_str, Id::from_bytes),
- secret: column_as_string!(secret, Secret::from_str),
- c: column_as_string!(c, PublicKey::from_hex, PublicKey::from_slice),
- witness: column_as_nullable_string!(witness)
- .and_then(|w| serde_json::from_str(&w).ok()),
- dleq: None,
- },
- state,
- ))
- }
- fn sql_row_to_blind_signature(row: Vec<Column>) -> Result<BlindSignature, Error> {
- unpack_into!(
- let (
- keyset_id, amount, c, dleq_e, dleq_s
- ) = row
- );
- let dleq = match (
- column_as_nullable_string!(dleq_e),
- column_as_nullable_string!(dleq_s),
- ) {
- (Some(e), Some(s)) => Some(BlindSignatureDleq {
- e: SecretKey::from_hex(e)?,
- s: SecretKey::from_hex(s)?,
- }),
- _ => None,
- };
- let amount: u64 = column_as_number!(amount);
- Ok(BlindSignature {
- amount: Amount::from(amount),
- keyset_id: column_as_string!(keyset_id, Id::from_str, Id::from_bytes),
- c: column_as_string!(c, PublicKey::from_hex, PublicKey::from_slice),
- dleq,
- })
- }
- fn sql_row_to_saga(row: Vec<Column>) -> Result<mint::Saga, Error> {
- unpack_into!(
- let (
- operation_id,
- operation_kind,
- state,
- blinded_secrets,
- input_ys,
- quote_id,
- created_at,
- updated_at
- ) = row
- );
- let operation_id_str = column_as_string!(&operation_id);
- let operation_id = uuid::Uuid::parse_str(&operation_id_str)
- .map_err(|e| Error::Internal(format!("Invalid operation_id UUID: {e}")))?;
- let operation_kind_str = column_as_string!(&operation_kind);
- let operation_kind = mint::OperationKind::from_str(&operation_kind_str)
- .map_err(|e| Error::Internal(format!("Invalid operation kind: {e}")))?;
- let state_str = column_as_string!(&state);
- let state = mint::SagaStateEnum::new(operation_kind, &state_str)
- .map_err(|e| Error::Internal(format!("Invalid saga state: {e}")))?;
- let blinded_secrets_str = column_as_string!(&blinded_secrets);
- let blinded_secrets: Vec<PublicKey> = serde_json::from_str(&blinded_secrets_str)
- .map_err(|e| Error::Internal(format!("Failed to deserialize blinded_secrets: {e}")))?;
- let input_ys_str = column_as_string!(&input_ys);
- let input_ys: Vec<PublicKey> = serde_json::from_str(&input_ys_str)
- .map_err(|e| Error::Internal(format!("Failed to deserialize input_ys: {e}")))?;
- let quote_id = match "e_id {
- Column::Text(s) => {
- if s.is_empty() {
- None
- } else {
- Some(s.clone())
- }
- }
- Column::Null => None,
- _ => None,
- };
- let created_at: u64 = column_as_number!(created_at);
- let updated_at: u64 = column_as_number!(updated_at);
- Ok(mint::Saga {
- operation_id,
- operation_kind,
- state,
- blinded_secrets,
- input_ys,
- quote_id,
- created_at,
- updated_at,
- })
- }
- #[cfg(test)]
- mod test {
- use super::*;
- mod keyset_amounts_tests {
- use super::*;
- #[test]
- fn keyset_with_amounts() {
- let amounts = (0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>();
- let result = sql_row_to_keyset_info(vec![
- Column::Text("0083a60439303340".to_owned()),
- Column::Text("sat".to_owned()),
- Column::Integer(1),
- Column::Integer(1749844864),
- Column::Null,
- Column::Text("0'/0'/0'".to_owned()),
- Column::Integer(0),
- Column::Text(serde_json::to_string(&amounts).expect("valid json")),
- Column::Integer(0),
- ]);
- assert!(result.is_ok());
- let keyset = result.unwrap();
- assert_eq!(keyset.amounts.len(), 32);
- }
- }
- }
|