diff options
author | practicalswift <practicalswift@users.noreply.github.com> | 2020-11-16 16:44:50 +0000 |
---|---|---|
committer | practicalswift <practicalswift@users.noreply.github.com> | 2021-03-02 16:05:28 +0000 |
commit | 1f05dbd06d896849d16b026bfc3315ee8b73a89f (patch) | |
tree | eda7a641dfa820f8c7f39cada9f04f28a547f663 /src/core_write.cpp | |
parent | 7cc75c9ba38e516067e5a4ab84311c62ddddced7 (diff) |
util: Avoid invalid integer negation in ValueFromAmount: make ValueFromAmount(const CAmount& n) well-defined also when n is std::numeric_limits<CAmount>::min()
Diffstat (limited to 'src/core_write.cpp')
-rw-r--r-- | src/core_write.cpp | 17 |
1 files changed, 10 insertions, 7 deletions
diff --git a/src/core_write.cpp b/src/core_write.cpp index a3902863d6..d3034ae25d 100644 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -14,17 +14,20 @@ #include <undo.h> #include <univalue.h> #include <util/check.h> -#include <util/system.h> #include <util/strencodings.h> +#include <util/system.h> -UniValue ValueFromAmount(const CAmount& amount) +UniValue ValueFromAmount(const CAmount amount) { - bool sign = amount < 0; - int64_t n_abs = (sign ? -amount : amount); - int64_t quotient = n_abs / COIN; - int64_t remainder = n_abs % COIN; + static_assert(COIN > 1); + int64_t quotient = amount / COIN; + int64_t remainder = amount % COIN; + if (amount < 0) { + quotient = -quotient; + remainder = -remainder; + } return UniValue(UniValue::VNUM, - strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); + strprintf("%s%d.%08d", amount < 0 ? "-" : "", quotient, remainder)); } std::string FormatScript(const CScript& script) |