cdk_sql_common/wallet/
mod.rs

1//! SQLite Wallet Database
2
3use std::collections::HashMap;
4use std::fmt::Debug;
5use std::str::FromStr;
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use cdk_common::common::ProofInfo;
10use cdk_common::database::{ConversionError, Error, WalletDatabase};
11use cdk_common::mint_url::MintUrl;
12use cdk_common::nuts::{MeltQuoteState, MintQuoteState};
13use cdk_common::secret::Secret;
14use cdk_common::wallet::{self, MintQuote, Transaction, TransactionDirection, TransactionId};
15use cdk_common::{
16    database, Amount, CurrencyUnit, Id, KeySet, KeySetInfo, Keys, MintInfo, PaymentMethod, Proof,
17    ProofDleq, PublicKey, SecretKey, SpendingConditions, State,
18};
19use tracing::instrument;
20
21use crate::common::migrate;
22use crate::database::{ConnectionWithTransaction, DatabaseExecutor};
23use crate::pool::{DatabasePool, Pool, PooledResource};
24use crate::stmt::{query, Column};
25use crate::{
26    column_as_binary, column_as_nullable_binary, column_as_nullable_number,
27    column_as_nullable_string, column_as_number, column_as_string, unpack_into,
28};
29
30#[rustfmt::skip]
31mod migrations {
32    include!(concat!(env!("OUT_DIR"), "/migrations_wallet.rs"));
33}
34
35/// Wallet SQLite Database
36#[derive(Debug, Clone)]
37pub struct SQLWalletDatabase<RM>
38where
39    RM: DatabasePool + 'static,
40{
41    pool: Arc<Pool<RM>>,
42}
43
44impl<RM> SQLWalletDatabase<RM>
45where
46    RM: DatabasePool + 'static,
47{
48    /// Creates a new instance
49    pub async fn new<X>(db: X) -> Result<Self, Error>
50    where
51        X: Into<RM::Config>,
52    {
53        let pool = Pool::new(db.into());
54        Self::migrate(pool.get().map_err(|e| Error::Database(Box::new(e)))?).await?;
55
56        Ok(Self { pool })
57    }
58
59    /// Migrate [`WalletSqliteDatabase`]
60    async fn migrate(conn: PooledResource<RM>) -> Result<(), Error> {
61        let tx = ConnectionWithTransaction::new(conn).await?;
62        migrate(&tx, RM::Connection::name(), migrations::MIGRATIONS).await?;
63        // Update any existing keys with missing keyset_u32 values
64        Self::add_keyset_u32(&tx).await?;
65        tx.commit().await?;
66
67        Ok(())
68    }
69
70    async fn add_keyset_u32<T>(conn: &T) -> Result<(), Error>
71    where
72        T: DatabaseExecutor,
73    {
74        // First get the keysets where keyset_u32 on key is null
75        let keys_without_u32: Vec<Vec<Column>> = query(
76            r#"
77            SELECT
78                id
79            FROM key
80            WHERE keyset_u32 IS NULL
81            "#,
82        )?
83        .fetch_all(conn)
84        .await?;
85
86        for id in keys_without_u32 {
87            let id = column_as_string!(id.first().unwrap());
88
89            if let Ok(id) = Id::from_str(&id) {
90                query(
91                    r#"
92            UPDATE
93                key
94            SET keyset_u32 = :u32_keyset
95            WHERE id = :keyset_id
96            "#,
97                )?
98                .bind("u32_keyset", u32::from(id))
99                .bind("keyset_id", id.to_string())
100                .execute(conn)
101                .await?;
102            }
103        }
104
105        // Also update keysets where keyset_u32 is null
106        let keysets_without_u32: Vec<Vec<Column>> = query(
107            r#"
108            SELECT
109                id
110            FROM keyset
111            WHERE keyset_u32 IS NULL
112            "#,
113        )?
114        .fetch_all(conn)
115        .await?;
116
117        for id in keysets_without_u32 {
118            let id = column_as_string!(id.first().unwrap());
119
120            if let Ok(id) = Id::from_str(&id) {
121                query(
122                    r#"
123            UPDATE
124                keyset
125            SET keyset_u32 = :u32_keyset
126            WHERE id = :keyset_id
127            "#,
128                )?
129                .bind("u32_keyset", u32::from(id))
130                .bind("keyset_id", id.to_string())
131                .execute(conn)
132                .await?;
133            }
134        }
135
136        Ok(())
137    }
138}
139
140#[async_trait]
141impl<RM> WalletDatabase for SQLWalletDatabase<RM>
142where
143    RM: DatabasePool + 'static,
144{
145    type Err = database::Error;
146
147    #[instrument(skip(self))]
148    async fn get_melt_quotes(&self) -> Result<Vec<wallet::MeltQuote>, Self::Err> {
149        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
150
151        Ok(query(
152            r#"
153              SELECT
154                  id,
155                  unit,
156                  amount,
157                  request,
158                  fee_reserve,
159                  state,
160                  expiry,
161                  payment_preimage,
162                  payment_method
163              FROM
164                  melt_quote
165              "#,
166        )?
167        .fetch_all(&*conn)
168        .await?
169        .into_iter()
170        .map(sql_row_to_melt_quote)
171        .collect::<Result<_, _>>()?)
172    }
173
174    #[instrument(skip(self, mint_info))]
175    async fn add_mint(
176        &self,
177        mint_url: MintUrl,
178        mint_info: Option<MintInfo>,
179    ) -> Result<(), Self::Err> {
180        let (
181            name,
182            pubkey,
183            version,
184            description,
185            description_long,
186            contact,
187            nuts,
188            icon_url,
189            urls,
190            motd,
191            time,
192            tos_url,
193        ) = match mint_info {
194            Some(mint_info) => {
195                let MintInfo {
196                    name,
197                    pubkey,
198                    version,
199                    description,
200                    description_long,
201                    contact,
202                    nuts,
203                    icon_url,
204                    urls,
205                    motd,
206                    time,
207                    tos_url,
208                } = mint_info;
209
210                (
211                    name,
212                    pubkey.map(|p| p.to_bytes().to_vec()),
213                    version.map(|v| serde_json::to_string(&v).ok()),
214                    description,
215                    description_long,
216                    contact.map(|c| serde_json::to_string(&c).ok()),
217                    serde_json::to_string(&nuts).ok(),
218                    icon_url,
219                    urls.map(|c| serde_json::to_string(&c).ok()),
220                    motd,
221                    time,
222                    tos_url,
223                )
224            }
225            None => (
226                None, None, None, None, None, None, None, None, None, None, None, None,
227            ),
228        };
229
230        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
231
232        query(
233            r#"
234INSERT INTO mint
235(
236    mint_url, name, pubkey, version, description, description_long,
237    contact, nuts, icon_url, urls, motd, mint_time, tos_url
238)
239VALUES
240(
241    :mint_url, :name, :pubkey, :version, :description, :description_long,
242    :contact, :nuts, :icon_url, :urls, :motd, :mint_time, :tos_url
243)
244ON CONFLICT(mint_url) DO UPDATE SET
245    name = excluded.name,
246    pubkey = excluded.pubkey,
247    version = excluded.version,
248    description = excluded.description,
249    description_long = excluded.description_long,
250    contact = excluded.contact,
251    nuts = excluded.nuts,
252    icon_url = excluded.icon_url,
253    urls = excluded.urls,
254    motd = excluded.motd,
255    mint_time = excluded.mint_time,
256    tos_url = excluded.tos_url
257;
258        "#,
259        )?
260        .bind("mint_url", mint_url.to_string())
261        .bind("name", name)
262        .bind("pubkey", pubkey)
263        .bind("version", version)
264        .bind("description", description)
265        .bind("description_long", description_long)
266        .bind("contact", contact)
267        .bind("nuts", nuts)
268        .bind("icon_url", icon_url)
269        .bind("urls", urls)
270        .bind("motd", motd)
271        .bind("mint_time", time.map(|v| v as i64))
272        .bind("tos_url", tos_url)
273        .execute(&*conn)
274        .await?;
275
276        Ok(())
277    }
278
279    #[instrument(skip(self))]
280    async fn remove_mint(&self, mint_url: MintUrl) -> Result<(), Self::Err> {
281        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
282
283        query(r#"DELETE FROM mint WHERE mint_url=:mint_url"#)?
284            .bind("mint_url", mint_url.to_string())
285            .execute(&*conn)
286            .await?;
287
288        Ok(())
289    }
290
291    #[instrument(skip(self))]
292    async fn get_mint(&self, mint_url: MintUrl) -> Result<Option<MintInfo>, Self::Err> {
293        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
294        Ok(query(
295            r#"
296            SELECT
297                name,
298                pubkey,
299                version,
300                description,
301                description_long,
302                contact,
303                nuts,
304                icon_url,
305                motd,
306                urls,
307                mint_time,
308                tos_url
309            FROM
310                mint
311            WHERE mint_url = :mint_url
312            "#,
313        )?
314        .bind("mint_url", mint_url.to_string())
315        .fetch_one(&*conn)
316        .await?
317        .map(sql_row_to_mint_info)
318        .transpose()?)
319    }
320
321    #[instrument(skip(self))]
322    async fn get_mints(&self) -> Result<HashMap<MintUrl, Option<MintInfo>>, Self::Err> {
323        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
324        Ok(query(
325            r#"
326                SELECT
327                    name,
328                    pubkey,
329                    version,
330                    description,
331                    description_long,
332                    contact,
333                    nuts,
334                    icon_url,
335                    motd,
336                    urls,
337                    mint_time,
338                    tos_url,
339                    mint_url
340                FROM
341                    mint
342                "#,
343        )?
344        .fetch_all(&*conn)
345        .await?
346        .into_iter()
347        .map(|mut row| {
348            let url = column_as_string!(
349                row.pop().ok_or(ConversionError::MissingColumn(0, 1))?,
350                MintUrl::from_str
351            );
352
353            Ok((url, sql_row_to_mint_info(row).ok()))
354        })
355        .collect::<Result<HashMap<_, _>, Error>>()?)
356    }
357
358    #[instrument(skip(self))]
359    async fn update_mint_url(
360        &self,
361        old_mint_url: MintUrl,
362        new_mint_url: MintUrl,
363    ) -> Result<(), Self::Err> {
364        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
365        let tables = ["mint_quote", "proof"];
366
367        for table in &tables {
368            query(&format!(
369                r#"
370                UPDATE {table}
371                SET mint_url = :new_mint_url
372                WHERE mint_url = :old_mint_url
373            "#
374            ))?
375            .bind("new_mint_url", new_mint_url.to_string())
376            .bind("old_mint_url", old_mint_url.to_string())
377            .execute(&*conn)
378            .await?;
379        }
380
381        Ok(())
382    }
383
384    #[instrument(skip(self, keysets))]
385    async fn add_mint_keysets(
386        &self,
387        mint_url: MintUrl,
388        keysets: Vec<KeySetInfo>,
389    ) -> Result<(), Self::Err> {
390        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
391
392        for keyset in keysets {
393            query(
394                r#"
395    INSERT INTO keyset
396    (mint_url, id, unit, active, input_fee_ppk, final_expiry, keyset_u32)
397    VALUES
398    (:mint_url, :id, :unit, :active, :input_fee_ppk, :final_expiry, :keyset_u32)
399    ON CONFLICT(id) DO UPDATE SET
400        active = excluded.active,
401        input_fee_ppk = excluded.input_fee_ppk
402    "#,
403            )?
404            .bind("mint_url", mint_url.to_string())
405            .bind("id", keyset.id.to_string())
406            .bind("unit", keyset.unit.to_string())
407            .bind("active", keyset.active)
408            .bind("input_fee_ppk", keyset.input_fee_ppk as i64)
409            .bind("final_expiry", keyset.final_expiry.map(|v| v as i64))
410            .bind("keyset_u32", u32::from(keyset.id))
411            .execute(&*conn)
412            .await?;
413        }
414
415        Ok(())
416    }
417
418    #[instrument(skip(self))]
419    async fn get_mint_keysets(
420        &self,
421        mint_url: MintUrl,
422    ) -> Result<Option<Vec<KeySetInfo>>, Self::Err> {
423        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
424
425        let keysets = query(
426            r#"
427            SELECT
428                id,
429                unit,
430                active,
431                input_fee_ppk,
432                final_expiry
433            FROM
434                keyset
435            WHERE mint_url = :mint_url
436            "#,
437        )?
438        .bind("mint_url", mint_url.to_string())
439        .fetch_all(&*conn)
440        .await?
441        .into_iter()
442        .map(sql_row_to_keyset)
443        .collect::<Result<Vec<_>, Error>>()?;
444
445        match keysets.is_empty() {
446            false => Ok(Some(keysets)),
447            true => Ok(None),
448        }
449    }
450
451    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
452    async fn get_keyset_by_id(&self, keyset_id: &Id) -> Result<Option<KeySetInfo>, Self::Err> {
453        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
454        Ok(query(
455            r#"
456            SELECT
457                id,
458                unit,
459                active,
460                input_fee_ppk,
461                final_expiry
462            FROM
463                keyset
464            WHERE id = :id
465            "#,
466        )?
467        .bind("id", keyset_id.to_string())
468        .fetch_one(&*conn)
469        .await?
470        .map(sql_row_to_keyset)
471        .transpose()?)
472    }
473
474    #[instrument(skip_all)]
475    async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err> {
476        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
477        query(
478            r#"
479INSERT INTO mint_quote
480(id, mint_url, amount, unit, request, state, expiry, secret_key, payment_method, amount_issued, amount_paid)
481VALUES
482(:id, :mint_url, :amount, :unit, :request, :state, :expiry, :secret_key, :payment_method, :amount_issued, :amount_paid)
483ON CONFLICT(id) DO UPDATE SET
484    mint_url = excluded.mint_url,
485    amount = excluded.amount,
486    unit = excluded.unit,
487    request = excluded.request,
488    state = excluded.state,
489    expiry = excluded.expiry,
490    secret_key = excluded.secret_key,
491    payment_method = excluded.payment_method,
492    amount_issued = excluded.amount_issued,
493    amount_paid = excluded.amount_paid
494;
495        "#,
496        )?
497        .bind("id", quote.id.to_string())
498        .bind("mint_url", quote.mint_url.to_string())
499        .bind("amount", quote.amount.map(|a| a.to_i64()))
500        .bind("unit", quote.unit.to_string())
501        .bind("request", quote.request)
502        .bind("state", quote.state.to_string())
503        .bind("expiry", quote.expiry as i64)
504        .bind("secret_key", quote.secret_key.map(|p| p.to_string()))
505        .bind("payment_method", quote.payment_method.to_string())
506        .bind("amount_issued", quote.amount_issued.to_i64())
507        .bind("amount_paid", quote.amount_paid.to_i64())
508        .execute(&*conn).await?;
509
510        Ok(())
511    }
512
513    #[instrument(skip(self))]
514    async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, Self::Err> {
515        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
516        Ok(query(
517            r#"
518            SELECT
519                id,
520                mint_url,
521                amount,
522                unit,
523                request,
524                state,
525                expiry,
526                secret_key,
527                payment_method,
528                amount_issued,
529                amount_paid
530            FROM
531                mint_quote
532            WHERE
533                id = :id
534            "#,
535        )?
536        .bind("id", quote_id.to_string())
537        .fetch_one(&*conn)
538        .await?
539        .map(sql_row_to_mint_quote)
540        .transpose()?)
541    }
542
543    #[instrument(skip(self))]
544    async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
545        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
546        Ok(query(
547            r#"
548            SELECT
549                id,
550                mint_url,
551                amount,
552                unit,
553                request,
554                state,
555                expiry,
556                secret_key
557                payment_method,
558                amount_issued,
559                amount_paid
560            FROM
561                mint_quote
562            "#,
563        )?
564        .fetch_all(&*conn)
565        .await?
566        .into_iter()
567        .map(sql_row_to_mint_quote)
568        .collect::<Result<_, _>>()?)
569    }
570
571    #[instrument(skip(self))]
572    async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
573        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
574        query(r#"DELETE FROM mint_quote WHERE id=:id"#)?
575            .bind("id", quote_id.to_string())
576            .execute(&*conn)
577            .await?;
578
579        Ok(())
580    }
581
582    #[instrument(skip_all)]
583    async fn add_melt_quote(&self, quote: wallet::MeltQuote) -> Result<(), Self::Err> {
584        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
585        query(
586            r#"
587INSERT INTO melt_quote
588(id, unit, amount, request, fee_reserve, state, expiry, payment_method)
589VALUES
590(:id, :unit, :amount, :request, :fee_reserve, :state, :expiry, :payment_method)
591ON CONFLICT(id) DO UPDATE SET
592    unit = excluded.unit,
593    amount = excluded.amount,
594    request = excluded.request,
595    fee_reserve = excluded.fee_reserve,
596    state = excluded.state,
597    expiry = excluded.expiry,
598    payment_method = excluded.payment_method
599;
600        "#,
601        )?
602        .bind("id", quote.id.to_string())
603        .bind("unit", quote.unit.to_string())
604        .bind("amount", u64::from(quote.amount) as i64)
605        .bind("request", quote.request)
606        .bind("fee_reserve", u64::from(quote.fee_reserve) as i64)
607        .bind("state", quote.state.to_string())
608        .bind("expiry", quote.expiry as i64)
609        .bind("payment_method", quote.payment_method.to_string())
610        .execute(&*conn)
611        .await?;
612
613        Ok(())
614    }
615
616    #[instrument(skip(self))]
617    async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<wallet::MeltQuote>, Self::Err> {
618        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
619        Ok(query(
620            r#"
621            SELECT
622                id,
623                unit,
624                amount,
625                request,
626                fee_reserve,
627                state,
628                expiry,
629                payment_preimage,
630                payment_method
631            FROM
632                melt_quote
633            WHERE
634                id=:id
635            "#,
636        )?
637        .bind("id", quote_id.to_owned())
638        .fetch_one(&*conn)
639        .await?
640        .map(sql_row_to_melt_quote)
641        .transpose()?)
642    }
643
644    #[instrument(skip(self))]
645    async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
646        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
647        query(r#"DELETE FROM melt_quote WHERE id=:id"#)?
648            .bind("id", quote_id.to_owned())
649            .execute(&*conn)
650            .await?;
651
652        Ok(())
653    }
654
655    #[instrument(skip_all)]
656    async fn add_keys(&self, keyset: KeySet) -> Result<(), Self::Err> {
657        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
658
659        // Recompute ID for verification
660        keyset.verify_id()?;
661
662        query(
663            r#"
664            INSERT INTO key
665            (id, keys, keyset_u32)
666            VALUES
667            (:id, :keys, :keyset_u32)
668        "#,
669        )?
670        .bind("id", keyset.id.to_string())
671        .bind(
672            "keys",
673            serde_json::to_string(&keyset.keys).map_err(Error::from)?,
674        )
675        .bind("keyset_u32", u32::from(keyset.id))
676        .execute(&*conn)
677        .await?;
678
679        Ok(())
680    }
681
682    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
683    async fn get_keys(&self, keyset_id: &Id) -> Result<Option<Keys>, Self::Err> {
684        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
685        Ok(query(
686            r#"
687            SELECT
688                keys
689            FROM key
690            WHERE id = :id
691            "#,
692        )?
693        .bind("id", keyset_id.to_string())
694        .pluck(&*conn)
695        .await?
696        .map(|keys| {
697            let keys = column_as_string!(keys);
698            serde_json::from_str(&keys).map_err(Error::from)
699        })
700        .transpose()?)
701    }
702
703    #[instrument(skip(self))]
704    async fn remove_keys(&self, id: &Id) -> Result<(), Self::Err> {
705        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
706        query(r#"DELETE FROM key WHERE id = :id"#)?
707            .bind("id", id.to_string())
708            .pluck(&*conn)
709            .await?;
710
711        Ok(())
712    }
713
714    async fn update_proofs(
715        &self,
716        added: Vec<ProofInfo>,
717        removed_ys: Vec<PublicKey>,
718    ) -> Result<(), Self::Err> {
719        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
720
721        let tx = ConnectionWithTransaction::new(conn).await?;
722
723        // TODO: Use a transaction for all these operations
724        for proof in added {
725            query(
726                r#"
727    INSERT INTO proof
728    (y, mint_url, state, spending_condition, unit, amount, keyset_id, secret, c, witness, dleq_e, dleq_s, dleq_r)
729    VALUES
730    (:y, :mint_url, :state, :spending_condition, :unit, :amount, :keyset_id, :secret, :c, :witness, :dleq_e, :dleq_s, :dleq_r)
731    ON CONFLICT(y) DO UPDATE SET
732        mint_url = excluded.mint_url,
733        state = excluded.state,
734        spending_condition = excluded.spending_condition,
735        unit = excluded.unit,
736        amount = excluded.amount,
737        keyset_id = excluded.keyset_id,
738        secret = excluded.secret,
739        c = excluded.c,
740        witness = excluded.witness,
741        dleq_e = excluded.dleq_e,
742        dleq_s = excluded.dleq_s,
743        dleq_r = excluded.dleq_r
744    ;
745            "#,
746            )?
747            .bind("y", proof.y.to_bytes().to_vec())
748            .bind("mint_url", proof.mint_url.to_string())
749            .bind("state",proof.state.to_string())
750            .bind(
751                "spending_condition",
752                proof
753                    .spending_condition
754                    .map(|s| serde_json::to_string(&s).ok()),
755            )
756            .bind("unit", proof.unit.to_string())
757            .bind("amount", u64::from(proof.proof.amount) as i64)
758            .bind("keyset_id", proof.proof.keyset_id.to_string())
759            .bind("secret", proof.proof.secret.to_string())
760            .bind("c", proof.proof.c.to_bytes().to_vec())
761            .bind(
762                "witness",
763                proof
764                    .proof
765                    .witness
766                    .map(|w| serde_json::to_string(&w).unwrap()),
767            )
768            .bind(
769                "dleq_e",
770                proof.proof.dleq.as_ref().map(|dleq| dleq.e.to_secret_bytes().to_vec()),
771            )
772            .bind(
773                "dleq_s",
774                proof.proof.dleq.as_ref().map(|dleq| dleq.s.to_secret_bytes().to_vec()),
775            )
776            .bind(
777                "dleq_r",
778                proof.proof.dleq.as_ref().map(|dleq| dleq.r.to_secret_bytes().to_vec()),
779            )
780            .execute(&tx).await?;
781        }
782
783        query(r#"DELETE FROM proof WHERE y IN (:ys)"#)?
784            .bind_vec(
785                "ys",
786                removed_ys.iter().map(|y| y.to_bytes().to_vec()).collect(),
787            )
788            .execute(&tx)
789            .await?;
790
791        tx.commit().await?;
792
793        Ok(())
794    }
795
796    #[instrument(skip(self, state, spending_conditions))]
797    async fn get_proofs(
798        &self,
799        mint_url: Option<MintUrl>,
800        unit: Option<CurrencyUnit>,
801        state: Option<Vec<State>>,
802        spending_conditions: Option<Vec<SpendingConditions>>,
803    ) -> Result<Vec<ProofInfo>, Self::Err> {
804        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
805        Ok(query(
806            r#"
807            SELECT
808                amount,
809                unit,
810                keyset_id,
811                secret,
812                c,
813                witness,
814                dleq_e,
815                dleq_s,
816                dleq_r,
817                y,
818                mint_url,
819                state,
820                spending_condition
821            FROM proof
822        "#,
823        )?
824        .fetch_all(&*conn)
825        .await?
826        .into_iter()
827        .filter_map(|row| {
828            let row = sql_row_to_proof_info(row).ok()?;
829
830            if row.matches_conditions(&mint_url, &unit, &state, &spending_conditions) {
831                Some(row)
832            } else {
833                None
834            }
835        })
836        .collect::<Vec<_>>())
837    }
838
839    async fn update_proofs_state(&self, ys: Vec<PublicKey>, state: State) -> Result<(), Self::Err> {
840        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
841        query("UPDATE proof SET state = :state WHERE y IN (:ys)")?
842            .bind_vec("ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
843            .bind("state", state.to_string())
844            .execute(&*conn)
845            .await?;
846
847        Ok(())
848    }
849
850    #[instrument(skip(self), fields(keyset_id = %keyset_id))]
851    async fn increment_keyset_counter(&self, keyset_id: &Id, count: u32) -> Result<u32, Self::Err> {
852        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
853        let tx = ConnectionWithTransaction::new(conn).await?;
854
855        // Lock the row and get current counter
856        let current_counter = query(
857            r#"
858            SELECT counter
859            FROM keyset
860            WHERE id=:id
861            FOR UPDATE
862            "#,
863        )?
864        .bind("id", keyset_id.to_string())
865        .pluck(&tx)
866        .await?
867        .map(|n| Ok::<_, Error>(column_as_number!(n)))
868        .transpose()?
869        .unwrap_or(0);
870
871        let new_counter = current_counter + count;
872
873        // Update with the new counter value
874        query(
875            r#"
876            UPDATE keyset
877            SET counter=:new_counter
878            WHERE id=:id
879            "#,
880        )?
881        .bind("new_counter", new_counter)
882        .bind("id", keyset_id.to_string())
883        .execute(&tx)
884        .await?;
885
886        tx.commit().await?;
887
888        Ok(new_counter)
889    }
890
891    #[instrument(skip(self))]
892    async fn add_transaction(&self, transaction: Transaction) -> Result<(), Self::Err> {
893        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
894        let mint_url = transaction.mint_url.to_string();
895        let direction = transaction.direction.to_string();
896        let unit = transaction.unit.to_string();
897        let amount = u64::from(transaction.amount) as i64;
898        let fee = u64::from(transaction.fee) as i64;
899        let ys = transaction
900            .ys
901            .iter()
902            .flat_map(|y| y.to_bytes().to_vec())
903            .collect::<Vec<_>>();
904
905        query(
906            r#"
907INSERT INTO transactions
908(id, mint_url, direction, unit, amount, fee, ys, timestamp, memo, metadata, quote_id)
909VALUES
910(:id, :mint_url, :direction, :unit, :amount, :fee, :ys, :timestamp, :memo, :metadata, :quote_id)
911ON CONFLICT(id) DO UPDATE SET
912    mint_url = excluded.mint_url,
913    direction = excluded.direction,
914    unit = excluded.unit,
915    amount = excluded.amount,
916    fee = excluded.fee,
917    ys = excluded.ys,
918    timestamp = excluded.timestamp,
919    memo = excluded.memo,
920    metadata = excluded.metadata,
921    quote_id = excluded.quote_id
922;
923        "#,
924        )?
925        .bind("id", transaction.id().as_slice().to_vec())
926        .bind("mint_url", mint_url)
927        .bind("direction", direction)
928        .bind("unit", unit)
929        .bind("amount", amount)
930        .bind("fee", fee)
931        .bind("ys", ys)
932        .bind("timestamp", transaction.timestamp as i64)
933        .bind("memo", transaction.memo)
934        .bind(
935            "metadata",
936            serde_json::to_string(&transaction.metadata).map_err(Error::from)?,
937        )
938        .bind("quote_id", transaction.quote_id)
939        .execute(&*conn)
940        .await?;
941
942        Ok(())
943    }
944
945    #[instrument(skip(self))]
946    async fn get_transaction(
947        &self,
948        transaction_id: TransactionId,
949    ) -> Result<Option<Transaction>, Self::Err> {
950        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
951        Ok(query(
952            r#"
953            SELECT
954                mint_url,
955                direction,
956                unit,
957                amount,
958                fee,
959                ys,
960                timestamp,
961                memo,
962                metadata,
963                quote_id
964            FROM
965                transactions
966            WHERE
967                id = :id
968            "#,
969        )?
970        .bind("id", transaction_id.as_slice().to_vec())
971        .fetch_one(&*conn)
972        .await?
973        .map(sql_row_to_transaction)
974        .transpose()?)
975    }
976
977    #[instrument(skip(self))]
978    async fn list_transactions(
979        &self,
980        mint_url: Option<MintUrl>,
981        direction: Option<TransactionDirection>,
982        unit: Option<CurrencyUnit>,
983    ) -> Result<Vec<Transaction>, Self::Err> {
984        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
985
986        Ok(query(
987            r#"
988            SELECT
989                mint_url,
990                direction,
991                unit,
992                amount,
993                fee,
994                ys,
995                timestamp,
996                memo,
997                metadata,
998                quote_id
999            FROM
1000                transactions
1001            "#,
1002        )?
1003        .fetch_all(&*conn)
1004        .await?
1005        .into_iter()
1006        .filter_map(|row| {
1007            // TODO: Avoid a table scan by passing the heavy lifting of checking to the DB engine
1008            let transaction = sql_row_to_transaction(row).ok()?;
1009            if transaction.matches_conditions(&mint_url, &direction, &unit) {
1010                Some(transaction)
1011            } else {
1012                None
1013            }
1014        })
1015        .collect::<Vec<_>>())
1016    }
1017
1018    #[instrument(skip(self))]
1019    async fn remove_transaction(&self, transaction_id: TransactionId) -> Result<(), Self::Err> {
1020        let conn = self.pool.get().map_err(|e| Error::Database(Box::new(e)))?;
1021
1022        query(r#"DELETE FROM transactions WHERE id=:id"#)?
1023            .bind("id", transaction_id.as_slice().to_vec())
1024            .execute(&*conn)
1025            .await?;
1026
1027        Ok(())
1028    }
1029}
1030
1031fn sql_row_to_mint_info(row: Vec<Column>) -> Result<MintInfo, Error> {
1032    unpack_into!(
1033        let (
1034            name,
1035            pubkey,
1036            version,
1037            description,
1038            description_long,
1039            contact,
1040            nuts,
1041            icon_url,
1042            motd,
1043            urls,
1044            mint_time,
1045            tos_url
1046        ) = row
1047    );
1048
1049    Ok(MintInfo {
1050        name: column_as_nullable_string!(&name),
1051        pubkey: column_as_nullable_string!(&pubkey, |v| serde_json::from_str(v).ok(), |v| {
1052            serde_json::from_slice(v).ok()
1053        }),
1054        version: column_as_nullable_string!(&version).and_then(|v| serde_json::from_str(&v).ok()),
1055        description: column_as_nullable_string!(description),
1056        description_long: column_as_nullable_string!(description_long),
1057        contact: column_as_nullable_string!(contact, |v| serde_json::from_str(&v).ok()),
1058        nuts: column_as_nullable_string!(nuts, |v| serde_json::from_str(&v).ok())
1059            .unwrap_or_default(),
1060        urls: column_as_nullable_string!(urls, |v| serde_json::from_str(&v).ok()),
1061        icon_url: column_as_nullable_string!(icon_url),
1062        motd: column_as_nullable_string!(motd),
1063        time: column_as_nullable_number!(mint_time).map(|t| t),
1064        tos_url: column_as_nullable_string!(tos_url),
1065    })
1066}
1067
1068#[instrument(skip_all)]
1069fn sql_row_to_keyset(row: Vec<Column>) -> Result<KeySetInfo, Error> {
1070    unpack_into!(
1071        let (
1072            id,
1073            unit,
1074            active,
1075            input_fee_ppk,
1076            final_expiry
1077        ) = row
1078    );
1079
1080    Ok(KeySetInfo {
1081        id: column_as_string!(id, Id::from_str, Id::from_bytes),
1082        unit: column_as_string!(unit, CurrencyUnit::from_str),
1083        active: matches!(active, Column::Integer(1)),
1084        input_fee_ppk: column_as_nullable_number!(input_fee_ppk).unwrap_or_default(),
1085        final_expiry: column_as_nullable_number!(final_expiry),
1086    })
1087}
1088
1089fn sql_row_to_mint_quote(row: Vec<Column>) -> Result<MintQuote, Error> {
1090    unpack_into!(
1091        let (
1092            id,
1093            mint_url,
1094            amount,
1095            unit,
1096            request,
1097            state,
1098            expiry,
1099            secret_key,
1100            row_method,
1101            row_amount_minted,
1102            row_amount_paid
1103        ) = row
1104    );
1105
1106    let amount: Option<i64> = column_as_nullable_number!(amount);
1107
1108    let amount_paid: u64 = column_as_number!(row_amount_paid);
1109    let amount_minted: u64 = column_as_number!(row_amount_minted);
1110    let payment_method =
1111        PaymentMethod::from_str(&column_as_string!(row_method)).map_err(Error::from)?;
1112
1113    Ok(MintQuote {
1114        id: column_as_string!(id),
1115        mint_url: column_as_string!(mint_url, MintUrl::from_str),
1116        amount: amount.and_then(Amount::from_i64),
1117        unit: column_as_string!(unit, CurrencyUnit::from_str),
1118        request: column_as_string!(request),
1119        state: column_as_string!(state, MintQuoteState::from_str),
1120        expiry: column_as_number!(expiry),
1121        secret_key: column_as_nullable_string!(secret_key)
1122            .map(|v| SecretKey::from_str(&v))
1123            .transpose()?,
1124        payment_method,
1125        amount_issued: amount_minted.into(),
1126        amount_paid: amount_paid.into(),
1127    })
1128}
1129
1130fn sql_row_to_melt_quote(row: Vec<Column>) -> Result<wallet::MeltQuote, Error> {
1131    unpack_into!(
1132        let (
1133            id,
1134            unit,
1135            amount,
1136            request,
1137            fee_reserve,
1138            state,
1139            expiry,
1140            payment_preimage,
1141            row_method
1142        ) = row
1143    );
1144
1145    let amount: u64 = column_as_number!(amount);
1146    let fee_reserve: u64 = column_as_number!(fee_reserve);
1147
1148    let payment_method =
1149        PaymentMethod::from_str(&column_as_string!(row_method)).map_err(Error::from)?;
1150
1151    Ok(wallet::MeltQuote {
1152        id: column_as_string!(id),
1153        amount: Amount::from(amount),
1154        unit: column_as_string!(unit, CurrencyUnit::from_str),
1155        request: column_as_string!(request),
1156        fee_reserve: Amount::from(fee_reserve),
1157        state: column_as_string!(state, MeltQuoteState::from_str),
1158        expiry: column_as_number!(expiry),
1159        payment_preimage: column_as_nullable_string!(payment_preimage),
1160        payment_method,
1161    })
1162}
1163
1164fn sql_row_to_proof_info(row: Vec<Column>) -> Result<ProofInfo, Error> {
1165    unpack_into!(
1166        let (
1167            amount,
1168            unit,
1169            keyset_id,
1170            secret,
1171            c,
1172            witness,
1173            dleq_e,
1174            dleq_s,
1175            dleq_r,
1176            y,
1177            mint_url,
1178            state,
1179            spending_condition
1180        ) = row
1181    );
1182
1183    let dleq = match (
1184        column_as_nullable_binary!(dleq_e),
1185        column_as_nullable_binary!(dleq_s),
1186        column_as_nullable_binary!(dleq_r),
1187    ) {
1188        (Some(e), Some(s), Some(r)) => {
1189            let e_key = SecretKey::from_slice(&e)?;
1190            let s_key = SecretKey::from_slice(&s)?;
1191            let r_key = SecretKey::from_slice(&r)?;
1192
1193            Some(ProofDleq::new(e_key, s_key, r_key))
1194        }
1195        _ => None,
1196    };
1197
1198    let amount: u64 = column_as_number!(amount);
1199    let proof = Proof {
1200        amount: Amount::from(amount),
1201        keyset_id: column_as_string!(keyset_id, Id::from_str),
1202        secret: column_as_string!(secret, Secret::from_str),
1203        witness: column_as_nullable_string!(witness, |v| { serde_json::from_str(&v).ok() }, |v| {
1204            serde_json::from_slice(&v).ok()
1205        }),
1206        c: column_as_string!(c, PublicKey::from_str, PublicKey::from_slice),
1207        dleq,
1208    };
1209
1210    Ok(ProofInfo {
1211        proof,
1212        y: column_as_string!(y, PublicKey::from_str, PublicKey::from_slice),
1213        mint_url: column_as_string!(mint_url, MintUrl::from_str),
1214        state: column_as_string!(state, State::from_str),
1215        spending_condition: column_as_nullable_string!(
1216            spending_condition,
1217            |r| { serde_json::from_str(&r).ok() },
1218            |r| { serde_json::from_slice(&r).ok() }
1219        ),
1220        unit: column_as_string!(unit, CurrencyUnit::from_str),
1221    })
1222}
1223
1224fn sql_row_to_transaction(row: Vec<Column>) -> Result<Transaction, Error> {
1225    unpack_into!(
1226        let (
1227            mint_url,
1228            direction,
1229            unit,
1230            amount,
1231            fee,
1232            ys,
1233            timestamp,
1234            memo,
1235            metadata,
1236            quote_id
1237        ) = row
1238    );
1239
1240    let amount: u64 = column_as_number!(amount);
1241    let fee: u64 = column_as_number!(fee);
1242
1243    Ok(Transaction {
1244        mint_url: column_as_string!(mint_url, MintUrl::from_str),
1245        direction: column_as_string!(direction, TransactionDirection::from_str),
1246        unit: column_as_string!(unit, CurrencyUnit::from_str),
1247        amount: Amount::from(amount),
1248        fee: Amount::from(fee),
1249        ys: column_as_binary!(ys)
1250            .chunks(33)
1251            .map(PublicKey::from_slice)
1252            .collect::<Result<Vec<_>, _>>()?,
1253        timestamp: column_as_number!(timestamp),
1254        memo: column_as_nullable_string!(memo),
1255        metadata: column_as_nullable_string!(metadata, |v| serde_json::from_str(&v).ok(), |v| {
1256            serde_json::from_slice(&v).ok()
1257        })
1258        .unwrap_or_default(),
1259        quote_id: column_as_nullable_string!(quote_id),
1260    })
1261}