HomePhabricator

Check for overflow when calculating sum of outputs

Description

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

Details

Provenance
Elichai Turkel <elichai.turkel@gmail.com>Authored on Mar 31 2021, 07:53
PiRKCommitted on Mar 31 2021, 07:54
PiRKPushed on Mar 31 2021, 07:54
Reviewer
Restricted Project
Differential Revision
D8899: Check for overflow when calculating sum of outputs
Parents
rABC2d08db5fe0ac: [avalanche] Add an RPC to build a delegation
Branches
Unknown
Tags
Unknown