Merge rust-bitcoin/rust-bitcoin#7096: Add x_only_serde module for `XOnlyPublicKey` serde
What changed, and why it matters
This change fixes a data-integrity problem in how a special Bitcoin public key type (XOnlyPublicKey) was being saved and loaded through serde. Previously, the type silently dropped the 'parity' bit during serialization, so an odd-parity key could be serialized and then deserialized as a different, even-parity key. The patch removes the automatic serde implementation and instead offers two explicit modules: one that preserves parity by serializing the full public key, and one that intentionally drops parity. It also removes serde support from Taproot ControlBlock because that structure contained an XOnlyPublicKey and could no longer round-trip safely by default. This is a correctness and API-breaking change, not a remote code-execution vulnerability.
Treat this as a behavioral/API fix rather than an exploitable vulnerability. Downstream users relying on XOnlyPublicKey serde should migrate to either bitcoin::key::x_only_serde::with_parity or without_parity. Review any persisted serialized XOnlyPublicKey or ControlBlock data, because old odd-parity keys may have been silently stored with even parity. No emergency patch is required, but a changelog note and migration guidance are appropriate.
Security signals we found
Loss of cryptographic metadata (parity) during serialization/deserialization
Silent mutation of deserialized X-only public keys with odd parity
API-breaking removal of default serde traits to prevent accidental misuse
Addition of explicit parity-preserving and parity-discarding serde modules
Removal of serde derive on Taproot ControlBlock due to non-roundtripping XOnlyPublicKey field
Evidence from the diff
The commit removes the default Serialize/Deserialize impls for crypto::key::XOnlyPublicKey and bitcoin::taproot::ControlBlock, and introduces a key::x_only_serde module with with_parity and without_parity submodules. The old implementation delegated serialization to the inner secp256k1::XOnlyPublicKey, which cannot encode the Parity stored in the rust-bitcoin wrapper. On deserialization it always supplied Parity::Even, causing odd-parity keys to mutate. The new design forces callers to choose whether parity matters. with_parity serializes via FullPublicKey and round-trips; without_parity matches the old 32-byte behavior but documents the parity loss. TweakedPublicKey also loses its transparent serde derive because it wraps XOnlyPublicKey. Tests and a control-block regression fixture are removed or updated accordingly.
Changed components
crypto/src/key.rs (XOnlyPublicKey, TweakedPublicKey, x_only_serde module)bitcoin/src/crypto/key.rs (re-export of x_only_serde)bitcoin/src/taproot/mod.rs (ControlBlock serde derive removal)bitcoin/tests/serde.rs (control block regression test removal)bitcoin/tests/sighash.rs (XOnlyPublicKey serde annotation update)Inspect captured patch +143 / −35
### bitcoin/src/crypto/key.rs
@@ -10,6 +10,8 @@ use crate::{script, P2wpkhScriptCode};
#[rustfmt::skip] // Keep public re-exports separate.
pub use secp256k1::{constants, Parity};
+#[cfg(feature = "serde")]
+pub use crypto::key::x_only_serde;
#[doc(no_inline)]
pub use crypto::key::{
FromSliceError, FromWifError, InvalidAddressVersionError, InvalidWifCompressionFlagError,
### bitcoin/src/taproot/mod.rs
@@ -987,7 +987,6 @@ impl<'tree> ScriptLeaf<'tree> {
/// Control block data structure used in Tapscript satisfaction.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ControlBlock<Branch = TaprootMerkleBranchBuf, Key = UntweakedPublicKey>
where
Branch: ?Sized,
### bitcoin/tests/data/serde/control_block_hex
@@ -1 +0,0 @@
-c1a9d6f66cd4b25004f526bfa873e56942f98e8e492bd79ed6532b966104817c2bda584e7d32612381cf88edc1c02e28a296e807c16ad22f591ee113946e48a71e0641e660d1e5392fb79d64838c2b84faf04b7f5f283c9d8bf83e39e177b64372a0cd22eeab7e093873e851e247714eff762d8a30be699ba4456cfe6491b282e193a071350ae099005a5950d74f73ba13077a57bc478007fb0e4d1099ce9cf3d4
### bitcoin/tests/serde.rs
@@ -23,7 +23,7 @@ use bincode::serialize;
use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
use bitcoin::locktime::{absolute, relative};
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
-use bitcoin::taproot::{self, ControlBlock, LeafVersion, TapTree, TaprootBuilder};
+use bitcoin::taproot::{self, LeafVersion, TapTree, TaprootBuilder};
use bitcoin::witness::Witness;
use bitcoin::{
ecdsa, hex, Address, AddressParams, LegacyPublicKey, OutPoint, ScriptSigBuf, TapScriptBuf,
@@ -150,16 +150,6 @@ fn serde_regression_ecdsa_sig() {
assert_eq!(got, want)
}
-#[test]
-fn serde_regression_control_block() {
- let s = include_str!("data/serde/control_block_hex");
- let block = ControlBlock::decode(&hex::decode_to_vec(s.trim()).unwrap()).unwrap();
-
- let got = serialize(&block).unwrap();
- let want = include_bytes!("data/serde/control_block_bincode") as &[_];
- assert_eq!(got, want)
-}
-
#[test]
fn serde_regression_child_number() {
let num = ChildNumber::from_raw(0xDEADBEEF);
### bitcoin/tests/sighash.rs
@@ -127,6 +127,7 @@ fn bip_341_sighash_tests() {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct KpsInputSpendingIntermediary {
+ #[serde(with = "bitcoin::key::x_only_serde::without_parity")]
internal_pubkey: XOnlyPublicKey,
tweaked_privkey: SecretKey,
sig_msg: String,
### crypto/src/key.rs
@@ -57,6 +57,9 @@ mod x_only_public_key {
/// A Bitcoin Schnorr X-only public key used for BIP-0340 signatures.
///
/// This type also holds the parity of the full public key.
+ ///
+ /// This type does not implement `serde` traits, since the x-only encoding does not include
+ /// the parity. Use one of the modules in `key::x_only_serde` instead.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct XOnlyPublicKey {
inner: secp256k1::XOnlyPublicKey,
@@ -216,15 +219,10 @@ mod private_key {
}
mod tweaked_public_key {
- #[cfg(feature = "serde")]
- use serde::{Deserialize, Serialize};
-
use super::{TweakedKeypair, XOnlyPublicKey};
/// Tweaked BIP-0340 X-coord-only public key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
- #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
- #[cfg_attr(feature = "serde", serde(transparent))]
pub struct TweakedPublicKey(XOnlyPublicKey);
impl TweakedPublicKey {
@@ -1301,26 +1299,145 @@ impl<'de> serde::Deserialize<'de> for WifKey {
}
}
-// XOnlyPublicKey should serialize/deserialize identically to the inner type.
#[cfg(feature = "serde")]
-impl serde::Serialize for XOnlyPublicKey {
- #[inline]
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- <secp256k1::XOnlyPublicKey as serde::Serialize>::serialize(&self.to_inner(), serializer)
+pub mod x_only_serde {
+ //! Serde serialization and deserialization support for x-only public keys.
+ //!
+ //! An [`XOnlyPublicKey`] holds the parity of its full public key, but the standard 32-byte
+ //! x-only encoding cannot represent it. Since there is not a default way to serialize an x-only
+ //! public key that also round-trips, [`XOnlyPublicKey`] does not implement `Serialize` or
+ //! `Deserialize` and it's up to the user to decide whether the parity should be retained.
+ //!
+ //! The provided modules can be used as follows:
+ //!
+ //! ```
+ //! # #[cfg(feature = "hex")] {
+ //! use bitcoin_crypto::key::XOnlyPublicKey;
+ //! use serde::{Deserialize, Serialize};
+ //!
+ //! #[derive(Serialize, Deserialize)]
+ //! pub struct Foo {
+ //! #[serde(with = "bitcoin_crypto::key::x_only_serde::with_parity")]
+ //! pub key: XOnlyPublicKey,
+ //! #[serde(with = "bitcoin_crypto::key::x_only_serde::without_parity::opt")]
+ //! pub maybe_key: Option<XOnlyPublicKey>,
+ //! }
+ //! # }
+ //! ```
+ //!
+ //! [`XOnlyPublicKey`]: super::XOnlyPublicKey
+
+ #![allow(clippy::missing_errors_doc)] // Errors are on serde fn impls
+
+ #[cfg(feature = "hex")]
+ pub mod with_parity {
+ //! Serialize and deserialize [`XOnlyPublicKey`] including its parity.
+ //!
+ //! The key is encoded identically to a [`FullPublicKey`], so this format round-trips.
+ //!
+ //! Use with `#[serde(with = "bitcoin_crypto::key::x_only_serde::with_parity")]`.
+
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ use crate::key::{FullPublicKey, XOnlyPublicKey};
+
+ /// Serializes `key` as a [`FullPublicKey`] using its parity.
+ #[inline]
+ pub fn serialize<S: Serializer>(key: &XOnlyPublicKey, s: S) -> Result<S::Ok, S::Error> {
+ key.to_public_key().serialize(s)
+ }
+
+ /// Deserializes a [`FullPublicKey`] into an [`XOnlyPublicKey`] retaining its parity.
+ #[inline]
+ pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<XOnlyPublicKey, D::Error> {
+ FullPublicKey::deserialize(d).map(XOnlyPublicKey::from)
+ }
+
+ pub mod opt {
+ //! Serialize and deserialize [`Option<XOnlyPublicKey>`] including its parity.
+ //!
+ //! Use with `#[serde(with = "bitcoin_crypto::key::x_only_serde::with_parity::opt")]`.
+
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ use crate::key::{FullPublicKey, XOnlyPublicKey};
+
+ /// Serializes `key` as an optional [`FullPublicKey`] using its parity.
+ #[inline]
+ #[allow(clippy::ref_option)] // API forced by serde.
+ pub fn serialize<S: Serializer>(
+ key: &Option<XOnlyPublicKey>,
+ s: S,
+ ) -> Result<S::Ok, S::Error> {
+ key.map(XOnlyPublicKey::to_public_key).serialize(s)
+ }
+
+ /// Deserializes an optional [`FullPublicKey`] into an [`XOnlyPublicKey`] retaining its
+ /// parity.
+ #[inline]
+ pub fn deserialize<'d, D: Deserializer<'d>>(
+ d: D,
+ ) -> Result<Option<XOnlyPublicKey>, D::Error> {
+ Option::<FullPublicKey>::deserialize(d).map(|key| key.map(XOnlyPublicKey::from))
+ }
+ }
}
-}
-#[cfg(feature = "serde")]
-impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
- #[inline]
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- Ok(Self::from_secp(secp256k1::XOnlyPublicKey::deserialize(deserializer)?, Parity::Even))
+ pub mod without_parity {
+ //! Serialize and deserialize [`XOnlyPublicKey`] without its parity.
+ //!
+ //! The key is encoded identically to a [`secp256k1::XOnlyPublicKey`]. This format does not
+ //! round-trip for keys with odd parity; deserialized keys always have even parity.
+ //!
+ //! Use with `#[serde(with = "bitcoin_crypto::key::x_only_serde::without_parity")]`.
+
+ use secp256k1::Parity;
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ use crate::key::XOnlyPublicKey;
+
+ /// Serializes the x-coordinate of `key`, discarding its parity.
+ #[inline]
+ pub fn serialize<S: Serializer>(key: &XOnlyPublicKey, s: S) -> Result<S::Ok, S::Error> {
+ <secp256k1::XOnlyPublicKey as Serialize>::serialize(&key.to_inner(), s)
+ }
+
+ /// Deserializes an x-coordinate into an [`XOnlyPublicKey`] with even parity.
+ #[inline]
+ pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<XOnlyPublicKey, D::Error> {
+ secp256k1::XOnlyPublicKey::deserialize(d)
+ .map(|key| XOnlyPublicKey::from_secp(key, Parity::Even))
+ }
+
+ pub mod opt {
+ //! Serialize and deserialize [`Option<XOnlyPublicKey>`] without its parity.
+ //!
+ //! Use with `#[serde(with = "bitcoin_crypto::key::x_only_serde::without_parity::opt")]`.
+
+ use secp256k1::Parity;
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ use crate::key::XOnlyPublicKey;
+
+ /// Serializes the x-coordinate of an optional `key`, discarding its parity.
+ #[inline]
+ #[allow(clippy::ref_option)] // API forced by serde.
+ pub fn serialize<S: Serializer>(
+ key: &Option<XOnlyPublicKey>,
+ s: S,
+ ) -> Result<S::Ok, S::Error> {
+ key.map(XOnlyPublicKey::to_inner).serialize(s)
+ }
+
+ /// Deserializes an optional x-coordinate into an [`XOnlyPublicKey`] with even parity.
+ #[inline]
+ pub fn deserialize<'d, D: Deserializer<'d>>(
+ d: D,
+ ) -> Result<Option<XOnlyPublicKey>, D::Error> {
+ Option::<secp256k1::XOnlyPublicKey>::deserialize(d)
+ .map(|key| key.map(|key| XOnlyPublicKey::from_secp(key, Parity::Even)))
+ }
+ }
}
}
Why this scored 37/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.