primitives: implement lexicographic Header Ord
What changed, and why it matters
This commit changes how Bitcoin block headers are sorted in the rust-bitcoin library. Previously, Rust's automatic ordering compared fields one by one in memory. Now, ordering is explicitly defined to match the byte-for-byte order of the header when serialized to the Bitcoin network format. This is a correctness/consistency improvement, not a security fix. There is no indication it addresses a vulnerability or was triggered by a security report.
No security action required. Treat as a normal code-quality/consistency change. Reviewers may want to confirm the lexicographic ordering matches intended downstream use (e.g., BIP-related ordering assumptions).
Security signals we found
No security-relevant signals present in commit message or diff
Change is a semantic correctness/consistency improvement to ordering
No mention of vulnerability, CVE, bug bounty, researcher, or security advisory
Evidence from the diff
The commit removes the derived PartialOrd/Ord impls for the Header struct and replaces them with manual implementations. The new ordering compares a tuple of each field’s little-endian/consensus byte representation, which is equivalent to lexicographic comparison of the consensus serialization. A test verifies that Header ordering matches encoding::encode_to_vec ordering. The change affects only ordering semantics and has no observable security-relevant behavior beyond making Ord deterministic relative to serialized bytes.
Changed components
rust-bitcoin primitives crateprimitives/src/block.rsHeader struct Ord/PartialOrd implementationsInspect captured patch +45 / −1
### 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;
@@ -674,7 +675,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,
@@ -724,6 +725,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>;
@@ -1562,6 +1586,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();Why this scored 18/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.