From 6ecc41d126621862fe2392c7ab510e2ef9ecc960 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 13 Mar 2024 09:17:32 +1100 Subject: [PATCH] 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? --- bitcoin/src/crypto/key.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index e3babd05..7848e8e7 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -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)), }