primitives: Remove serde derives from all types
What changed, and why it matters
This commit removes the automatic serde serialization/deserialization macros from the rust-bitcoin primitives crate and replaces them with hand-written implementations. It is a code-quality and dependency-reduction change, not a security fix. There is no evidence in the commit or supplied references that this addresses a vulnerability.
No security action required. Treat as a normal refactoring commit. Reviewers may optionally verify that the new explicit serde impls preserve backward-compatible wire/JSON formats, but the diff shows no indication of format changes.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change drops the derive feature from the optional serde dependency in primitives/Cargo.toml and replaces #[derive(Serialize, Deserialize)] with explicit Serialize/Deserialize impls for Version types in block.rs and transaction.rs. In transaction.rs, the previously derive-generated field identifier enum for OutPoint deserialization is replaced by a manually implemented Deserialize for OutPointField. The dev-dependencies add serde with derive for tests. No functional behavior change is visible in the diff; the explicit impls mirror the derived behavior (e.g., serializing the inner integer via to_consensus()/to_u32() and deserializing via the corresponding constructors).
Changed components
primitives/Cargo.tomlprimitives/src/block.rsprimitives/src/transaction.rsprimitives/src/lib.rsInspect captured patch +106 / −15
### primitives/Cargo.toml
@@ -29,11 +29,12 @@ units = { package = "bitcoin-units", path = "../units", version = "0.7.0", defau
arbitrary = { version = "1.4.1", optional = true }
hex = { package = "hex-conservative", version = "1.1.0", default-features = false, optional = true }
-serde = { version = "1.0.195", default-features = false, features = ["derive", "alloc"], optional = true }
+serde = { version = "1.0.195", default-features = false, features = ["alloc"], optional = true }
[dev-dependencies]
serde_json = "1.0.68"
bincode = "1.3.1"
+serde = { version = "1.0.195", default-features = false, features = ["derive"] }
[package.metadata.docs.rs]
all-features = true
### primitives/src/block.rs
@@ -78,6 +78,8 @@ use encoding::{Decoder2, Encoder2, PrefixedSliceEncoder, VecDecoder};
use hashes::sha256d;
#[cfg(feature = "alloc")]
use hashes::HashEngine as _;
+#[cfg(feature = "serde")]
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "hex")]
use crate::hex_codec::HexPrimitive;
@@ -945,7 +947,6 @@ impl From<&Header> for BlockHash {
/// * [BIP-0009 - Version bits with timeout and delay](https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki) (current usage)
/// * [BIP-0034 - Block v2, Height in Coinbase](https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki)
#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Version(i32);
impl Version {
@@ -1028,6 +1029,28 @@ impl Default for Version {
fn default() -> Self { Self::NO_SOFT_FORK_SIGNALLING }
}
+#[cfg(feature = "serde")]
+impl Serialize for Version {
+ #[inline]
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ i32::serialize(&self.to_consensus(), s)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for Version {
+ #[inline]
+ fn deserialize<D>(d: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok(Self::from_consensus(i32::deserialize(d)?))
+ }
+}
+
impl encoding::Encode for Version {
type Encoder<'e> = VersionEncoder<'e>;
#[inline]
### primitives/src/lib.rs
@@ -72,7 +72,6 @@ pub extern crate encoding;
#[cfg(feature = "hex")]
pub extern crate hex;
#[cfg(feature = "serde")]
-#[macro_use]
pub extern crate serde;
mod hash_types;
### primitives/src/transaction.rs
@@ -1171,13 +1171,6 @@ impl<'de> Deserialize<'de> for OutPoint {
deserializer.deserialize_str(StringVisitor)
} else {
- #[derive(Deserialize)]
- #[serde(field_identifier, rename_all = "lowercase")]
- enum Field {
- Txid,
- Vout,
- }
-
struct OutPointVisitor;
impl<'de> de::Visitor<'de> for OutPointVisitor {
@@ -1208,14 +1201,14 @@ impl<'de> Deserialize<'de> for OutPoint {
while let Some(key) = map.next_key()? {
match key {
- Field::Txid => {
+ OutPointField::Txid => {
if txid.is_some() {
return Err(de::Error::duplicate_field("txid"));
}
let bytes: [u8; 32] = map.next_value()?;
txid = Some(Txid::from_byte_array(bytes));
}
- Field::Vout => {
+ OutPointField::Vout => {
if vout.is_some() {
return Err(de::Error::duplicate_field("vout"));
}
@@ -1232,9 +1225,63 @@ impl<'de> Deserialize<'de> for OutPoint {
}
}
- const FIELDS: &[&str] = &["txid", "vout"];
- deserializer.deserialize_struct("OutPoint", FIELDS, OutPointVisitor)
+ deserializer.deserialize_struct("OutPoint", OutPointField::NAMES, OutPointVisitor)
+ }
+ }
+}
+
+/// A field of [`OutPoint`] when deserializing from a non-human-readable format.
+#[cfg(feature = "serde")]
+enum OutPointField {
+ Txid,
+ Vout,
+}
+
+#[cfg(feature = "serde")]
+impl OutPointField {
+ const NAMES: &'static [&'static str] = &["txid", "vout"];
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for OutPointField {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct FieldVisitor;
+
+ impl de::Visitor<'_> for FieldVisitor {
+ type Value = OutPointField;
+
+ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str("field identifier")
+ }
+
+ fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
+ match v {
+ 0 => Ok(OutPointField::Txid),
+ 1 => Ok(OutPointField::Vout),
+ _ => Err(E::invalid_value(
+ de::Unexpected::Unsigned(v),
+ &"field index 0 <= i < 2",
+ )),
+ }
+ }
+
+ fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
+ self.visit_bytes(v.as_bytes())
+ }
+
+ fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
+ match v {
+ b"txid" => Ok(OutPointField::Txid),
+ b"vout" => Ok(OutPointField::Vout),
+ _ => {
+ let v = crate::prelude::String::from_utf8_lossy(v);
+ Err(E::unknown_field(&v, OutPointField::NAMES))
+ }
+ }
+ }
}
+
+ deserializer.deserialize_identifier(FieldVisitor)
}
}
@@ -1250,7 +1297,6 @@ impl<'de> Deserialize<'de> for OutPoint {
/// [BIP-0068]: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
/// [BIP-0431]: https://github.com/bitcoin/bips/blob/master/bip-0431.mediawiki
#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Version(u32);
impl Version {
@@ -1315,6 +1361,28 @@ impl From<Version> for u32 {
fn from(version: Version) -> Self { version.0 }
}
+#[cfg(feature = "serde")]
+impl Serialize for Version {
+ #[inline]
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ u32::serialize(&self.to_u32(), s)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for Version {
+ #[inline]
+ fn deserialize<D>(d: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok(Self::maybe_non_standard(u32::deserialize(d)?))
+ }
+}
+
impl encoding::Encode for Version {
type Encoder<'e> = VersionEncoder<'e>;
#[inline]Why this scored 17/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.