12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259 |
- //! SQLite Wallet Database
- use std::collections::HashMap;
- use std::fmt::Debug;
- use std::str::FromStr;
- use std::sync::Arc;
- use async_trait::async_trait;
- use cdk_common::common::ProofInfo;
- use cdk_common::database::{ConversionError, Error, WalletDatabase};
- use cdk_common::mint_url::MintUrl;
- use cdk_common::nuts::{MeltQuoteState, MintQuoteState};
- use cdk_common::secret::Secret;
- use cdk_common::wallet::{self, MintQuote, Transaction, TransactionDirection, TransactionId};
- use cdk_common::{
- database, Amount, CurrencyUnit, Id, KeySet, KeySetInfo, Keys, MintInfo, PaymentMethod, Proof,
- ProofDleq, PublicKey, SecretKey, SpendingConditions, State,
- };
- 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_binary, column_as_nullable_binary, column_as_nullable_number,
- column_as_nullable_string, column_as_number, column_as_string, unpack_into,
- };
- #[rustfmt::skip]
- mod migrations;
- /// Wallet SQLite Database
- #[derive(Debug, Clone)]
- pub struct SQLWalletDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- pool: Arc<Pool<RM>>,
- }
- impl<RM> SQLWalletDatabase<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 [`WalletSqliteDatabase`]
- async fn migrate(conn: PooledResource<RM>) -> Result<(), Error> {
- let tx = ConnectionWithTransaction::new(conn).await?;
- migrate(&tx, RM::Connection::name(), migrations::MIGRATIONS).await?;
- // Update any existing keys with missing keyset_u32 values
- Self::add_keyset_u32(&tx).await?;
- tx.commit().await?;
- Ok(())
- }
- async fn add_keyset_u32<T>(conn: &T) -> Result<(), Error>
- where
- T: DatabaseExecutor,
- {
- // First get the keysets where keyset_u32 on key is null
- let keys_without_u32: Vec<Vec<Column>> = query(
- r#"
- SELECT
- id
- FROM key
- WHERE keyset_u32 IS NULL
- "#,
- )?
- .fetch_all(conn)
- .await?;
- for id in keys_without_u32 {
- let id = column_as_string!(id.first().unwrap());
- if let Ok(id) = Id::from_str(&id) {
- query(
- r#"
- UPDATE
- key
- SET keyset_u32 = :u32_keyset
- WHERE id = :keyset_id
- "#,
- )?
- .bind("u32_keyset", u32::from(id))
- .bind("keyset_id", id.to_string())
- .execute(conn)
- .await?;
- }
- }
- // Also update keysets where keyset_u32 is null
- let keysets_without_u32: Vec<Vec<Column>> = query(
- r#"
- SELECT
- id
- FROM keyset
- WHERE keyset_u32 IS NULL
- "#,
- )?
- .fetch_all(conn)
- .await?;
- for id in keysets_without_u32 {
- let id = column_as_string!(id.first().unwrap());
- if let Ok(id) = Id::from_str(&id) {
- query(
- r#"
- UPDATE
- keyset
- SET keyset_u32 = :u32_keyset
- WHERE id = :keyset_id
- "#,
- )?
- .bind("u32_keyset", u32::from(id))
- .bind("keyset_id", id.to_string())
- .execute(conn)
- .await?;
- }
- }
- Ok(())
- }
- }
- #[async_trait]
- impl<RM> WalletDatabase for SQLWalletDatabase<RM>
- where
- RM: DatabasePool + 'static,
- {
- type Err = database::Error;
- #[instrument(skip(self))]
- async fn get_melt_quotes(&self) -> Result<Vec<wallet::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,
- state,
- expiry,
- payment_preimage,
- payment_method
- FROM
- melt_quote
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_melt_quote)
- .collect::<Result<_, _>>()?)
- }
- #[instrument(skip(self, mint_info))]
- async fn add_mint(
- &self,
- mint_url: MintUrl,
- mint_info: Option<MintInfo>,
- ) -> Result<(), Self::Err> {
- let (
- name,
- pubkey,
- version,
- description,
- description_long,
- contact,
- nuts,
- icon_url,
- urls,
- motd,
- time,
- tos_url,
- ) = match mint_info {
- Some(mint_info) => {
- let MintInfo {
- name,
- pubkey,
- version,
- description,
- description_long,
- contact,
- nuts,
- icon_url,
- urls,
- motd,
- time,
- tos_url,
- } = mint_info;
- (
- name,
- pubkey.map(|p| p.to_bytes().to_vec()),
- version.map(|v| serde_json::to_string(&v).ok()),
- description,
- description_long,
- contact.map(|c| serde_json::to_string(&c).ok()),
- serde_json::to_string(&nuts).ok(),
- icon_url,
- urls.map(|c| serde_json::to_string(&c).ok()),
- motd,
- time,
- tos_url,
- )
- }
- None => (
- None, None, None, None, None, None, None, None, None, None, None, None,
- ),
- };
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- INSERT INTO mint
- (
- mint_url, name, pubkey, version, description, description_long,
- contact, nuts, icon_url, urls, motd, mint_time, tos_url
- )
- VALUES
- (
- :mint_url, :name, :pubkey, :version, :description, :description_long,
- :contact, :nuts, :icon_url, :urls, :motd, :mint_time, :tos_url
- )
- ON CONFLICT(mint_url) DO UPDATE SET
- name = excluded.name,
- pubkey = excluded.pubkey,
- version = excluded.version,
- description = excluded.description,
- description_long = excluded.description_long,
- contact = excluded.contact,
- nuts = excluded.nuts,
- icon_url = excluded.icon_url,
- urls = excluded.urls,
- motd = excluded.motd,
- mint_time = excluded.mint_time,
- tos_url = excluded.tos_url
- ;
- "#,
- )?
- .bind("mint_url", mint_url.to_string())
- .bind("name", name)
- .bind("pubkey", pubkey)
- .bind("version", version)
- .bind("description", description)
- .bind("description_long", description_long)
- .bind("contact", contact)
- .bind("nuts", nuts)
- .bind("icon_url", icon_url)
- .bind("urls", urls)
- .bind("motd", motd)
- .bind("mint_time", time.map(|v| v as i64))
- .bind("tos_url", tos_url)
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn remove_mint(&self, mint_url: MintUrl) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(r#"DELETE FROM mint WHERE mint_url=:mint_url"#)?
- .bind("mint_url", mint_url.to_string())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn get_mint(&self, mint_url: MintUrl) -> Result<Option<MintInfo>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- name,
- pubkey,
- version,
- description,
- description_long,
- contact,
- nuts,
- icon_url,
- motd,
- urls,
- mint_time,
- tos_url
- FROM
- mint
- WHERE mint_url = :mint_url
- "#,
- )?
- .bind("mint_url", mint_url.to_string())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_mint_info)
- .transpose()?)
- }
- #[instrument(skip(self))]
- async fn get_mints(&self) -> Result<HashMap<MintUrl, Option<MintInfo>>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- name,
- pubkey,
- version,
- description,
- description_long,
- contact,
- nuts,
- icon_url,
- motd,
- urls,
- mint_time,
- tos_url,
- mint_url
- FROM
- mint
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(|mut row| {
- let url = column_as_string!(
- row.pop().ok_or(ConversionError::MissingColumn(0, 1))?,
- MintUrl::from_str
- );
- Ok((url, sql_row_to_mint_info(row).ok()))
- })
- .collect::<Result<HashMap<_, _>, Error>>()?)
- }
- #[instrument(skip(self))]
- async fn update_mint_url(
- &self,
- old_mint_url: MintUrl,
- new_mint_url: MintUrl,
- ) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let tables = ["mint_quote", "proof"];
- for table in &tables {
- query(&format!(
- r#"
- UPDATE {table}
- SET mint_url = :new_mint_url
- WHERE mint_url = :old_mint_url
- "#
- ))?
- .bind("new_mint_url", new_mint_url.to_string())
- .bind("old_mint_url", old_mint_url.to_string())
- .execute(&*conn)
- .await?;
- }
- Ok(())
- }
- #[instrument(skip(self, keysets))]
- async fn add_mint_keysets(
- &self,
- mint_url: MintUrl,
- keysets: Vec<KeySetInfo>,
- ) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- for keyset in keysets {
- query(
- r#"
- INSERT INTO keyset
- (mint_url, id, unit, active, input_fee_ppk, final_expiry, keyset_u32)
- VALUES
- (:mint_url, :id, :unit, :active, :input_fee_ppk, :final_expiry, :keyset_u32)
- ON CONFLICT(id) DO UPDATE SET
- active = excluded.active,
- input_fee_ppk = excluded.input_fee_ppk
- "#,
- )?
- .bind("mint_url", mint_url.to_string())
- .bind("id", keyset.id.to_string())
- .bind("unit", keyset.unit.to_string())
- .bind("active", keyset.active)
- .bind("input_fee_ppk", keyset.input_fee_ppk as i64)
- .bind("final_expiry", keyset.final_expiry.map(|v| v as i64))
- .bind("keyset_u32", u32::from(keyset.id))
- .execute(&*conn)
- .await?;
- }
- Ok(())
- }
- #[instrument(skip(self))]
- async fn get_mint_keysets(
- &self,
- mint_url: MintUrl,
- ) -> Result<Option<Vec<KeySetInfo>>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let keysets = query(
- r#"
- SELECT
- id,
- unit,
- active,
- input_fee_ppk,
- final_expiry
- FROM
- keyset
- WHERE mint_url = :mint_url
- "#,
- )?
- .bind("mint_url", mint_url.to_string())
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_keyset)
- .collect::<Result<Vec<_>, Error>>()?;
- match keysets.is_empty() {
- false => Ok(Some(keysets)),
- true => Ok(None),
- }
- }
- #[instrument(skip(self), fields(keyset_id = %keyset_id))]
- async fn get_keyset_by_id(&self, keyset_id: &Id) -> Result<Option<KeySetInfo>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- id,
- unit,
- active,
- input_fee_ppk,
- final_expiry
- FROM
- keyset
- WHERE id = :id
- "#,
- )?
- .bind("id", keyset_id.to_string())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_keyset)
- .transpose()?)
- }
- #[instrument(skip_all)]
- async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- INSERT INTO mint_quote
- (id, mint_url, amount, unit, request, state, expiry, secret_key, payment_method, amount_issued, amount_paid)
- VALUES
- (:id, :mint_url, :amount, :unit, :request, :state, :expiry, :secret_key, :payment_method, :amount_issued, :amount_paid)
- ON CONFLICT(id) DO UPDATE SET
- mint_url = excluded.mint_url,
- amount = excluded.amount,
- unit = excluded.unit,
- request = excluded.request,
- state = excluded.state,
- expiry = excluded.expiry,
- secret_key = excluded.secret_key,
- payment_method = excluded.payment_method,
- amount_issued = excluded.amount_issued,
- amount_paid = excluded.amount_paid
- ;
- "#,
- )?
- .bind("id", quote.id.to_string())
- .bind("mint_url", quote.mint_url.to_string())
- .bind("amount", quote.amount.map(|a| a.to_i64()))
- .bind("unit", quote.unit.to_string())
- .bind("request", quote.request)
- .bind("state", quote.state.to_string())
- .bind("expiry", quote.expiry as i64)
- .bind("secret_key", quote.secret_key.map(|p| p.to_string()))
- .bind("payment_method", quote.payment_method.to_string())
- .bind("amount_issued", quote.amount_issued.to_i64())
- .bind("amount_paid", quote.amount_paid.to_i64())
- .execute(&*conn).await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- id,
- mint_url,
- amount,
- unit,
- request,
- state,
- expiry,
- secret_key,
- payment_method,
- amount_issued,
- amount_paid
- FROM
- mint_quote
- WHERE
- id = :id
- "#,
- )?
- .bind("id", quote_id.to_string())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_mint_quote)
- .transpose()?)
- }
- #[instrument(skip(self))]
- async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- id,
- mint_url,
- amount,
- unit,
- request,
- state,
- expiry,
- secret_key
- payment_method,
- amount_issued,
- amount_paid
- FROM
- mint_quote
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .map(sql_row_to_mint_quote)
- .collect::<Result<_, _>>()?)
- }
- #[instrument(skip(self))]
- async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(r#"DELETE FROM mint_quote WHERE id=:id"#)?
- .bind("id", quote_id.to_string())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip_all)]
- async fn add_melt_quote(&self, quote: wallet::MeltQuote) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- INSERT INTO melt_quote
- (id, unit, amount, request, fee_reserve, state, expiry, payment_method)
- VALUES
- (:id, :unit, :amount, :request, :fee_reserve, :state, :expiry, :payment_method)
- ON CONFLICT(id) DO UPDATE SET
- unit = excluded.unit,
- amount = excluded.amount,
- request = excluded.request,
- fee_reserve = excluded.fee_reserve,
- state = excluded.state,
- expiry = excluded.expiry,
- payment_method = excluded.payment_method
- ;
- "#,
- )?
- .bind("id", quote.id.to_string())
- .bind("unit", quote.unit.to_string())
- .bind("amount", u64::from(quote.amount) as i64)
- .bind("request", quote.request)
- .bind("fee_reserve", u64::from(quote.fee_reserve) as i64)
- .bind("state", quote.state.to_string())
- .bind("expiry", quote.expiry as i64)
- .bind("payment_method", quote.payment_method.to_string())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<wallet::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,
- state,
- expiry,
- payment_preimage,
- payment_method
- FROM
- melt_quote
- WHERE
- id=:id
- "#,
- )?
- .bind("id", quote_id.to_owned())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_melt_quote)
- .transpose()?)
- }
- #[instrument(skip(self))]
- async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(r#"DELETE FROM melt_quote WHERE id=:id"#)?
- .bind("id", quote_id.to_owned())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip_all)]
- async fn add_keys(&self, keyset: KeySet) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- // Recompute ID for verification
- keyset.verify_id()?;
- query(
- r#"
- INSERT INTO key
- (id, keys, keyset_u32)
- VALUES
- (:id, :keys, :keyset_u32)
- "#,
- )?
- .bind("id", keyset.id.to_string())
- .bind(
- "keys",
- serde_json::to_string(&keyset.keys).map_err(Error::from)?,
- )
- .bind("keyset_u32", u32::from(keyset.id))
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self), fields(keyset_id = %keyset_id))]
- async fn get_keys(&self, keyset_id: &Id) -> Result<Option<Keys>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- keys
- FROM key
- WHERE id = :id
- "#,
- )?
- .bind("id", keyset_id.to_string())
- .pluck(&*conn)
- .await?
- .map(|keys| {
- let keys = column_as_string!(keys);
- serde_json::from_str(&keys).map_err(Error::from)
- })
- .transpose()?)
- }
- #[instrument(skip(self))]
- async fn remove_keys(&self, id: &Id) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(r#"DELETE FROM key WHERE id = :id"#)?
- .bind("id", id.to_string())
- .pluck(&*conn)
- .await?;
- Ok(())
- }
- async fn update_proofs(
- &self,
- added: Vec<ProofInfo>,
- removed_ys: Vec<PublicKey>,
- ) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let tx = ConnectionWithTransaction::new(conn).await?;
- // TODO: Use a transaction for all these operations
- for proof in added {
- query(
- r#"
- INSERT INTO proof
- (y, mint_url, state, spending_condition, unit, amount, keyset_id, secret, c, witness, dleq_e, dleq_s, dleq_r)
- VALUES
- (:y, :mint_url, :state, :spending_condition, :unit, :amount, :keyset_id, :secret, :c, :witness, :dleq_e, :dleq_s, :dleq_r)
- ON CONFLICT(y) DO UPDATE SET
- mint_url = excluded.mint_url,
- state = excluded.state,
- spending_condition = excluded.spending_condition,
- unit = excluded.unit,
- amount = excluded.amount,
- keyset_id = excluded.keyset_id,
- secret = excluded.secret,
- c = excluded.c,
- witness = excluded.witness,
- dleq_e = excluded.dleq_e,
- dleq_s = excluded.dleq_s,
- dleq_r = excluded.dleq_r
- ;
- "#,
- )?
- .bind("y", proof.y.to_bytes().to_vec())
- .bind("mint_url", proof.mint_url.to_string())
- .bind("state",proof.state.to_string())
- .bind(
- "spending_condition",
- proof
- .spending_condition
- .map(|s| serde_json::to_string(&s).ok()),
- )
- .bind("unit", proof.unit.to_string())
- .bind("amount", u64::from(proof.proof.amount) as i64)
- .bind("keyset_id", proof.proof.keyset_id.to_string())
- .bind("secret", proof.proof.secret.to_string())
- .bind("c", proof.proof.c.to_bytes().to_vec())
- .bind(
- "witness",
- proof
- .proof
- .witness
- .map(|w| serde_json::to_string(&w).unwrap()),
- )
- .bind(
- "dleq_e",
- proof.proof.dleq.as_ref().map(|dleq| dleq.e.to_secret_bytes().to_vec()),
- )
- .bind(
- "dleq_s",
- proof.proof.dleq.as_ref().map(|dleq| dleq.s.to_secret_bytes().to_vec()),
- )
- .bind(
- "dleq_r",
- proof.proof.dleq.as_ref().map(|dleq| dleq.r.to_secret_bytes().to_vec()),
- )
- .execute(&tx).await?;
- }
- query(r#"DELETE FROM proof WHERE y IN (:ys)"#)?
- .bind_vec(
- "ys",
- removed_ys.iter().map(|y| y.to_bytes().to_vec()).collect(),
- )
- .execute(&tx)
- .await?;
- tx.commit().await?;
- Ok(())
- }
- #[instrument(skip(self, state, spending_conditions))]
- async fn get_proofs(
- &self,
- mint_url: Option<MintUrl>,
- unit: Option<CurrencyUnit>,
- state: Option<Vec<State>>,
- spending_conditions: Option<Vec<SpendingConditions>>,
- ) -> Result<Vec<ProofInfo>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- amount,
- unit,
- keyset_id,
- secret,
- c,
- witness,
- dleq_e,
- dleq_s,
- dleq_r,
- y,
- mint_url,
- state,
- spending_condition
- FROM proof
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .filter_map(|row| {
- let row = sql_row_to_proof_info(row).ok()?;
- if row.matches_conditions(&mint_url, &unit, &state, &spending_conditions) {
- Some(row)
- } else {
- None
- }
- })
- .collect::<Vec<_>>())
- }
- async fn update_proofs_state(&self, ys: Vec<PublicKey>, state: State) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query("UPDATE proof SET state = :state WHERE y IN (:ys)")?
- .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
- .bind("state", state.to_string())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self), fields(keyset_id = %keyset_id))]
- async fn increment_keyset_counter(&self, keyset_id: &Id, count: u32) -> Result<u32, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let tx = ConnectionWithTransaction::new(conn).await?;
- // Lock the row and get current counter
- let current_counter = query(
- r#"
- SELECT counter
- FROM keyset
- WHERE id=:id
- FOR UPDATE
- "#,
- )?
- .bind("id", keyset_id.to_string())
- .pluck(&tx)
- .await?
- .map(|n| Ok::<_, Error>(column_as_number!(n)))
- .transpose()?
- .unwrap_or(0);
- let new_counter = current_counter + count;
- // Update with the new counter value
- query(
- r#"
- UPDATE keyset
- SET counter=:new_counter
- WHERE id=:id
- "#,
- )?
- .bind("new_counter", new_counter)
- .bind("id", keyset_id.to_string())
- .execute(&tx)
- .await?;
- tx.commit().await?;
- Ok(new_counter)
- }
- #[instrument(skip(self))]
- async fn add_transaction(&self, transaction: Transaction) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mint_url = transaction.mint_url.to_string();
- let direction = transaction.direction.to_string();
- let unit = transaction.unit.to_string();
- let amount = u64::from(transaction.amount) as i64;
- let fee = u64::from(transaction.fee) as i64;
- let ys = transaction
- .ys
- .iter()
- .flat_map(|y| y.to_bytes().to_vec())
- .collect::<Vec<_>>();
- query(
- r#"
- INSERT INTO transactions
- (id, mint_url, direction, unit, amount, fee, ys, timestamp, memo, metadata, quote_id)
- VALUES
- (:id, :mint_url, :direction, :unit, :amount, :fee, :ys, :timestamp, :memo, :metadata, :quote_id)
- ON CONFLICT(id) DO UPDATE SET
- mint_url = excluded.mint_url,
- direction = excluded.direction,
- unit = excluded.unit,
- amount = excluded.amount,
- fee = excluded.fee,
- ys = excluded.ys,
- timestamp = excluded.timestamp,
- memo = excluded.memo,
- metadata = excluded.metadata,
- quote_id = excluded.quote_id
- ;
- "#,
- )?
- .bind("id", transaction.id().as_slice().to_vec())
- .bind("mint_url", mint_url)
- .bind("direction", direction)
- .bind("unit", unit)
- .bind("amount", amount)
- .bind("fee", fee)
- .bind("ys", ys)
- .bind("timestamp", transaction.timestamp as i64)
- .bind("memo", transaction.memo)
- .bind(
- "metadata",
- serde_json::to_string(&transaction.metadata).map_err(Error::from)?,
- )
- .bind("quote_id", transaction.quote_id)
- .execute(&*conn)
- .await?;
- Ok(())
- }
- #[instrument(skip(self))]
- async fn get_transaction(
- &self,
- transaction_id: TransactionId,
- ) -> Result<Option<Transaction>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- mint_url,
- direction,
- unit,
- amount,
- fee,
- ys,
- timestamp,
- memo,
- metadata,
- quote_id
- FROM
- transactions
- WHERE
- id = :id
- "#,
- )?
- .bind("id", transaction_id.as_slice().to_vec())
- .fetch_one(&*conn)
- .await?
- .map(sql_row_to_transaction)
- .transpose()?)
- }
- #[instrument(skip(self))]
- async fn list_transactions(
- &self,
- mint_url: Option<MintUrl>,
- direction: Option<TransactionDirection>,
- unit: Option<CurrencyUnit>,
- ) -> Result<Vec<Transaction>, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- Ok(query(
- r#"
- SELECT
- mint_url,
- direction,
- unit,
- amount,
- fee,
- ys,
- timestamp,
- memo,
- metadata,
- quote_id
- FROM
- transactions
- "#,
- )?
- .fetch_all(&*conn)
- .await?
- .into_iter()
- .filter_map(|row| {
- // TODO: Avoid a table scan by passing the heavy lifting of checking to the DB engine
- let transaction = sql_row_to_transaction(row).ok()?;
- if transaction.matches_conditions(&mint_url, &direction, &unit) {
- Some(transaction)
- } else {
- None
- }
- })
- .collect::<Vec<_>>())
- }
- #[instrument(skip(self))]
- async fn remove_transaction(&self, transaction_id: TransactionId) -> Result<(), Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(r#"DELETE FROM transactions WHERE id=:id"#)?
- .bind("id", transaction_id.as_slice().to_vec())
- .execute(&*conn)
- .await?;
- Ok(())
- }
- }
- fn sql_row_to_mint_info(row: Vec<Column>) -> Result<MintInfo, Error> {
- unpack_into!(
- let (
- name,
- pubkey,
- version,
- description,
- description_long,
- contact,
- nuts,
- icon_url,
- motd,
- urls,
- mint_time,
- tos_url
- ) = row
- );
- Ok(MintInfo {
- name: column_as_nullable_string!(&name),
- pubkey: column_as_nullable_string!(&pubkey, |v| serde_json::from_str(v).ok(), |v| {
- serde_json::from_slice(v).ok()
- }),
- version: column_as_nullable_string!(&version).and_then(|v| serde_json::from_str(&v).ok()),
- description: column_as_nullable_string!(description),
- description_long: column_as_nullable_string!(description_long),
- contact: column_as_nullable_string!(contact, |v| serde_json::from_str(&v).ok()),
- nuts: column_as_nullable_string!(nuts, |v| serde_json::from_str(&v).ok())
- .unwrap_or_default(),
- urls: column_as_nullable_string!(urls, |v| serde_json::from_str(&v).ok()),
- icon_url: column_as_nullable_string!(icon_url),
- motd: column_as_nullable_string!(motd),
- time: column_as_nullable_number!(mint_time).map(|t| t),
- tos_url: column_as_nullable_string!(tos_url),
- })
- }
- #[instrument(skip_all)]
- fn sql_row_to_keyset(row: Vec<Column>) -> Result<KeySetInfo, Error> {
- unpack_into!(
- let (
- id,
- unit,
- active,
- input_fee_ppk,
- final_expiry
- ) = row
- );
- Ok(KeySetInfo {
- 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)),
- input_fee_ppk: column_as_nullable_number!(input_fee_ppk).unwrap_or_default(),
- final_expiry: column_as_nullable_number!(final_expiry),
- })
- }
- fn sql_row_to_mint_quote(row: Vec<Column>) -> Result<MintQuote, Error> {
- unpack_into!(
- let (
- id,
- mint_url,
- amount,
- unit,
- request,
- state,
- expiry,
- secret_key,
- row_method,
- row_amount_minted,
- row_amount_paid
- ) = row
- );
- let amount: Option<i64> = column_as_nullable_number!(amount);
- let amount_paid: u64 = column_as_number!(row_amount_paid);
- let amount_minted: u64 = column_as_number!(row_amount_minted);
- let payment_method =
- PaymentMethod::from_str(&column_as_string!(row_method)).map_err(Error::from)?;
- Ok(MintQuote {
- id: column_as_string!(id),
- mint_url: column_as_string!(mint_url, MintUrl::from_str),
- amount: amount.and_then(Amount::from_i64),
- unit: column_as_string!(unit, CurrencyUnit::from_str),
- request: column_as_string!(request),
- state: column_as_string!(state, MintQuoteState::from_str),
- expiry: column_as_number!(expiry),
- secret_key: column_as_nullable_string!(secret_key)
- .map(|v| SecretKey::from_str(&v))
- .transpose()?,
- payment_method,
- amount_issued: amount_minted.into(),
- amount_paid: amount_paid.into(),
- })
- }
- fn sql_row_to_melt_quote(row: Vec<Column>) -> Result<wallet::MeltQuote, Error> {
- unpack_into!(
- let (
- id,
- unit,
- amount,
- request,
- fee_reserve,
- state,
- expiry,
- payment_preimage,
- row_method
- ) = row
- );
- let amount: u64 = column_as_number!(amount);
- let fee_reserve: u64 = column_as_number!(fee_reserve);
- let payment_method =
- PaymentMethod::from_str(&column_as_string!(row_method)).map_err(Error::from)?;
- Ok(wallet::MeltQuote {
- id: column_as_string!(id),
- amount: Amount::from(amount),
- unit: column_as_string!(unit, CurrencyUnit::from_str),
- request: column_as_string!(request),
- fee_reserve: Amount::from(fee_reserve),
- state: column_as_string!(state, MeltQuoteState::from_str),
- expiry: column_as_number!(expiry),
- payment_preimage: column_as_nullable_string!(payment_preimage),
- payment_method,
- })
- }
- fn sql_row_to_proof_info(row: Vec<Column>) -> Result<ProofInfo, Error> {
- unpack_into!(
- let (
- amount,
- unit,
- keyset_id,
- secret,
- c,
- witness,
- dleq_e,
- dleq_s,
- dleq_r,
- y,
- mint_url,
- state,
- spending_condition
- ) = row
- );
- let dleq = match (
- column_as_nullable_binary!(dleq_e),
- column_as_nullable_binary!(dleq_s),
- column_as_nullable_binary!(dleq_r),
- ) {
- (Some(e), Some(s), Some(r)) => {
- let e_key = SecretKey::from_slice(&e)?;
- let s_key = SecretKey::from_slice(&s)?;
- let r_key = SecretKey::from_slice(&r)?;
- Some(ProofDleq::new(e_key, s_key, r_key))
- }
- _ => None,
- };
- let amount: u64 = column_as_number!(amount);
- let proof = Proof {
- amount: Amount::from(amount),
- keyset_id: column_as_string!(keyset_id, Id::from_str),
- secret: column_as_string!(secret, Secret::from_str),
- witness: column_as_nullable_string!(witness, |v| { serde_json::from_str(&v).ok() }, |v| {
- serde_json::from_slice(&v).ok()
- }),
- c: column_as_string!(c, PublicKey::from_str, PublicKey::from_slice),
- dleq,
- };
- Ok(ProofInfo {
- proof,
- y: column_as_string!(y, PublicKey::from_str, PublicKey::from_slice),
- mint_url: column_as_string!(mint_url, MintUrl::from_str),
- state: column_as_string!(state, State::from_str),
- spending_condition: column_as_nullable_string!(
- spending_condition,
- |r| { serde_json::from_str(&r).ok() },
- |r| { serde_json::from_slice(&r).ok() }
- ),
- unit: column_as_string!(unit, CurrencyUnit::from_str),
- })
- }
- fn sql_row_to_transaction(row: Vec<Column>) -> Result<Transaction, Error> {
- unpack_into!(
- let (
- mint_url,
- direction,
- unit,
- amount,
- fee,
- ys,
- timestamp,
- memo,
- metadata,
- quote_id
- ) = row
- );
- let amount: u64 = column_as_number!(amount);
- let fee: u64 = column_as_number!(fee);
- Ok(Transaction {
- mint_url: column_as_string!(mint_url, MintUrl::from_str),
- direction: column_as_string!(direction, TransactionDirection::from_str),
- unit: column_as_string!(unit, CurrencyUnit::from_str),
- amount: Amount::from(amount),
- fee: Amount::from(fee),
- ys: column_as_binary!(ys)
- .chunks(33)
- .map(PublicKey::from_slice)
- .collect::<Result<Vec<_>, _>>()?,
- timestamp: column_as_number!(timestamp),
- memo: column_as_nullable_string!(memo),
- metadata: column_as_nullable_string!(metadata, |v| serde_json::from_str(&v).ok(), |v| {
- serde_json::from_slice(&v).ok()
- })
- .unwrap_or_default(),
- quote_id: column_as_nullable_string!(quote_id),
- })
- }
|