Skip to content

Commit 945fcd0

Browse files
committed
fix ParsePublicKeyError using hex::InvalidCharError
What: - Replaced the InvalidChar variant u8 with hex::InvalidCharError Why: - hex::InvalidCharError includes both the invalid character and its position. - This improves debugging and makes error messages more actionable.
1 parent 16b5220 commit 945fcd0

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

bitcoin/src/crypto/key.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -241,14 +241,14 @@ impl FromStr for PublicKey {
241241
match s.len() {
242242
66 => {
243243
let bytes = <[u8; 33]>::from_hex(s).map_err(|e| match e {
244-
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
244+
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
245245
InvalidLength(_) => unreachable!("length checked already"),
246246
})?;
247247
Ok(PublicKey::from_slice(&bytes)?)
248248
}
249249
130 => {
250250
let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e {
251-
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
251+
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
252252
InvalidLength(_) => unreachable!("length checked already"),
253253
})?;
254254
Ok(PublicKey::from_slice(&bytes)?)
@@ -1017,7 +1017,7 @@ pub enum ParsePublicKeyError {
10171017
/// Error originated while parsing string.
10181018
Encoding(FromSliceError),
10191019
/// Hex decoding error.
1020-
InvalidChar(u8),
1020+
InvalidChar(hex::InvalidCharError),
10211021
/// `PublicKey` hex should be 66 or 130 digits long.
10221022
InvalidHexLength(usize),
10231023
}
@@ -1520,12 +1520,22 @@ mod tests {
15201520
assert_eq!(s.len(), 130);
15211521
let res = s.parse::<PublicKey>();
15221522
assert!(res.is_err());
1523-
assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1523+
if let Err(ParsePublicKeyError::InvalidChar(err)) = res {
1524+
assert_eq!(err.invalid_char(), b'g');
1525+
assert_eq!(err.pos(), 129);
1526+
} else {
1527+
panic!("Expected Invalid char error");
1528+
}
15241529

15251530
let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1ag";
15261531
assert_eq!(s.len(), 66);
15271532
let res = s.parse::<PublicKey>();
15281533
assert!(res.is_err());
1529-
assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
1534+
if let Err(ParsePublicKeyError::InvalidChar(err)) = res {
1535+
assert_eq!(err.invalid_char(), b'g');
1536+
assert_eq!(err.pos(), 65);
1537+
} else {
1538+
panic!("Expected Invalid char error");
1539+
}
15301540
}
15311541
}

0 commit comments

Comments
 (0)