Skip to content

Commit 055254e

Browse files
committed
Merge bitcoin/bitcoin#32300: feefrac: avoid integer overflow in temporary
5cb1241 feefrac: avoid integer overflow in temporary (Pieter Wuille) Pull request description: In `FeeFrac::Div(__int128 n, int32_t d, bool round_down)` in src/util/feefrac.h, the following line computes the result: ```c++ return quot + (mod > 0) - (mod && round_down); ``` The function can only be called under conditions where the result is in range, and thus doesn't involve any integer overflow. However, the intermediary result computed by just `quot + (mod > 0)` may still overflow if it's going to be corrected by the `- (mod && round_down)` that follows. Fix this by balancing the two correction steps with each other first: ```c++ return quot + ((mod > 0) - (mod && round_down)); ``` Fixes #32294. ACKs for top commit: l0rinc: Tested ACK 5cb1241 maflcko: lgtm ACK 5cb1241 achow101: ACK 5cb1241 Tree-SHA512: 9daaccdf9acd7652d53b52cad2dc12872558265e863acdde2d6015f885cb87c0505f9bd5be5499fc0a0eded29bec719643f6af1fbc3604518143985094226c95
2 parents 33d40a6 + 5cb1241 commit 055254e

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

src/test/feefrac_tests.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ BOOST_AUTO_TEST_CASE(feefrac_operators)
148148
FeeFrac max_fee2{1, 1};
149149
BOOST_CHECK(max_fee >= max_fee2);
150150

151+
// Test for integer overflow issue (https://github.com/bitcoin/bitcoin/issues/32294)
152+
BOOST_CHECK_EQUAL((FeeFrac{0x7ffffffdfffffffb, 0x7ffffffd}.EvaluateFeeDown(0x7fffffff)), 0x7fffffffffffffff);
151153
}
152154

153155
BOOST_AUTO_TEST_SUITE_END()

src/util/feefrac.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ struct FeeFrac
9696
int64_t quot = n / d;
9797
int32_t mod = n % d;
9898
// Correct result if the / operator above rounded in the wrong direction.
99-
return quot + (mod > 0) - (mod && round_down);
99+
return quot + ((mod > 0) - (mod && round_down));
100100
}
101101
#else
102102
static constexpr auto Mul = MulFallback;

0 commit comments

Comments
 (0)