Bläddra i källkod

Move more functions to transaction

Cesar Rodas 3 månader sedan
förälder
incheckning
3a17665d84

+ 5 - 11
crates/cdk-common/src/database/mint/mod.rs

@@ -157,12 +157,6 @@ pub trait ProofsDatabase {
     /// Mint Proof Database Error
     type Err: Into<Error> + From<Error>;
 
-    /// Remove [`Proofs`]
-    async fn remove_proofs(
-        &self,
-        ys: &[PublicKey],
-        quote_id: Option<Uuid>,
-    ) -> Result<(), Self::Err>;
     /// Get [`Proofs`] by ys
     async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err>;
     /// Get ys by quote id
@@ -241,6 +235,11 @@ pub trait Transaction<'a, Error>:
     + SignaturesTransaction<'a, Err = Error>
     + ProofsTransaction<'a, Err = Error>
 {
+    /// Set [`QuoteTTL`]
+    async fn set_quote_ttl(&mut self, quote_ttl: QuoteTTL) -> Result<(), Error>;
+
+    /// Set [`MintInfo`]
+    async fn set_mint_info(&mut self, mint_info: MintInfo) -> Result<(), Error>;
 }
 
 /// Mint Database trait
@@ -253,14 +252,9 @@ pub trait Database<Error>:
         &'a self,
     ) -> Result<Box<dyn Transaction<'a, Error> + Send + Sync + 'a>, Error>;
 
-    /// Set [`MintInfo`]
-    async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), Error>;
-
     /// Get [`MintInfo`]
     async fn get_mint_info(&self) -> Result<MintInfo, Error>;
 
-    /// Set [`QuoteTTL`]
-    async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), Error>;
     /// Get [`QuoteTTL`]
     async fn get_quote_ttl(&self) -> Result<QuoteTTL, Error>;
 }

+ 5 - 4
crates/cdk-integration-tests/src/init_pure_tests.rs

@@ -227,11 +227,12 @@ pub async fn create_and_start_test_mint() -> Result<Mint> {
         .map(|x| x.clone())
         .expect("localstore");
 
-    localstore
-        .set_mint_info(mint_builder.mint_info.clone())
-        .await?;
+    let mut tx = localstore.begin_transaction().await?;
+    tx.set_mint_info(mint_builder.mint_info.clone()).await?;
+
     let quote_ttl = QuoteTTL::new(10000, 10000);
-    localstore.set_quote_ttl(quote_ttl).await?;
+    tx.set_quote_ttl(quote_ttl).await?;
+    tx.commit().await?;
 
     let mint = mint_builder.build().await?;
 

+ 5 - 3
crates/cdk-integration-tests/tests/mint.rs

@@ -51,13 +51,15 @@ async fn test_correct_keyset() {
         .with_seed(mnemonic.to_seed_normalized("").to_vec());
 
     let mint = mint_builder.build().await.unwrap();
+    let mut tx = localstore.begin_transaction().await.unwrap();
 
-    localstore
-        .set_mint_info(mint_builder.mint_info.clone())
+    tx.set_mint_info(mint_builder.mint_info.clone())
         .await
         .unwrap();
     let quote_ttl = QuoteTTL::new(10000, 10000);
-    localstore.set_quote_ttl(quote_ttl).await.unwrap();
+    tx.set_quote_ttl(quote_ttl).await.unwrap();
+
+    tx.commit().await.unwrap();
 
     let active = mint.get_active_keysets();
 

+ 1 - 2
crates/cdk-sqlite/src/mint/memory.rs

@@ -53,9 +53,8 @@ pub async fn new_with_state(
 
     tx.add_proofs(pending_proofs, None).await?;
     tx.add_proofs(spent_proofs, None).await?;
+    tx.set_mint_info(mint_info).await?;
     tx.commit().await?;
 
-    db.set_mint_info(mint_info).await?;
-
     Ok(db)
 }

+ 29 - 66
crates/cdk-sqlite/src/mint/mod.rs

@@ -75,6 +75,26 @@ where
         .collect::<Result<HashMap<_, _>, _>>()
 }
 
+#[inline(always)]
+async fn set_to_config<T, C>(conn: &C, id: &str, value: &T) -> Result<(), Error>
+where
+    T: ?Sized + serde::Serialize,
+    C: DatabaseExecutor + Send + Sync,
+{
+    query(
+        r#"
+        INSERT INTO config (id, value) VALUES (:id, :value)
+            ON CONFLICT(id) DO UPDATE SET value = excluded.value
+            "#,
+    )
+    .bind(":id", id.to_owned())
+    .bind(":value", serde_json::to_string(&value)?)
+    .execute(conn)
+    .await?;
+
+    Ok(())
+}
+
 impl MintSqliteDatabase {
     /// Create new [`MintSqliteDatabase`]
     #[cfg(not(feature = "sqlcipher"))]
@@ -102,25 +122,6 @@ impl MintSqliteDatabase {
     }
 
     #[inline(always)]
-    async fn set_to_config<T>(&self, id: &str, value: &T) -> Result<(), Error>
-    where
-        T: ?Sized + serde::Serialize,
-    {
-        query(
-            r#"
-            INSERT INTO config (id, value) VALUES (:id, :value)
-                ON CONFLICT(id) DO UPDATE SET value = excluded.value
-                "#,
-        )
-        .bind(":id", id.to_owned())
-        .bind(":value", serde_json::to_string(&value)?)
-        .execute(&self.pool)
-        .await?;
-
-        Ok(())
-    }
-
-    #[inline(always)]
     async fn fetch_from_config<T>(&self, id: &str) -> Result<T, Error>
     where
         T: serde::de::DeserializeOwned,
@@ -141,7 +142,15 @@ pub struct SqliteTransaction<'a> {
 }
 
 #[async_trait]
-impl<'a> database::MintTransaction<'a, database::Error> for SqliteTransaction<'a> {}
+impl<'a> database::MintTransaction<'a, database::Error> for SqliteTransaction<'a> {
+    async fn set_mint_info(&mut self, mint_info: MintInfo) -> Result<(), database::Error> {
+        Ok(set_to_config(&self.transaction, "mint_info", &mint_info).await?)
+    }
+
+    async fn set_quote_ttl(&mut self, quote_ttl: QuoteTTL) -> Result<(), database::Error> {
+        Ok(set_to_config(&self.transaction, "quote_ttl", &quote_ttl).await?)
+    }
+}
 
 #[async_trait]
 impl MintDbWriterFinalizer for SqliteTransaction<'_> {
