Merge rust-bitcoin/rust-bitcoin#7023: Evaluate macro arguments once in load_int_le and impl_hex
What changed, and why it matters
This merge commit fixes two internal Rust macros that accidentally evaluated their arguments multiple times instead of once. In one case, a buffer and index used in a hashing function were evaluated 2-3 times per call; in the other, a hex-character lookup table was rebuilt 64 times every time a large number was formatted as hex. The patch binds each argument to a single variable using a match expression, and adds tests that prove the arguments are now evaluated exactly once. These are correctness/performance hygiene fixes rather than an obvious remote exploit, but repeated evaluation of user-supplied expressions in macros can hide subtle bugs or side effects.
Treat as a low-severity correctness fix. Review downstream callers of `load_int_le!` and `impl_hex!` to confirm no observable behavior change from removing duplicated side effects. Include the new unit tests in CI. No urgent security response is indicated by the supplied materials, but the pattern is worth auditing elsewhere in the workspace.
Security signals we found
Macro argument multiple-evaluation bug (code-quality / correctness)
Potential unexpected side effects from duplicated expression evaluation
Unsafe code path (`load_int_le!`) touched by macro change
Performance/DoS relevance: 64x redundant lookup construction per U256 format
No explicit security advisory or CVE referenced in commit materials
Evidence from the diff
The commit merges PR #7023, which audits workspace macros for repeated evaluation of runtime expr, tt, and block captures. It changes load_int_le! in hashes/src/siphash24/mod.rs and impl_hex! in internals/src/u256.rs to bind their repeated macro arguments once via match ($buf, $i) { (buf, i) => ... } and match $lookup { lookup => ... }. Previously load_int_le! expanded $buf twice and $i three times; impl_hex! expanded $lookup twice per byte (64 times for a U256). The included unit tests pass counting expressions/blocks and assert single evaluation. The fixes remove duplicated side effects and redundant work, improving deterministic behavior and performance of SipHash-24 and U256 formatting code paths.
Changed components
hashes/src/siphash24/mod.rs: load_int_le! macrointernals/src/u256.rs: impl_hex! macroSipHash-24 implementationU256 Display/LowerHex/UpperHex formatting implementationsInspect captured patch +73 / −11
### hashes/src/siphash24/mod.rs
@@ -44,12 +44,16 @@ macro_rules! compress {
/// Unsafe because: unchecked indexing at `i..i+size_of(int_ty)`.
macro_rules! load_int_le {
($buf:expr, $i:expr, $int_ty:ident) => {{
- debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
- $int_ty::from_le_bytes(
- $buf.get_unchecked($i..($i + mem::size_of::<$int_ty>()))
- .try_into()
- .expect("len is correctly computed using size_of"),
- )
+ match ($buf, $i) {
+ (buf, i) => {
+ debug_assert!(i + mem::size_of::<$int_ty>() <= buf.len());
+ $int_ty::from_le_bytes(
+ buf.get_unchecked(i..(i + mem::size_of::<$int_ty>()))
+ .try_into()
+ .expect("len is correctly computed using size_of"),
+ )
+ }
+ }
}};
}
@@ -243,6 +247,29 @@ unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
mod tests {
use super::*;
+ #[test]
+ fn load_int_le_evaluates_arguments_once() {
+ let bytes = [1u8, 2, 3, 4, 5, 6, 7, 8];
+ let mut buf_hits = 0;
+ let mut index_hits = 0;
+ let loaded = unsafe {
+ load_int_le!(
+ {
+ buf_hits += 1;
+ &bytes[..]
+ },
+ {
+ index_hits += 1;
+ 0
+ },
+ u64
+ )
+ };
+ assert_eq!(loaded, u64::from_le_bytes(bytes));
+ assert_eq!(buf_hits, 1);
+ assert_eq!(index_hits, 1);
+ }
+
#[test]
fn siphash_2_4() {
#[rustfmt::skip]
### internals/src/u256.rs
@@ -532,11 +532,14 @@ macro_rules! impl_hex {
}
#[allow(clippy::indexing_slicing)]
- for byte in self.to_be_bytes() {
- let upper_idx = ((byte & 0xf0) >> 4) as usize;
- let lower_idx = (byte & 0xf) as usize;
- f.write_char($lookup[upper_idx])?;
- f.write_char($lookup[lower_idx])?;
+ match $lookup {
+ lookup =>
+ for byte in self.to_be_bytes() {
+ let upper_idx = ((byte & 0xf0) >> 4) as usize;
+ let lower_idx = (byte & 0xf) as usize;
+ f.write_char(lookup[upper_idx])?;
+ f.write_char(lookup[lower_idx])?;
+ },
}
Ok(())
}
@@ -883,6 +886,38 @@ mod tests {
);
}
+ #[test]
+ fn impl_hex_evaluates_lookup_once_per_format() {
+ use core::fmt::Write as _;
+ use core::sync::atomic::{AtomicUsize, Ordering};
+
+ static LOOKUP_HITS: AtomicUsize = AtomicUsize::new(0);
+
+ trait CountingHex {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
+ }
+
+ impl_hex!(CountingHex, {
+ LOOKUP_HITS.fetch_add(1, Ordering::Relaxed);
+ ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
+ });
+
+ struct Hex(U256);
+
+ impl fmt::Display for Hex {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { CountingHex::fmt(&self.0, f) }
+ }
+
+ struct Sink;
+
+ impl fmt::Write for Sink {
+ fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) }
+ }
+
+ write!(Sink, "{}", Hex(U256::MAX)).unwrap();
+ assert_eq!(LOOKUP_HITS.load(Ordering::Relaxed), 1);
+ }
+
#[test]
#[cfg(feature = "alloc")]
fn u256_display() {Why this scored 32/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.