Skip to content

Commit 971c424

Browse files
Replace map_err closures with ResultExt convenience methods (#606)
Add `map_err_display_alt`, `map_err_debug`, and `map_err_prefix` to `ResultExt` trait, then replace all manual `.map_err(|e| Variant(e.to_string()))` and similar patterns across the codebase with the appropriate method.
1 parent c9a01cf commit 971c424

File tree

23 files changed

+221
-118
lines changed

23 files changed

+221
-118
lines changed

rust/Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust/crates/cove-cspp/src/cspp.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use cove_util::ResultExt as _;
12
use std::sync::{Arc, LazyLock, Mutex};
23

34
use arc_swap::ArcSwapOption;
@@ -77,18 +78,15 @@ impl<S: CsppStore> Cspp<S> {
7778
let hex = hex::encode(master_key.as_bytes());
7879
let cryptor = Cryptor::new();
7980

80-
let encrypted =
81-
cryptor.encrypt_to_string(&hex).map_err(|e| CsppError::Encrypt(e.to_string()))?;
81+
let encrypted = cryptor.encrypt_to_string(&hex).map_err_str(CsppError::Encrypt)?;
8282

8383
let encryption_key = cryptor.serialize_to_string();
8484

8585
self.0
8686
.save(MASTER_KEY_ENCRYPTION_KEY_AND_NONCE.into(), encryption_key)
87-
.map_err(|e| CsppError::Save(e.to_string()))?;
87+
.map_err_str(CsppError::Save)?;
8888

89-
self.0
90-
.save(MASTER_KEY_NAME.into(), encrypted)
91-
.map_err(|e| CsppError::Save(e.to_string()))?;
89+
self.0.save(MASTER_KEY_NAME.into(), encrypted).map_err_str(CsppError::Save)?;
9290

9391
Ok(())
9492
}
@@ -103,15 +101,13 @@ impl<S: CsppStore> Cspp<S> {
103101
return Ok(None);
104102
};
105103

106-
let cryptor = Cryptor::try_from_string(&encryption_secret)
107-
.map_err(|e| CsppError::Decrypt(e.to_string()))?;
104+
let cryptor =
105+
Cryptor::try_from_string(&encryption_secret).map_err_str(CsppError::Decrypt)?;
108106

109-
let hex = cryptor
110-
.decrypt_from_string(&encrypted)
111-
.map_err(|e| CsppError::Decrypt(e.to_string()))?;
107+
let hex = cryptor.decrypt_from_string(&encrypted).map_err_str(CsppError::Decrypt)?;
112108

113109
let bytes: [u8; 32] = hex::decode(hex)
114-
.map_err(|e| CsppError::InvalidData(e.to_string()))?
110+
.map_err_str(CsppError::InvalidData)?
115111
.try_into()
116112
.map_err(|_| CsppError::InvalidData("master key not 32 bytes".into()))?;
117113

rust/crates/cove-types/src/address.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use cove_util::ResultExt as _;
12
use std::hash::Hash;
23
use std::str::FromStr as _;
34
use std::{hash::Hasher, sync::Arc};
@@ -147,7 +148,7 @@ impl Address {
147148
let script = output.script_pubkey.clone().into_boxed_script();
148149

149150
let address = BdkAddress::from_script(&script, Params::from(network))
150-
.map_err(|e| Error::ScriptError(e.to_string()))?;
151+
.map_err_str(Error::ScriptError)?;
151152

152153
Ok(Self::new(address))
153154
}

rust/crates/cove-types/src/confirm.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use cove_util::ResultExt as _;
12
use std::sync::Arc;
23

34
use ahash::AHashMap as HashMap;
@@ -311,7 +312,7 @@ impl ConfirmDetails {
311312
max_version: version,
312313
},
313314
)
314-
.map_err(|e| ConfirmDetailsError::QrCodeCreation(e.to_string()))?;
315+
.map_err_str(ConfirmDetailsError::QrCodeCreation)?;
315316

316317
Ok(split.parts)
317318
}

rust/crates/cove-types/src/psbt.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use bdk_wallet::psbt::PsbtUtils as _;
22
use bitcoin::{Amount as BdkAmount, TxIn, TxOut};
3+
use cove_util::ResultExt as _;
34
use derive_more::{AsRef, Deref, From, Into};
45
use std::fmt::Debug;
56

