Ungate FromStr and Display for Xpriv and Xpub
What changed, and why it matters
This commit removes a feature gate so that two Bitcoin key types (Xpriv and Xpub) can be converted to and from their standard text representation even when the library is built without memory allocation support. It also swaps the underlying base58 error type to one that works in no-alloc builds. The change is a portability/cleanup refactor, not a fix for an active security bug.
No security action required. Review as normal code-quality/portability change. If consuming this library, verify no breaking changes in error variant matching for downstream code that previously matched InvalidBase58PayloadLength directly.
Security signals we found
No security-relevant signal in commit message or diff
Refactor to support no-alloc builds
Error type changed from DecodeCheckError to DecodeCheckArrayError
Fixed 78-byte payload size used for bounded base58 encode/decode
No mention of CVE, advisory, researcher, or security bug
Evidence from the diff
The patch ungates fmt::Display and FromStr for Xpriv and Xpub so they are available without the alloc feature. Encoding now uses base58::Base58CkString::encode (bounded) instead of encode_unbounded, with an unwrap/expect justified by the fixed 78-byte payload. Decoding now uses base58::decode_check_to_array::<78>, moving length validation into the base58 layer. ParseXprivError and ParseXpubError now wrap DecodeCheckArrayError instead of DecodeCheckError, and the InvalidBase58PayloadLength variant becomes effectively unused for the length-mismatch path because the array API reports it via the Base58 variant. Tests are updated to expect Base58 invalid-length errors. There is no evidence of a vulnerability being fixed; it is an API availability and error-type consistency change.
Changed components
key_expression/src/bip32.rsXpriv Display/FromStr implementationsXpub Display/FromStr implementationsParseXprivError / ParseXpubError enum definitionsInspect captured patch +16 / −47
### key_expression/src/bip32.rs
@@ -27,12 +27,9 @@ pub use self::error::{
CannotDeriveHardenedChildError, DeriveXpubError, IndexOutOfRangeError,
InvalidBase58PayloadLengthError, InvalidSeedLengthError, InvalidXkeyPartsError,
MaximumDepthExceededError, ParseAbsoluteDerivationPathError, ParseChildNumberError,
- ParseRelativeDerivationPathError, XkeyDecodeError, XprivDecodeError, XpubDecodeError,
+ ParseRelativeDerivationPathError, ParseXprivError, ParseXpubError, XkeyDecodeError,
+ XprivDecodeError, XpubDecodeError,
};
-#[rustfmt::skip]
-#[cfg(feature = "alloc")]
-#[doc(no_inline)]
-pub use self::error::{ParseXprivError, ParseXpubError};
/// Version bytes for extended public keys on Bitcoin Mainnet.
const VERSION_BYTES_MAINNET_PUBLIC: [u8; 4] = [0x04, 0x88, 0xB2, 0x1E];
@@ -1264,47 +1261,37 @@ impl Xpub {
}
}
-#[cfg(feature = "alloc")]
impl fmt::Display for Xpriv {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- base58::Base58CkString::encode_unbounded(&self.encode()).fmt(fmt)
+ base58::Base58CkString::encode(&self.encode())
+ .expect("78 bytes encode to less than the length limit")
+ .fmt(fmt)
}
}
-#[cfg(feature = "alloc")]
impl FromStr for Xpriv {
type Err = ParseXprivError;
fn from_str(inp: &str) -> Result<Self, ParseXprivError> {
- let data = base58::decode_check(inp)?;
-
- if data.len() != 78 {
- return Err(InvalidBase58PayloadLengthError { length: data.len() })
- .map_err(ParseXprivError::InvalidBase58PayloadLength);
- }
+ let data = base58::decode_check_to_array::<78>(inp).map_err(ParseXprivError::Base58)?;
Self::decode(&data).map_err(ParseXprivError::Decode)
}
}
-#[cfg(feature = "alloc")]
impl fmt::Display for Xpub {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- base58::Base58CkString::encode_unbounded(&self.encode()[..]).fmt(fmt)
+ base58::Base58CkString::encode(&self.encode())
+ .expect("78 bytes encode to less than the length limit")
+ .fmt(fmt)
}
}
-#[cfg(feature = "alloc")]
impl FromStr for Xpub {
type Err = ParseXpubError;
fn from_str(inp: &str) -> Result<Self, ParseXpubError> {
- let data = base58::decode_check(inp)?;
-
- if data.len() != 78 {
- return Err(InvalidBase58PayloadLengthError { length: data.len() })
- .map_err(ParseXpubError::InvalidBase58PayloadLength);
- }
+ let data = base58::decode_check_to_array::<78>(inp).map_err(ParseXpubError::Base58)?;
Self::decode(&data).map_err(ParseXpubError::Decode)
}
@@ -1557,19 +1544,17 @@ pub mod error {
}
/// Error parsing a base58check BIP-0032 xpriv string.
- #[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseXprivError {
/// Base58 encoding error.
- Base58(base58::DecodeCheckError),
+ Base58(base58::DecodeCheckArrayError),
/// Base58 decoded data was an invalid length.
InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
/// Binary xpriv decode error.
Decode(XprivDecodeError),
}
- #[cfg(feature = "alloc")]
impl From<Infallible> for ParseXprivError {
fn from(never: Infallible) -> Self { match never {} }
}
@@ -1585,7 +1570,6 @@ pub mod error {
}
}
- #[cfg(feature = "alloc")]
impl fmt::Display for ParseXprivError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
@@ -1596,25 +1580,18 @@ pub mod error {
}
}
- #[cfg(feature = "alloc")]
- impl From<base58::DecodeCheckError> for ParseXprivError {
- fn from(e: base58::DecodeCheckError) -> Self { Self::Base58(e) }
- }
-
/// Error parsing a base58check BIP-0032 xpub string.
- #[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseXpubError {
/// Base58 encoding error.
- Base58(base58::DecodeCheckError),
+ Base58(base58::DecodeCheckArrayError),
/// Base58 decoded data was an invalid length.
InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
/// Binary xpub decode error.
Decode(XpubDecodeError),
}
- #[cfg(feature = "alloc")]
impl From<Infallible> for ParseXpubError {
fn from(never: Infallible) -> Self { match never {} }
}
@@ -1630,7 +1607,6 @@ pub mod error {
}
}
- #[cfg(feature = "alloc")]
impl fmt::Display for ParseXpubError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
@@ -1641,11 +1617,6 @@ pub mod error {
}
}
- #[cfg(feature = "alloc")]
- impl From<base58::DecodeCheckError> for ParseXpubError {
- fn from(e: base58::DecodeCheckError) -> Self { Self::Base58(e) }
- }
-
/// Attempted to derive a child of depth 256 or higher.
///
/// There is no way to encode such xkeys.
@@ -2687,15 +2658,13 @@ mod tests {
let encoded = base58::Base58CkString::encode(&vec![0u8; len]).unwrap();
match encoded.as_str().parse::<Xpriv>() {
- Err(ParseXprivError::InvalidBase58PayloadLength(e)) =>
- assert_eq!(e.invalid_base58_payload_length(), len),
- result => panic!("Expected InvalidBase58PayloadLength error, got {:?}", result),
+ Err(ParseXprivError::Base58(e)) => assert_eq!(e.invalid_length(), Some((len, 78))),
+ result => panic!("Expected Base58 invalid length error, got {:?}", result),
}
match encoded.as_str().parse::<Xpub>() {
- Err(ParseXpubError::InvalidBase58PayloadLength(e)) =>
- assert_eq!(e.invalid_base58_payload_length(), len),
- result => panic!("Expected InvalidBase58PayloadLength error, got {:?}", result),
+ Err(ParseXpubError::Base58(e)) => assert_eq!(e.invalid_length(), Some((len, 78))),
+ result => panic!("Expected Base58 invalid length error, got {:?}", result),
}
}
}Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.