Merge rust-bitcoin/rust-bitcoin#3847: ParsePublicKeyError using hex::InvalidCharError

945fcd0920 fix ParsePublicKeyError using hex::InvalidCharError (Innocent Onyemaenu)

Pull request description:

  Replaced the InvalidChar variant u8 with hex::InvalidCharError

  Resolves #3835

  changed InvalidChar variant of the ParsePublicKeyError from `u8` to `hex::InvalidCharError`

  ```
  pub enum ParsePublicKeyError {
      ...
      /// Hex decoding error.
      InvalidChar(hex::InvalidCharError),
      ...
  }

  Also,

  modified the test cases to accommodate the new variant

  Why:
  - hex::InvalidCharError includes both the invalid character and its position.
  - This improves debugging and makes error messages more actionable.

ACKs for top commit:
  apoelstra:
    ACK 945fcd09209120ef8869a2e4165e866328cc9bd5; successfully ran local tests; I like it
  clarkmoody:
    utACK 945fcd0920

Tree-SHA512: c13446c099cb02b4f253f9cc559a860aff3288a2cc5eac96d3cf910bf63e78957741bbdff69b936b16b36e46b366841a5c94876d16cbc0c41aea2a70866a6e45
This commit is contained in:
merge-script 2025-01-04 01:05:04 +00:00
commit 72cc88d907
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 15 additions and 5 deletions

View File

@ -241,14 +241,14 @@ impl FromStr for PublicKey {
match s.len() {
66 => {
let bytes = <[u8; 33]>::from_hex(s).map_err(|e| match e {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
InvalidLength(_) => unreachable!("length checked already"),
})?;
Ok(PublicKey::from_slice(&bytes)?)
}
130 => {
let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
InvalidLength(_) => unreachable!("length checked already"),
})?;
Ok(PublicKey::from_slice(&bytes)?)
@ -1017,7 +1017,7 @@ pub enum ParsePublicKeyError {
/// Error originated while parsing string.
Encoding(FromSliceError),
/// Hex decoding error.
InvalidChar(u8),
InvalidChar(hex::InvalidCharError),
/// `PublicKey` hex should be 66 or 130 digits long.
InvalidHexLength(usize),
}
@ -1520,12 +1520,22 @@ mod tests {
assert_eq!(s.len(), 130);
let res = s.parse::<PublicKey>();
assert!(res.is_err());
assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
if let Err(ParsePublicKeyError::InvalidChar(err)) = res {
assert_eq!(err.invalid_char(), b'g');
assert_eq!(err.pos(), 129);
} else {
panic!("Expected Invalid char error");
}
let s = "032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1ag";
assert_eq!(s.len(), 66);
let res = s.parse::<PublicKey>();
assert!(res.is_err());
assert_eq!(res.unwrap_err(), ParsePublicKeyError::InvalidChar(103));
if let Err(ParsePublicKeyError::InvalidChar(err)) = res {
assert_eq!(err.invalid_char(), b'g');
assert_eq!(err.pos(), 65);
} else {
panic!("Expected Invalid char error");
}
}
}