Return error when constructing pubkey from slice

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?
This commit is contained in:
Tobin C. Harding 2024-03-13 09:17:32 +11:00
parent 6f6cc00eb7
commit 6ecc41d126
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
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()), InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
InvalidLength(_) => unreachable!("length checked already") InvalidLength(_) => unreachable!("length checked already")
})?; })?;
Ok(PublicKey::from_slice(&bytes).expect("length checked already")) Ok(PublicKey::from_slice(&bytes)?)
}, },
130 => { 130 => {
let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e { let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()), InvalidChar(e) => ParsePublicKeyError::InvalidChar(e.invalid_char()),
InvalidLength(_) => unreachable!("length checked already") InvalidLength(_) => unreachable!("length checked already")
})?; })?;
Ok(PublicKey::from_slice(&bytes).expect("length checked already")) Ok(PublicKey::from_slice(&bytes)?)
} }
len => Err(ParsePublicKeyError::InvalidHexLength(len)), len => Err(ParsePublicKeyError::InvalidHexLength(len)),
} }