@@ -48,7 +49,7 @@ impl Psbt {
4849
#[uniffi::constructor(name = "new")]
4950
#[allow(clippy::needless_pass_by_value)] // uniffi requires Vec by value
5051
pub fn try_new(data: Vec<u8>) -> Result<Self> {
51-
let psbt = BdkPsbt::deserialize(&data).map_err(|e| PsbtError::Other(e.to_string()))?;
52+
let psbt = BdkPsbt::deserialize(&data).map_err_str(PsbtError::Other)?;
5253
Ok(psbt.into())
5354
}
5455

rust/crates/cove-ur/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ foundation-ur = { workspace = true }
1717
pubport = { workspace = true }
1818
hex = { workspace = true }
1919
tracing = { workspace = true }
20+
cove-util = { path = "../cove-util" }
2021

2122
[dev-dependencies]
2223
serde_json = { workspace = true }

rust/crates/cove-ur/src/coin_info.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! crypto-coin-info: Cryptocurrency coin info
22
//! BCR-2020-007: <https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2020-007-hdkey.md>
33
4+
use cove_util::ResultExt as _;
45
use minicbor::{Decode, Encode};
56

67
use crate::error::{Result, ToUrError, UrError};
@@ -31,7 +32,7 @@ impl CryptoCoinInfo {
3132
/// # Errors
3233
/// Returns error if CBOR encoding fails
3334
pub fn to_cbor(&self) -> Result<Vec<u8>> {
34-
minicbor::to_vec(self).map_err(|e| UrError::CborEncodeError(e.to_string()))
35+
minicbor::to_vec(self).map_err_str(UrError::CborEncodeError)
3536
}
3637

3738
/// Decode from tagged CBOR

rust/crates/cove-ur/src/crypto_hdkey.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
//! 5. Derive macros cannot express this embedded CBOR pattern cleanly
1010
1111
use bitcoin::bip32::{Xpriv, Xpub};
12+
use cove_util::ResultExt as _;
1213
use minicbor::{Decoder, Encoder, data::Tag};
1314

1415
use crate::{
@@ -389,8 +390,8 @@ impl CryptoHdkey {
389390
return Err(UrError::MasterKeyNotAllowed);
390391
}
391392

392-
let public_key = PublicKey::from_slice(&self.key_data)
393-
.map_err(|e| UrError::InvalidKeyData(e.to_string()))?;
393+
let public_key =
394+
PublicKey::from_slice(&self.key_data).map_err_str(UrError::InvalidKeyData)?;
394395

395396
let chain_code = self
396397
.chain_code

rust/crates/cove-ur/src/crypto_psbt.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//! 3. Derive macros don't provide significant simplification for this structure
88
99
use bitcoin::psbt::Psbt as BdkPsbt;
10+
use cove_util::ResultExt as _;
1011
use foundation_ur::{UR, bytewords};
1112
use minicbor::{Decoder, Encoder, data::Tag};
1213

@@ -35,7 +36,7 @@ impl CryptoPsbt {
3536
/// Returns error if PSBT deserialization fails
3637
pub fn from_bytes(psbt_bytes: &[u8]) -> Result<Self> {
3738
let psbt = BdkPsbt::deserialize(psbt_bytes)
38-
.map_err(|e| UrError::CborDecodeError(format!("Invalid PSBT: {e}")))?;
39+
.map_err_prefix("Invalid PSBT", UrError::CborDecodeError)?;
3940
Ok(Self { psbt })
4041
}
4142

@@ -63,10 +64,10 @@ impl CryptoPsbt {
6364
let mut encoder = Encoder::new(&mut buffer);
6465

6566
// write tag 310
66-
encoder.tag(Tag::new(CRYPTO_PSBT)).map_err(|e| UrError::CborEncodeError(e.to_string()))?;
67+
encoder.tag(Tag::new(CRYPTO_PSBT)).map_err_str(UrError::CborEncodeError)?;
6768

6869
// write PSBT as byte string
69-
encoder.bytes(&psbt_bytes).map_err(|e| UrError::CborEncodeError(e.to_string()))?;
70+
encoder.bytes(&psbt_bytes).map_err_str(UrError::CborEncodeError)?;
7071

7172
Ok(buffer)
7273
}
@@ -95,7 +96,7 @@ impl CryptoPsbt {
9596

9697
// deserialize PSBT
9798
let psbt = BdkPsbt::deserialize(&psbt_bytes)
98-
.map_err(|e| UrError::CborDecodeError(format!("Invalid PSBT: {e}")))?;
99+
.map_err_prefix("Invalid PSBT", UrError::CborDecodeError)?;
99100

100101
Ok(Self { psbt })
101102
}
@@ -115,7 +116,7 @@ impl CryptoPsbt {
115116
/// # Errors
116117
/// Returns error if UR parsing or CBOR decoding fails
117118
pub fn from_ur_string(ur: &str) -> Result<Self> {
118-
let ur = UR::parse(ur).map_err(|e| UrError::UrParseError(e.to_string()))?;
119+
let ur = UR::parse(ur).map_err_str(UrError::UrParseError)?;
119120

120121
// verify UR type
121122
if ur.as_type() != "crypto-psbt" {
@@ -130,7 +131,7 @@ impl CryptoPsbt {
130131
UR::SinglePart { message, .. } => {
131132
// decode bytewords to bytes (UR uses minimal style)
132133
bytewords::decode(message, bytewords::Style::Minimal)
133-
.map_err(|e| UrError::UrParseError(format!("Bytewords decode error: {e}")))?
134+
.map_err_prefix("Bytewords decode error", UrError::UrParseError)?
134135
}
135136
UR::SinglePartDeserialized { message, .. } => {
136137
// already deserialized

rust/crates/cove-ur/src/crypto_seed.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
//! BCR-2020-006: <https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2020-006-urtypes.md>
33
44
use bip39::Mnemonic;
5+
use cove_util::ResultExt as _;
56
use minicbor::{Decode, Encode};
67

78
use crate::{
@@ -71,7 +72,7 @@ impl CryptoSeed {
7172
/// Returns error if entropy is invalid for BIP39
7273
pub fn to_mnemonic(&self) -> Result<Mnemonic> {
7374
Mnemonic::from_entropy(&self.payload)
74-
.map_err(|e| UrError::InvalidField(format!("Invalid BIP39 entropy: {e}")))
75+
.map_err_prefix("Invalid BIP39 entropy", UrError::InvalidField)
7576
}
7677

7778
/// Encode as tagged CBOR
@@ -86,7 +87,7 @@ impl CryptoSeed {
8687
name: self.name.clone(),
8788
note: self.note.clone(),
8889
};
89-
minicbor::to_vec(&cbor).map_err(|e| UrError::CborEncodeError(e.to_string()))
90+
minicbor::to_vec(&cbor).map_err_str(UrError::CborEncodeError)
9091
}
9192

9293
/// Decode from tagged CBOR

0 commit comments

Comments
 (0)