Merge rust-bitcoin/rust-bitcoin#7009: primitives: Fix hash serde invalid length error message
What changed, and why it matters
This commit fixes only the wording of an error message shown when someone tries to deserialize a Bitcoin hash from the wrong number of bytes. It does not change any security behavior, validation, or data handling; it only makes the error message include the expected length (e.g., '32') instead of the placeholder text 'N'.
No security action needed; this is a cosmetic/test-only fix to an error message.
Security signals we found
No strong security signals were identified.
Evidence from the diff
In primitives/src/hash_types/mod.rs, the serde visitor for fixed-size hashes changed its expecting implementation to print the concrete expected byte length and passes &self to E::invalid_length so serde uses that expecting text. A test was added verifying the error string contains ’ 32 ’ when a 31-byte slice is deserialized as a 32-byte Txid. No cryptographic or parsing logic changed.
Changed components
primitives/src/hash_types/mod.rs serde_details visitorInspect captured patch +13 / −5
### primitives/src/hash_types/mod.rs
@@ -181,17 +181,15 @@ pub mod serde_details {
type Value = [u8; N];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("a bytestring")
+ write!(formatter, "a sequence of {} bytes", N)
}
fn visit_bytes<E>(self, v: &[u8]) -> core::result::Result<Self::Value, E>
where
E: de::Error,
{
- let bytes = <[u8; N]>::try_from(v).map_err(|_| {
- // from_slice only errors on incorrect length
- E::invalid_length(v.len(), &stringify!(N))
- })?;
+ // `try_from` only errors on incorrect length.
+ let bytes = <[u8; N]>::try_from(v).map_err(|_| E::invalid_length(v.len(), &self))?;
Ok(bytes)
}
@@ -229,6 +227,16 @@ mod tests {
assert_eq!(got, tc);
}
+ #[test]
+ #[cfg(feature = "serde")]
+ fn serde_non_human_readable_wrong_length() {
+ use alloc::string::ToString as _;
+
+ let ser = bincode::serialize(&[0u8; 31].as_slice()).unwrap();
+ let err = bincode::deserialize::<Txid>(&ser).unwrap_err();
+ assert!(err.to_string().contains(" 32 "));
+ }
+
#[test]
#[cfg(feature = "serde")] // Implies alloc and hex
fn serde_non_human_readable_roundtrips() {Why this scored 20/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.