Просмотр исходного кода

refactor: remove the use of flat maps

thesimplekid 6 месяцев назад
Родитель
Сommit
bcb4a5927d

+ 2 - 2
crates/cdk-cli/src/sub_commands/receive.rs

@@ -46,7 +46,7 @@ pub async fn receive(
         let mut s_keys: Vec<SecretKey> = sub_command_args
             .signing_key
             .iter()
-            .flat_map(|s| {
+            .map(|s| {
                 if s.starts_with("nsec") {
                     let nostr_key = nostr_sdk::SecretKey::from_str(s).expect("Invalid secret key");
 
@@ -55,7 +55,7 @@ pub async fn receive(
                     SecretKey::from_str(s)
                 }
             })
-            .collect();
+            .collect::<Result<Vec<SecretKey>, _>>()?;
         signing_keys.append(&mut s_keys);
     }
 

+ 10 - 4
crates/cdk-redb/src/mint/mod.rs

@@ -580,15 +580,21 @@ impl MintDatabase for MintRedbDatabase {
         let read_txn = db.begin_read().map_err(Error::from)?;
         let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
 
-        let proofs_for_id: Proofs = table
+        let proofs_for_id = table
             .iter()
             .map_err(Error::from)?
             .flatten()
-            .flat_map(|(_, p)| serde_json::from_str::<Proof>(p.value()))
+            .map(|(_, p)| serde_json::from_str::<Proof>(p.value()))
+            .collect::<Result<Proofs, _>>()?
+            .into_iter()
             .filter(|p| &p.keyset_id == keyset_id)
-            .collect();
+            .collect::<Proofs>();
+
+        let proof_ys = proofs_for_id
+            .iter()
+            .map(|p| p.y())
+            .collect::<Result<Vec<PublicKey>, _>>()?;
 
-        let proof_ys: Vec<PublicKey> = proofs_for_id.iter().flat_map(|p| p.y()).collect();
         assert_eq!(proofs_for_id.len(), proof_ys.len());
 
         let states = self.get_proofs_states(&proof_ys).await?;

+ 3 - 3
crates/cdk-redb/src/wallet/mod.rs

@@ -340,12 +340,12 @@ impl WalletDatabase for WalletRedbDatabase {
             .open_multimap_table(MINT_KEYSETS_TABLE)
             .map_err(Error::from)?;
 
-        let keyset_ids: Vec<Id> = table
+        let keyset_ids = table
             .get(mint_url.to_string().as_str())
             .map_err(Error::from)?
             .flatten()
-            .flat_map(|k| Id::from_bytes(k.value()))
-            .collect();
+            .map(|k| Id::from_bytes(k.value()))
+            .collect::<Result<Vec<_>, _>>()?;
 
         let mut keysets = vec![];
 

+ 3 - 2
crates/cdk-rexie/src/wallet.rs

@@ -429,8 +429,9 @@ impl WalletDatabase for WalletRexieDatabase {
 
         Ok(quotes
             .into_iter()
-            .flat_map(|(_id, q)| serde_wasm_bindgen::from_value(q))
-            .collect())
+            .map(|(_id, q)| serde_wasm_bindgen::from_value(q))
+            .collect::<Result<Vec<MintQuote>, serde_wasm_bindgen::Error>>()
+            .map_err(<serde_wasm_bindgen::Error as Into<Error>>::into)?)
     }
 
     async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err> {

+ 12 - 6
crates/cdk-sqlite/src/mint/mod.rs

@@ -287,7 +287,10 @@ FROM mint_quote
         .await
         .map_err(Error::from)?;
 
-        let mint_quotes = rec.into_iter().flat_map(sqlite_row_to_mint_quote).collect();
+        let mint_quotes = rec
+            .into_iter()
+            .map(sqlite_row_to_mint_quote)
+            .collect::<Result<Vec<MintQuote>, _>>()?;
 
         Ok(mint_quotes)
     }
@@ -362,7 +365,10 @@ FROM melt_quote
         .await
         .map_err(Error::from)?;
 
-        let melt_quotes = rec.into_iter().flat_map(sqlite_row_to_melt_quote).collect();
+        let melt_quotes = rec
+            .into_iter()
+            .map(sqlite_row_to_melt_quote)
+            .collect::<Result<Vec<mint::MeltQuote>, _>>()?;
 
         Ok(melt_quotes)
     }
@@ -477,8 +483,8 @@ FROM keyset;
 
         Ok(recs
             .into_iter()
-            .flat_map(sqlite_row_to_keyset_info)
-            .collect())
+            .map(sqlite_row_to_keyset_info)
+            .collect::<Result<_, _>>()?)
     }
 
     async fn add_proofs(&self, proofs: Proofs) -> Result<(), Self::Err> {
@@ -733,8 +739,8 @@ WHERE keyset_id=?;
         let signatures = rec
             .map_err(Error::from)?
             .into_iter()
-            .flat_map(sqlite_row_to_blind_signature)
-            .collect();
+            .map(sqlite_row_to_blind_signature)
+            .collect::<Result<_, _>>()?;
 
         Ok(signatures)
     }

+ 8 - 2
crates/cdk-sqlite/src/wallet/mod.rs

@@ -272,7 +272,10 @@ WHERE mint_url=?
             },
         };
 
