units: Remove serde derives from all types
What changed, and why it matters
This commit removes the automatic serde (serialization/deserialization) derive feature from the `units` crate and replaces it with hand-written implementations. The stated goal is to reduce compile-time dependencies and make the code easier to reason about. There is no direct security fix here, but any change to serialization behavior carries a small risk of accidentally altering how data is encoded or decoded, which could affect downstream users relying on stable formats.
Review the manual serde implementations for format parity with the previous derive-based behavior, especially for `CompactTarget` and `Sequence` where the consensus `u32` representation is used. Run the existing serde round-trip tests and consider adding tests that compare serialized bytes before and after this change if not already present. No urgent security patch is indicated.
Security signals we found
Behavior-preserving refactor of serialization code
Removal of serde derive dependency reduces macro-generated code and supply-chain surface
Manual serde impls introduce potential for human error in format compatibility
No input validation, bounds checking, or cryptographic logic changes visible in diff
Evidence from the diff
The patch drops features = ["derive"] from the optional serde dependency in units/Cargo.toml. It then replaces #[derive(Serialize, Deserialize)] and #[cfg_attr(feature = "serde", derive(...))] macros with explicit impl Serialize and impl Deserialize blocks for Work, Target, CompactTarget, and Sequence. It also replaces internal #[derive(Deserialize)] #[serde(transparent)] wrapper structs in amount/serde.rs and fee_rate/serde.rs with equivalent manual Deserialize implementations that delegate to existing super::deserialize functions. The functional behavior appears intended to be identical, using the same underlying serialization formats (e.g., U256 for Work/Target, consensus u32 for CompactTarget and Sequence).
Changed components
units/Cargo.tomlunits/src/amount/serde.rsunits/src/fee_rate/serde.rsunits/src/pow.rsunits/src/sequence.rsInspect captured patch +111 / −25
### units/Cargo.toml
@@ -23,7 +23,7 @@ serde = ["dep:serde", "internals/serde"]
internals = { package = "bitcoin-internals", path = "../internals", version = "0.8.2" }
encoding = { package = "bitcoin-consensus-encoding", path = "../consensus_encoding", version = "1.0.0", default-features = false, optional = true }
-serde = { version = "1.0.195", default-features = false, features = ["derive"], optional = true }
+serde = { version = "1.0.195", default-features = false, optional = true }
arbitrary = { version = "1.4.1", optional = true }
[dev-dependencies]
### units/src/amount/serde.rs
@@ -321,9 +321,13 @@ pub mod as_sat {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper<T: AmountOps>(#[serde(with = "super")] T);
+ struct Wrapper<T: AmountOps>(T);
+
+ impl<'de, T: AmountOps> Deserialize<'de> for Wrapper<T> {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(internals::serde::cautious_size_hint::<X>(
seq.size_hint(),
@@ -501,9 +505,13 @@ pub mod as_btc {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper(#[serde(with = "super")] SignedAmount);
+ struct Wrapper(SignedAmount);
+
+ impl<'de> Deserialize<'de> for Wrapper {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(internals::serde::cautious_size_hint::<X>(
seq.size_hint(),
@@ -683,9 +691,13 @@ pub mod as_str {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper(#[serde(with = "super")] SignedAmount);
+ struct Wrapper(SignedAmount);
+
+ impl<'de> Deserialize<'de> for Wrapper {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(internals::serde::cautious_size_hint::<X>(
seq.size_hint(),
### units/src/fee_rate/serde.rs
@@ -138,9 +138,13 @@ pub mod as_sat_per_kwu_floor {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper(#[serde(with = "super")] FeeRate);
+ struct Wrapper(FeeRate);
+
+ impl<'de> Deserialize<'de> for Wrapper {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(
internals::serde::cautious_size_hint::<FeeRate>(seq.size_hint()),
@@ -274,9 +278,13 @@ pub mod as_sat_per_vb_floor {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper(#[serde(with = "super")] FeeRate);
+ struct Wrapper(FeeRate);
+
+ impl<'de> Deserialize<'de> for Wrapper {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(
internals::serde::cautious_size_hint::<FeeRate>(seq.size_hint()),
@@ -410,9 +418,13 @@ pub mod as_sat_per_vb_ceil {
where
A: SeqAccess<'de>,
{
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Wrapper(#[serde(with = "super")] FeeRate);
+ struct Wrapper(FeeRate);
+
+ impl<'de> Deserialize<'de> for Wrapper {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ super::deserialize(d).map(Wrapper)
+ }
+ }
let mut out = Vec::with_capacity(
internals::serde::cautious_size_hint::<FeeRate>(seq.size_hint()),
### units/src/pow.rs
@@ -9,7 +9,7 @@ use core::ops::{Add, Sub};
use arbitrary::{Arbitrary, Unstructured};
use internals::u256::U256;
#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::internal_macros::impl_fmt_traits_for_u32_wrapper;
use crate::parse_int::{self, PrefixedHexError, UnprefixedHexError};
@@ -93,14 +93,35 @@ macro_rules! do_impl {
U256::from_str(s).map($ty).map_err($err_ty)
}
}
+
+ #[cfg(feature = "serde")]
+ impl Serialize for $ty {
+ #[inline]
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ U256::serialize(&self.0, s)
+ }
+ }
+
+ #[cfg(feature = "serde")]
+ impl<'de> Deserialize<'de> for $ty {
+ #[inline]
+ fn deserialize<D>(d: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok($ty(U256::deserialize(d)?))
+ }
+ }
};
}
/// A 256 bit integer representing work.
///
/// Work is a measure of how difficult it is to find a hash below a given [`Target`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Work(U256);
impl Work {
@@ -159,7 +180,6 @@ impl Sub for Work {
///
/// ref: <https://en.bitcoin.it/wiki/Target>
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Target(U256);
impl Target {
@@ -318,7 +338,6 @@ impl_fmt_traits_for_u32_wrapper!(Target);
/// Equality is on the consensus encoded `u32`. Conversion to [`Target`] is lossy, so this type is
/// not ordered. To compare two targets convert them first.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CompactTarget(u32);
impl CompactTarget {
@@ -382,6 +401,28 @@ impl fmt::Display for CompactTarget {
parse_int::impl_parse_str_from_int_infallible!(CompactTarget, u32, from_consensus);
+#[cfg(feature = "serde")]
+impl Serialize for CompactTarget {
+ #[inline]
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ u32::serialize(&self.to_consensus_u32(), s)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for CompactTarget {
+ #[inline]
+ fn deserialize<D>(d: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok(Self::from_consensus(u32::deserialize(d)?))
+ }
+}
+
impl TryFrom<CompactTarget> for Target {
type Error = InvalidCompactTargetError;
### units/src/sequence.rs
@@ -19,7 +19,7 @@ use core::fmt;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::locktime::relative::error::TimeOverflowError;
use crate::locktime::relative::{self, NumberOf512Seconds};
@@ -32,7 +32,6 @@ pub use self::error::SequenceDecoderError;
/// Bitcoin transaction input sequence number.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Sequence(u32);
impl Sequence {
@@ -246,6 +245,28 @@ impl fmt::Debug for Sequence {
parse_int::impl_parse_str_from_int_infallible!(Sequence, u32, from_consensus);
+#[cfg(feature = "serde")]
+impl Serialize for Sequence {
+ #[inline]
+ fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ u32::serialize(&self.to_consensus_u32(), s)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for Sequence {
+ #[inline]
+ fn deserialize<D>(d: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok(Self::from_consensus(u32::deserialize(d)?))
+ }
+}
+
#[cfg(feature = "encoding")]
impl encoding::Encode for Sequence {
type Encoder<'e> = SequenceEncoder<'e>;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.