@@ -943,33 +952,6 @@ impl<'a> MintProofsTransaction<'a> for SqliteTransaction<'a> {
 impl MintProofsDatabase for MintSqliteDatabase {
     type Err = database::Error;
 
-    async fn remove_proofs(
-        &self,
-        ys: &[PublicKey],
-        _quote_id: Option<Uuid>,
-    ) -> Result<(), Self::Err> {
-        let transaction = self.pool.begin().await?;
-
-        let total_deleted = query(
-            r#"
-            DELETE FROM proof WHERE y IN (:ys) AND state NOT IN (:exclude_state)
-            "#,
-        )
-        .bind_vec(":ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
-        .bind_vec(":exclude_state", vec![State::Spent.to_string()])
-        .execute(&transaction)
-        .await?;
-
-        if total_deleted != ys.len() {
-            transaction.rollback().await?;
-            return Err(Self::Err::AttemptRemoveSpentProof);
-        }
-
-        transaction.commit().await?;
-
-        Ok(())
-    }
-
     async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err> {
         let mut proofs = query(
             r#"
@@ -1267,18 +1249,10 @@ impl MintDatabase<database::Error> for MintSqliteDatabase {
         }))
     }
 
-    async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), database::Error> {
-        Ok(self.set_to_config("mint_info", &mint_info).await?)
-    }
-
     async fn get_mint_info(&self) -> Result<MintInfo, database::Error> {
         Ok(self.fetch_from_config("mint_info").await?)
     }
 
-    async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), database::Error> {
-        Ok(self.set_to_config("quote_ttl", &quote_ttl).await?)
-    }
-
     async fn get_quote_ttl(&self) -> Result<QuoteTTL, database::Error> {
         Ok(self.fetch_from_config("quote_ttl").await?)
     }
@@ -1529,17 +1503,6 @@ mod tests {
 
         tx.commit().await.unwrap();
 
-        // Try to remove both proofs - should fail because one is spent
-        let result = db
-            .remove_proofs(&[proofs[0].y().unwrap(), proofs[1].y().unwrap()], None)
-            .await;
-
-        assert!(result.is_err());
-        assert!(matches!(
-            result.unwrap_err(),
-            database::Error::AttemptRemoveSpentProof
-        ));
-
         // Verify both proofs still exist
         let states = db
             .get_proofs_states(&[proofs[0].y().unwrap(), proofs[1].y().unwrap()])

+ 0 - 2
crates/cdk/src/mint/check_spendable.rs

@@ -33,8 +33,6 @@ impl Mint {
 
         tx.commit().await?;
 
-        self.localstore.remove_proofs(&unknown_proofs, None).await?;
-
         Ok(())
     }
 

+ 6 - 2
crates/cdk/src/mint/mod.rs

@@ -225,7 +225,9 @@ impl Mint {
     /// Set mint info
     #[instrument(skip_all)]
     pub async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), Error> {
-        Ok(self.localstore.set_mint_info(mint_info).await?)
+        let mut tx = self.localstore.begin_transaction().await?;
+        tx.set_mint_info(mint_info).await?;
+        Ok(tx.commit().await?)
     }
 
     /// Get quote ttl
@@ -237,7 +239,9 @@ impl Mint {
     /// Set quote ttl
     #[instrument(skip_all)]
     pub async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), Error> {
-        Ok(self.localstore.set_quote_ttl(quote_ttl).await?)
+        let mut tx = self.localstore.begin_transaction().await?;
+        tx.set_quote_ttl(quote_ttl).await?;
+        Ok(tx.commit().await?)
     }
 
     /// Wait for any invoice to be paid