-        let keysets: Vec<KeySetInfo> = recs.iter().flat_map(sqlite_row_to_keyset).collect();
+        let keysets = recs
+            .iter()
+            .map(sqlite_row_to_keyset)
+            .collect::<Result<Vec<KeySetInfo>, _>>()?;
 
         match keysets.is_empty() {
             false => Ok(Some(keysets)),
@@ -363,7 +366,10 @@ FROM mint_quote
         .await
         .map_err(Error::from)?;
 
-        let mint_quotes = rec.iter().flat_map(sqlite_row_to_mint_quote).collect();
+        let mint_quotes = rec
+            .iter()
+            .map(sqlite_row_to_mint_quote)
+            .collect::<Result<_, _>>()?;
 
         Ok(mint_quotes)
     }

+ 5 - 1
crates/cdk/src/cdk_database/mint_memory.rs

@@ -288,7 +288,11 @@ impl MintDatabase for MintMemoryDatabase {
             .cloned()
             .collect();
 
-        let proof_ys: Vec<PublicKey> = proofs_for_id.iter().flat_map(|p| p.y()).collect();
+        let proof_ys = proofs_for_id
+            .iter()
+            .map(|p| p.y())
+            .collect::<Result<Vec<PublicKey>, _>>()?;
+
         assert_eq!(proofs_for_id.len(), proof_ys.len());
 
         let states = self.get_proofs_states(&proof_ys).await?;

+ 8 - 2
crates/cdk/src/cdk_database/mod.rs

@@ -46,9 +46,15 @@ pub enum Error {
     /// CDK Error
     #[error(transparent)]
     Cdk(#[from] crate::error::Error),
-    /// NUT01 Error
+    /// NUT00 Error
     #[error(transparent)]
-    NUT01(#[from] crate::nuts::nut00::Error),
+    NUT00(#[from] crate::nuts::nut00::Error),
+    /// NUT02 Error
+    #[error(transparent)]
+    NUT02(#[from] crate::nuts::nut02::Error),
+    /// Serde Error
+    #[error(transparent)]
+    Serde(#[from] serde_json::Error),
     /// Unknown Quote
     #[error("Unknown Quote")]
     UnknownQuote,

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

@@ -662,11 +662,11 @@ impl Mint {
 
         let proof_count = swap_request.inputs.len();
 
-        let input_ys: Vec<PublicKey> = swap_request
+        let input_ys = swap_request
             .inputs
             .iter()
-            .flat_map(|p| hash_to_curve(&p.secret.to_bytes()))
-            .collect();
+            .map(|p| hash_to_curve(&p.secret.to_bytes()))
+            .collect::<Result<Vec<PublicKey>, _>>()?;
 
         self.localstore
             .add_proofs(swap_request.inputs.clone())
@@ -1000,11 +1000,11 @@ impl Mint {
     /// The [`Proofs`] should be returned to an unspent state and the quote should be unpaid
     #[instrument(skip_all)]
     pub async fn process_unpaid_melt(&self, melt_request: &MeltBolt11Request) -> Result<(), Error> {
-        let input_ys: Vec<PublicKey> = melt_request
+        let input_ys = melt_request
             .inputs
             .iter()
-            .flat_map(|p| hash_to_curve(&p.secret.to_bytes()))
-            .collect();
+            .map(|p| hash_to_curve(&p.secret.to_bytes()))
+            .collect::<Result<Vec<PublicKey>, _>>()?;
 
         self.localstore
             .update_proofs_states(&input_ys, State::Unspent)

+ 5 - 25
crates/cdk/src/nuts/nut01/mod.rs

@@ -6,8 +6,8 @@ use std::collections::BTreeMap;
 use std::ops::{Deref, DerefMut};
 
 use bitcoin::secp256k1;
-use serde::{de, Deserialize, Deserializer, Serialize};
-use serde_json::Value;
+use serde::{Deserialize, Serialize};
+use serde_with::{serde_as, VecSkipError};
 use thiserror::Error;
 
 mod public_key;
@@ -79,34 +79,14 @@ impl Keys {
 }
 
 /// Mint Public Keys [NUT-01]
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde_as]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct KeysResponse {
     /// Keysets
+    #[serde_as(as = "VecSkipError<_>")]
     pub keysets: Vec<KeySet>,
 }
 
-impl<'de> Deserialize<'de> for KeysResponse {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: Deserializer<'de>,
-    {
-        let keys_response: Value = Value::deserialize(deserializer)?;
-
-        let keysets = keys_response
-            .get("keysets")
-            .ok_or(de::Error::custom("Keysets not found"))?
-            .as_array()
-            .ok_or(de::Error::custom("Keysets not found"))?;
-
-        let keysets = keysets
-            .iter()
-            .flat_map(|keyset| serde_json::from_value(keyset.clone()))
-            .collect();
-
-        Ok(KeysResponse { keysets })
-    }
-}
-
 /// Mint keys
 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct MintKeys(BTreeMap<Amount, MintKeyPair>);

+ 4 - 4
crates/cdk/src/nuts/nut11/mod.rs

@@ -720,8 +720,8 @@ where
                 let pubkeys = tag
                     .iter()
                     .skip(1)
-                    .flat_map(|p| PublicKey::from_str(p.as_ref()))
-                    .collect();
+                    .map(|p| PublicKey::from_str(p.as_ref()))
+                    .collect::<Result<Vec<PublicKey>, _>>()?;
 
                 Ok(Self::Refund(pubkeys))
             }
@@ -729,8 +729,8 @@ where
                 let pubkeys = tag
                     .iter()
                     .skip(1)
-                    .flat_map(|p| PublicKey::from_str(p.as_ref()))
-                    .collect();
+                    .map(|p| PublicKey::from_str(p.as_ref()))
+                    .collect::<Result<Vec<PublicKey>, _>>()?;
 
                 Ok(Self::PubKeys(pubkeys))
             }

+ 9 - 6
crates/cdk/src/nuts/nut14/mod.rs

@@ -39,6 +39,9 @@ pub enum Error {
     /// Witness Signatures not provided
     #[error("Witness did not provide signatures")]
     SignaturesNotProvided,
+    /// Secp256k1 error
+    #[error(transparent)]
+    Secp256k1(#[from] bitcoin::secp256k1::Error),
     /// NUT11 Error
     #[error(transparent)]
     NUT11(#[from] super::nut11::Error),
@@ -81,12 +84,12 @@ impl Proof {
                 if let (Some(refund_key), Some(signatures)) =
                     (conditions.refund_keys, &self.witness)
                 {
-                    let signatures: Vec<Signature> = signatures
+                    let signatures = signatures
                         .signatures()
                         .ok_or(Error::SignaturesNotProvided)?
                         .iter()
-                        .flat_map(|s| Signature::from_str(s))
-                        .collect();
+                        .map(|s| Signature::from_str(s))
+                        .collect::<Result<Vec<Signature>, _>>()?;
 
                     // If secret includes refund keys check that there is a valid signature
                     if valid_signatures(self.secret.as_bytes(), &refund_key, &signatures).ge(&1) {
@@ -103,10 +106,10 @@ impl Proof {
                     .as_ref()
                     .ok_or(Error::SignaturesNotProvided)?;
 
-                let signatures: Vec<Signature> = signatures
+                let signatures = signatures
                     .iter()
-                    .flat_map(|s| Signature::from_str(s))
-                    .collect();
+                    .map(|s| Signature::from_str(s))
+                    .collect::<Result<Vec<Signature>, _>>()?;
 
                 if valid_signatures(self.secret.as_bytes(), &pubkey, &signatures).lt(&req_sigs) {
                     return Err(Error::IncorrectSecretKind);

+ 4 - 0
crates/cdk/src/wallet/error.rs

@@ -7,6 +7,7 @@ use thiserror::Error;
 use super::multi_mint_wallet::WalletKey;
 use crate::cdk_database;
 use crate::error::{ErrorCode, ErrorResponse};
+use crate::util::hex;
 
 /// Wallet Error
 #[derive(Debug, Error)]
@@ -75,6 +76,9 @@ pub enum Error {
     ///  Unknown error response
     #[error("Unknown Error response: `{0}`")]
     UnknownErrorResponse(String),
+    /// Hex Error
+    #[error(transparent)]
+    HexError(#[from] hex::Error),
     /// Unknown Wallet
     #[error("Unknown Wallet: `{0}`")]
     UnknownWallet(WalletKey),

+ 20 - 22
crates/cdk/src/wallet/mod.rs

@@ -357,8 +357,8 @@ impl Wallet {
         let proof_ys = proofs
             .iter()
             // Find Y for the secret
-            .flat_map(|p| hash_to_curve(p.secret.as_bytes()))
-            .collect::<Vec<PublicKey>>();
+            .map(|p| hash_to_curve(p.secret.as_bytes()))
+            .collect::<Result<Vec<PublicKey>, _>>()?;
 
         let spendable = self
             .client
@@ -388,8 +388,8 @@ impl Wallet {
                 proofs
                     .iter()
                     // Find Y for the secret
-                    .flat_map(|p| hash_to_curve(p.secret.as_bytes()))
-                    .collect::<Vec<PublicKey>>(),
+                    .map(|p| hash_to_curve(p.secret.as_bytes()))
+                    .collect::<Result<Vec<PublicKey>, _>>()?,
             )
             .await?;
 
@@ -611,7 +611,7 @@ impl Wallet {
 
         let proofs = proofs
             .into_iter()
-            .flat_map(|proof| {
+            .map(|proof| {
                 ProofInfo::new(
                     proof,
                     self.mint_url.clone(),
@@ -619,7 +619,7 @@ impl Wallet {
                     quote_info.unit,
                 )
             })
-            .collect();
+            .collect::<Result<Vec<ProofInfo>, _>>()?;
 
         // Add new proofs to store
         self.localstore.add_proofs(proofs).await?;
@@ -901,10 +901,8 @@ impl Wallet {
                 let send_proofs_info = proofs_to_send
                     .clone()
                     .into_iter()
-                    .flat_map(|proof| {
-                        ProofInfo::new(proof, mint_url.clone(), State::Reserved, *unit)
-                    })
-                    .collect();
+                    .map(|proof| ProofInfo::new(proof, mint_url.clone(), State::Reserved, *unit))
+                    .collect::<Result<Vec<ProofInfo>, _>>()?;
 
                 self.localstore.add_proofs(send_proofs_info).await?;
 
@@ -919,8 +917,8 @@ impl Wallet {
 
         let keep_proofs = change_proofs
             .into_iter()
-            .flat_map(|proof| ProofInfo::new(proof, mint_url.clone(), State::Unspent, *unit))
-            .collect();
+            .map(|proof| ProofInfo::new(proof, mint_url.clone(), State::Unspent, *unit))
+            .collect::<Result<Vec<ProofInfo>, _>>()?;
 
         self.localstore.add_proofs(keep_proofs).await?;
 
@@ -1342,7 +1340,7 @@ impl Wallet {
 
             let change_proofs_info = change_proofs
                 .into_iter()
-                .flat_map(|proof| {
+                .map(|proof| {
                     ProofInfo::new(
                         proof,
                         self.mint_url.clone(),
@@ -1350,7 +1348,7 @@ impl Wallet {
                         quote_info.unit,
                     )
                 })
-                .collect();
+                .collect::<Result<Vec<ProofInfo>, _>>()?;
 
             self.localstore.add_proofs(change_proofs_info).await?;
         }
@@ -1535,11 +1533,11 @@ impl Wallet {
         // Map hash of preimage to preimage
         let hashed_to_preimage: HashMap<String, &String> = preimages
             .iter()
-            .flat_map(|p| match hex::decode(p) {
-                Ok(hex_bytes) => Some((Sha256Hash::hash(&hex_bytes).to_string(), p)),
-                Err(_) => None,
+            .map(|p| {
+                let hex_bytes = hex::decode(p)?;
+                Ok::<(String, &String), Error>((Sha256Hash::hash(&hex_bytes).to_string(), p))
             })
-            .collect();
+            .collect::<Result<HashMap<String, &String>, _>>()?;
 
         let p2pk_signing_keys: HashMap<XOnlyPublicKey, &SecretKey> = p2pk_signing_keys
             .iter()
@@ -1628,8 +1626,8 @@ impl Wallet {
             total_amount += proofs.iter().map(|p| p.amount).sum();
             let proofs = proofs
                 .into_iter()
-                .flat_map(|proof| ProofInfo::new(proof, mint.clone(), State::Unspent, self.unit))
-                .collect();
+                .map(|proof| ProofInfo::new(proof, mint.clone(), State::Unspent, self.unit))
+                .collect::<Result<Vec<ProofInfo>, _>>()?;
             self.localstore.add_proofs(proofs).await?;
         }
 
@@ -1766,10 +1764,10 @@ impl Wallet {
 
                 let unspent_proofs = unspent_proofs
                     .into_iter()
-                    .flat_map(|proof| {
+                    .map(|proof| {
                         ProofInfo::new(proof, self.mint_url.clone(), State::Unspent, keyset.unit)
                     })
-                    .collect();
+                    .collect::<Result<Vec<ProofInfo>, _>>()?;
 
                 self.localstore.add_proofs(unspent_proofs).await?;