Merge rust-bitcoin/rust-bitcoin#6989: units: drop PartialOrd and Ord from CompactTarget
What changed, and why it matters
This change removes automatic numeric ordering from a Bitcoin type called CompactTarget because its underlying u32 value does not reliably reflect which mining target is actually harder. It also replaces the derived ordering of block headers with a clear byte-by-byte (lexicographic) ordering based on how headers are serialized. The patch is a correctness and API-safety improvement rather than a fix for an active exploit, but it prevents future bugs where code might accidentally sort or compare CompactTarget values as if the raw number meant 'harder' or 'easier'.
Review downstream code that sorts collections keyed by CompactTarget or block::Header. Update any code relying on the old derived ordering to explicitly convert CompactTarget to Target before comparing, or use the new lexicographic Header ordering if appropriate. No urgent patch is required, but treat this as a breaking API correctness change.
Security signals we found
Removal of semantically incorrect derived ordering on CompactTarget
Explicit lexicographic ordering for block::Header based on consensus serialization
Documentation update warning that CompactTarget equality is on the u32 and ordering requires conversion
Test added to enforce that Header ordering matches consensus serialization
API test updated to reflect CompactTarget no longer implements Ord/PartialOrd
Evidence from the diff
CompactTarget previously derived PartialOrd/Ord on its wrapped u32, which is semantically wrong: conversion to/from Target is lossy in both directions, so a larger u32 does not necessarily mean a harder/easier proof-of-work target. The commit drops those derives and updates docs to state equality remains on the consensus u32 while ordering requires explicit conversion to Target. block::Header and p2p HeaderAndShortIds also lose derived Ord/PartialOrd because they contain CompactTarget; Header instead gets an explicit lexicographic Ord over the consensus-serialized fields. A test verifies Header ordering matches encoding::encode_to_vec output. The API test struct no longer lists CompactTarget under common ordered traits.
Changed components
units::pow::CompactTargetprimitives::block::Headerp2p::HeaderAndShortIds (via derive removal inferred from PR description, not shown in diff)units/tests/api.rsInspect captured patch +52 / −10
### primitives/src/block.rs
@@ -67,6 +67,7 @@
#[cfg(feature = "alloc")]
use core::borrow::Borrow;
+use core::cmp::Ordering;
use core::fmt;
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
@@ -695,7 +696,7 @@ fn witness_commitment_from_coinbase(coinbase: &Transaction) -> Option<WitnessCom
/// # Bitcoin Core References
///
/// * [CBlockHeader definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/block.h#L20)
-#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
+#[derive(Copy, PartialEq, Eq, Clone, Hash)]
pub struct Header {
/// Block version, now repurposed for soft fork signalling.
pub version: Version,
@@ -745,6 +746,29 @@ impl Header {
}
}
+impl Ord for Header {
+ /// Orders headers lexicographically by their consensus serialization.
+ #[inline]
+ fn cmp(&self, other: &Self) -> Ordering {
+ let key = |h: &Self| {
+ (
+ h.version.to_consensus().to_le_bytes(),
+ h.prev_blockhash.to_byte_array(),
+ h.merkle_root.to_byte_array(),
+ h.time.to_u32().to_le_bytes(),
+ h.bits.to_consensus_u32().to_le_bytes(),
+ h.nonce.to_le_bytes(),
+ )
+ };
+ key(self).cmp(&key(other))
+ }
+}
+
+impl PartialOrd for Header {
+ #[inline]
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
+}
+
#[cfg(feature = "hex")]
impl core::str::FromStr for Header {
type Err = encoding::FromHexError<HeaderDecoderError>;
@@ -1605,6 +1629,26 @@ mod tests {
assert_eq!(block.block_hash(), header.block_hash());
}
+ #[test]
+ #[cfg(feature = "alloc")]
+ fn header_order_matches_serialization() {
+ let high_bits = Header {
+ version: Version::ONE,
+ prev_blockhash: BlockHash::from_byte_array([0; 32]),
+ merkle_root: TxMerkleNode::from_byte_array([0; 32]),
+ time: BlockTime::from_u32(0),
+ bits: CompactTarget::from_consensus(0x0100_0000),
+ nonce: 0,
+ };
+ let low_bits = Header { bits: CompactTarget::from_consensus(0x0000_0001), ..high_bits };
+
+ assert_eq!(
+ high_bits.cmp(&low_bits),
+ encoding::encode_to_vec(&high_bits).cmp(&encoding::encode_to_vec(&low_bits))
+ );
+ assert!(high_bits < low_bits);
+ }
+
#[test]
fn block_hash_from_header() {
let header = dummy_header();
### units/src/pow.rs
@@ -277,13 +277,11 @@ impl_fmt_traits_for_u32_wrapper!(Target);
/// OpenSSL's bignum (BN) type has an encoding, which is even called "compact" as in Bitcoin, which
/// is exactly this format.
///
-/// # Note on order/equality
+/// # Note on equality
///
-/// Usage of the ordering and equality traits for this type may be surprising. Converting between
-/// [`CompactTarget`] and [`Target`] is lossy *in both directions* (there are multiple
-/// [`CompactTarget`] values that map to the same [`Target`] value). Ordering and equality for this
-/// type are defined in terms of the underlying `u32`.
-#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+/// 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);
@@ -882,13 +880,13 @@ mod tests {
}
#[test]
- fn compact_target_ordering() {
+ fn compact_target_equality() {
let lower = CompactTarget::from_consensus(0x1d00_fffe);
let lower_copy = CompactTarget::from_consensus(0x1d00_fffe);
let higher = CompactTarget::from_consensus(0x1d00_ffff);
- assert!(lower < higher);
assert!(lower == lower_copy);
+ assert!(lower != higher);
}
#[test]
### units/tests/api.rs
@@ -113,7 +113,7 @@ struct CommonTraits {
j: locktime::absolute::MedianTimePast,
k: locktime::relative::NumberOf512Seconds,
l: locktime::relative::NumberOfBlocks,
- m: pow::CompactTarget,
+ // m: pow::CompactTarget, // does not include Ord or PartialOrd
n: time::BlockTime,
o: weight::Weight,
}Why this scored 28/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.