Check for overflow when calculating sum of outputs
Summary:
Address a possible undefined behavior when summing outputs for a transaction, when the first outputs are valid but a following output causes an overflow.
The exact order of the if, is important, we first do !MoneyRange(tx_out.nValue) to make sure the amount is non-negative. and then std::numeric_limits<CAmount>::max() - tx_out.nValue < nValueOut checks that the addition cannot overflow (if we won't check that the amount is positive this check can also overflow! (by doing something like max - -max))
and only then we make sure that the sum is also valid !MoneyRange(nValueOut + tx_out.nValue)
if any of these conditions fail we throw.
This is a backport of Core PR18383
Test Plan:
mkdir build_ubsan cd build_ubsan cmake -GNinja .. \ -DCMAKE_BUILD_TYPE=Debug \ -DENABLE_SANITIZERS=undefined ninja check
Reviewers: #bitcoin_abc, deadalnix
Reviewed By: #bitcoin_abc, deadalnix
Subscribers: deadalnix
Differential Revision: https://reviews.bitcoinabc.org/D8899