Add to_target conversion to CompactTarget
What changed, and why it matters
This commit adds a new convenience method, to_target(), to the CompactTarget type in the rust-bitcoin library. It simply calls the existing Target::from_compact() conversion under the hood and does not change any behavior, security logic, or calculations. It is a routine API ergonomics improvement, not a security fix.
No security action needed. Treat as a normal API addition.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch introduces CompactTarget::to_target(self) -> Target, which delegates to Target::from_compact(self). This follows the Rust API guideline C-CONV-SPECIFIC (prefer to/as/into over from for conversion methods). Existing unit tests are renamed and updated to call the new method, confirming identical results. No cryptographic, consensus, or arithmetic code is modified.
Changed components
units/src/pow.rs: CompactTarget typeInspect captured patch +9 / −4
diff --git a/units/src/pow.rs b/units/src/pow.rs
index f6073328..07d60c36 100644
--- a/units/src/pow.rs
+++ b/units/src/pow.rs
@@ -257,6 +257,11 @@ impl CompactTarget {
#[inline]
pub const fn to_consensus(self) -> u32 { self.0 }
+ /// Computes the [`Target`] value from this compact representation.
+ ///
+ /// ref: <https://developer.bitcoin.org/reference/block_chain.html#target-nbits>
+ pub fn to_target(self) -> Target { Target::from_compact(self) }
+
/// Constructs a new `CompactTarget` from a prefixed hex string.
///
/// # Errors
@@ -1322,7 +1327,7 @@ mod tests {
fn work_overflowing_subtraction_panics() { let _ = Work(U256::ZERO) - Work(U256::ONE); }
#[test]
- fn target_from_compact() {
+ fn compact_to_target() {
// (nBits, target)
let tests = [
(0x0100_3456_u32, 0x00_u64), // High bit set.
@@ -1339,20 +1344,20 @@ mod tests {
for (n_bits, target) in tests {
let want = Target(U256::from(target));
- let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
+ let got = CompactTarget::from_consensus(n_bits).to_target();
assert_eq!(got, want);
}
}
#[test]
- fn target_from_compact_overflow_boundaries() {
+ fn compact_to_target_overflow_boundaries() {
let tests = [
(0x2100_FFFF_u32, Target(U256::from(0xFFFF_u32) << 240)),
(0x2200_00FF_u32, Target(U256::from(0xFF_u32) << 248)),
];
for (n_bits, want) in tests {
- let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
+ let got = CompactTarget::from_consensus(n_bits).to_target();
assert_eq!(got, want);
}
}
Why this scored 15/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.