Merge rust-bitcoin/rust-bitcoin#2576: Return error when constructing pubkey from slice

6ecc41d126 Return error when constructing pubkey from slice (Tobin C. Harding)

Pull request description:

  This PR fixes a bug introduced by me in #2473, and uncovered by #2563 - amazing that it was found so quickly!

  Constructing a pubkey using `PublicKey::from_slice` can fail for reasons other than just incorrect length - we should not be using `expect` but rather returning the error.

  A purist might argue that we are now returning a nested error type with an unreachable variant:

    `ParsePublicKeyError::Encoding(FromSliceError::InvalidLength)`

  Is this acceptable or do we want to further improve this?

ACKs for top commit:
  sanket1729:
    ACK 6ecc41d126
  apoelstra:
    ACK 6ecc41d126

Tree-SHA512: ae8299b21c4787a104f98533105308e8e7678cd5a29b78c30012982d741c05ba5f2bb1edd1d61d3a5ce028235d18c1511e1f94207479bc19e88cfec7a7ca1737
This commit is contained in:
Andrew Poelstra 2024-03-14 06:54:43 +00:00
commit e0d58a9c1c
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 2 additions and 2 deletions

View File

@ -241,14 +241,14 @@ impl FromStr for PublicKey {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
InvalidLength(_) => unreachable!("length checked already")
})?;
Ok(PublicKey::from_slice(&bytes).expect("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()),
InvalidLength(_) => unreachable!("length checked already")
})?;
Ok(PublicKey::from_slice(&bytes).expect("length checked already"))
Ok(PublicKey::from_slice(&bytes)?)
}
len => Err(ParsePublicKeyError::InvalidHexLength(len)),
}