Skip to content

Commit

Permalink
fix: rounding issues: bitcoin/bitcoin#22949
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoshi Jäger committed Apr 6, 2022
1 parent 5e3a8f8 commit 344e306
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 7 deletions.
3 changes: 2 additions & 1 deletion src/policy/feerate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <policy/feerate.h>

#include <tinyformat.h>
#include <cmath>

CFeeRate::CFeeRate(const CAmount& nFeePaid, uint32_t num_bytes)
{
Expand All @@ -23,7 +24,7 @@ CAmount CFeeRate::GetFee(uint32_t num_bytes) const
{
const int64_t nSize{num_bytes};

CAmount nFee = nSatoshisPerK * nSize / 1000;
CAmount nFee{static_cast<CAmount>(std::ceil(nSatoshisPerK * nSize / 1000.0))};

if (nFee == 0 && nSize != 0) {
if (nSatoshisPerK > 0) nFee = CAmount(1);
Expand Down
1 change: 1 addition & 0 deletions src/policy/feerate.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class CFeeRate
CFeeRate(const CAmount& nFeePaid, uint32_t num_bytes);
/**
* Return the fee in satoshis for the given size in bytes.
* If the calculated fee would have fractional satoshis, then the returned fee will always be rounded up to the nearest satoshi.
*/
CAmount GetFee(uint32_t num_bytes) const;
/**
Expand Down
8 changes: 4 additions & 4 deletions src/test/amount_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ BOOST_AUTO_TEST_CASE(GetFeeTest)
// Truncates the result, if not integer
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(1)); // Special case: returns 1 instead of 0
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(14));
BOOST_CHECK_EQUAL(feeRate.GetFee(122), CAmount(15));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(122));
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(2));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(15));
BOOST_CHECK_EQUAL(feeRate.GetFee(122), CAmount(16));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(123));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(123));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(1107));

Expand Down
4 changes: 2 additions & 2 deletions src/test/transaction_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -808,12 +808,12 @@ BOOST_AUTO_TEST_CASE(test_IsStandard)
// nDustThreshold = 182 * 3702 / 1000
dustRelayFee = CFeeRate(3702);
// dust:
t.vout[0].nValue = 673 - 1;
t.vout[0].nValue = 674 - 1;
reason.clear();
BOOST_CHECK(!IsStandardTx(CTransaction(t), reason));
BOOST_CHECK_EQUAL(reason, "dust");
// not dust:
t.vout[0].nValue = 673;
t.vout[0].nValue = 674;
BOOST_CHECK(IsStandardTx(CTransaction(t), reason));
dustRelayFee = CFeeRate(DUST_RELAY_TX_FEE);

Expand Down

0 comments on commit 344e306

Please sign in to comment.