From 66f00e2074e6dfb665abb5d0f4a61d582942f264 Mon Sep 17 00:00:00 2001 From: Greg Sanders Date: Wed, 10 Jan 2024 12:58:12 -0500 Subject: [PATCH] Attempting to avoid all overflow in diagram checks --- src/policy/rbf.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/policy/rbf.cpp b/src/policy/rbf.cpp index 4625c02247e930..f19483d2d0c776 100644 --- a/src/policy/rbf.cpp +++ b/src/policy/rbf.cpp @@ -55,15 +55,21 @@ inline std::pair Mul128(int64_t a, int64_t b) #endif } -inline std::pair Add128(const std::pair& a, +inline std::pair Add128(const std::pair& a, const std::pair& b) { - // Add the low parts - uint64_t low = a.second + b.second; + uint32_t low_a_low = (uint32_t)a.second; + uint32_t low_a_high = a.second >> 32; + uint32_t low_b_low = (uint32_t)b.second; + uint32_t low_b_high = b.second >> 32; - // Calculate carry from the low part (if the addition of low parts overflows, it will carry to the high part) - int64_t carry = (low < a.second) ? 1 : 0; + uint64_t low_sum_low = static_cast(low_a_low) + low_b_low; + uint64_t carry = low_sum_low >> 32; // carry for the next 32 bits + + uint64_t low_sum_high = static_cast(low_a_high) + low_b_high + carry; + carry = low_sum_high >> 32; // carry for the high part + + uint64_t low = (low_sum_high << 32) | (low_sum_low & 0xFFFFFFFF); - // Add the high parts and the carry int64_t high = a.first + b.first + carry; return {high, low};