Skip to content

Commit

Permalink
Return error when constructing pubkey from slice
Browse files Browse the repository at this point in the history
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?
  • Loading branch information
tcharding committed Mar 12, 2024
1 parent 6f6cc00 commit 6ecc41d
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions bitcoin/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
}
Expand Down

0 comments on commit 6ecc41d

Please sign in to comment.