From 47e4bff0ee8e17bddbc96ad4e907439f5ea9feaa Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 5 Jun 2024 08:39:47 +1000 Subject: [PATCH 1/2] pow: Fix off-by-one error Length check has an off-by-one error in it, we want the check it include hex strings of length 32 (eg, 128 bytes). --- bitcoin/src/pow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index 1642bef46..01e895a15 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -497,7 +497,7 @@ impl U256 { // Caller to ensure `s` does not contain a prefix. fn from_hex_internal(s: &str) -> Result { - let (high, low) = if s.len() < 32 { + let (high, low) = if s.len() <= 32 { let low = parse::hex_u128_unchecked(s)?; (0, low) } else { From 3298c0c4b5e9f200f200609b0c1f7051a5eec246 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 5 Jun 2024 08:41:02 +1000 Subject: [PATCH 2/2] pow: Unit test from_hex_internal Add a unit test that fails if put before the "pow: Fix off-by-one error" patch. Tests that we can correctly parse a 32 character long hex string into a `U256`. --- bitcoin/src/pow.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index 01e895a15..eab1f9e3e 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -1652,6 +1652,14 @@ mod tests { assert_eq!(got, val); } + #[test] + fn u256_from_hex_32_characters_long() { + let hex = "a69b455cd41bb662a69b4555deadbeef"; + let want = U256(0x00, 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF); + let got = U256::from_unprefixed_hex(hex).expect("failed to parse hex"); + assert_eq!(got, want); + } + #[cfg(feature = "serde")] #[test] fn u256_serde() {