| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341 |
- //! 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 {
- include!(concat!(env!("OUT_DIR"), "/migrations_wallet.rs"));
- }
- /// 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?;
- }
- if !removed_ys.is_empty() {
- 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 get_balance(
- &self,
- mint_url: Option<MintUrl>,
- unit: Option<CurrencyUnit>,
- states: Option<Vec<State>>,
- ) -> Result<u64, Self::Err> {
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- let mut query_str = "SELECT COALESCE(SUM(amount), 0) as total FROM proof".to_string();
- let mut where_clauses = Vec::new();
- let states = states
- .unwrap_or_default()
- .into_iter()
- .map(|x| x.to_string())
- .collect::<Vec<_>>();
- if mint_url.is_some() {
- where_clauses.push("mint_url = :mint_url");
- }
- if unit.is_some() {
- where_clauses.push("unit = :unit");
- }
- if !states.is_empty() {
- where_clauses.push("state IN (:states)");
- }
- if !where_clauses.is_empty() {
- query_str.push_str(" WHERE ");
- query_str.push_str(&where_clauses.join(" AND "));
- }
- let mut q = query(&query_str)?;
- if let Some(ref mint_url) = mint_url {
- q = q.bind("mint_url", mint_url.to_string());
- }
- if let Some(ref unit) = unit {
- q = q.bind("unit", unit.to_string());
- }
- if !states.is_empty() {
- q = q.bind_vec("states", states);
- }
- let balance = q
- .pluck(&*conn)
- .await?
- .map(|n| {
- // SQLite SUM returns INTEGER which we need to convert to u64
- match n {
- crate::stmt::Column::Integer(i) => Ok(i as u64),
- crate::stmt::Column::Real(f) => Ok(f as u64),
- _ => Err(Error::Database(Box::new(std::io::Error::new(
- std::io::ErrorKind::InvalidData,
- "Invalid balance type",
- )))),
- }
- })
- .transpose()?
- .unwrap_or(0);
- Ok(balance)
- }
- 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 from keyset_counter table
- let current_counter = query(
- r#"
- SELECT counter
- FROM keyset_counter
- WHERE keyset_id=:keyset_id
- FOR UPDATE
- "#,
- )?
- .bind("keyset_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;
- // Upsert the new counter value
- query(
- r#"
- INSERT INTO keyset_counter (keyset_id, counter)
- VALUES (:keyset_id, :new_counter)
- ON CONFLICT(keyset_id) DO UPDATE SET
- counter = excluded.counter
- "#,
- )?
- .bind("keyset_id", keyset_id.to_string())
- .bind("new_counter", new_counter)
- .execute(&tx)
- .await?;
- tx.commit().await?;
- Ok(new_counter)
- }
- #[instrument(skip(self))]
- async fn add_transaction(&self, transaction: Transaction) -> Result<(), Self::Err> {
- 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<_>>();
- let id = transaction.id();
- let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
- query(
- r#"
- INSERT INTO transactions
- (id, mint_url, direction, unit, amount, fee, ys, timestamp, memo, metadata, quote_id, payment_request, payment_proof)
- VALUES
- (:id, :mint_url, :direction, :unit, :amount, :fee, :ys, :timestamp, :memo, :metadata, :quote_id, :payment_request, :payment_proof)
- ON CONFLICT(id) DO UPDATE SET
- mint_url = excluded.mint_url,
- direction = excluded.direction,
- unit = excluded.unit,
- amount = excluded.amount,
- fee = excluded.fee,
- timestamp = excluded.timestamp,
- memo = excluded.memo,
- metadata = excluded.metadata,
- quote_id = excluded.quote_id,
- payment_request = excluded.payment_request,
- payment_proof = excluded.payment_proof
- ;
- "#,
- )?
- .bind("id", 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)
- .bind("payment_request", transaction.payment_request)
- .bind("payment_proof", transaction.payment_proof)
- .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,
- payment_request,
- payment_proof
- 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,
- payment_request,
- payment_proof
- 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,
- payment_request,
- payment_proof
- ) = 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),
- payment_request: column_as_nullable_string!(payment_request),
- payment_proof: column_as_nullable_string!(payment_proof),
- })
- }
|