Skip to content

Commit fa996c5

Browse files
author
MarcoFalke
committed
refactor: Avoid integer overflow in ApplyStats when activating snapshot
1 parent fac0188 commit fa996c5

File tree

4 files changed

+9
-4
lines changed

4 files changed

+9
-4
lines changed

src/index/coinstatsindex.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ bool CoinStatsIndex::LookUpStats(const CBlockIndex* block_index, CCoinsStats& co
321321
coins_stats.hashSerialized = entry.muhash;
322322
coins_stats.nTransactionOutputs = entry.transaction_output_count;
323323
coins_stats.nBogoSize = entry.bogo_size;
324-
coins_stats.nTotalAmount = entry.total_amount;
324+
coins_stats.total_amount = entry.total_amount;
325325
coins_stats.total_subsidy = entry.total_subsidy;
326326
coins_stats.total_unspendable_amount = entry.total_unspendable_amount;
327327
coins_stats.total_prevout_spent_amount = entry.total_prevout_spent_amount;

src/node/coinstats.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <index/coinstatsindex.h>
1212
#include <serialize.h>
1313
#include <uint256.h>
14+
#include <util/overflow.h>
1415
#include <util/system.h>
1516
#include <validation.h>
1617

@@ -82,7 +83,9 @@ static void ApplyStats(CCoinsStats& stats, const uint256& hash, const std::map<u
8283
stats.nTransactions++;
8384
for (auto it = outputs.begin(); it != outputs.end(); ++it) {
8485
stats.nTransactionOutputs++;
85-
stats.nTotalAmount += it->second.out.nValue;
86+
if (stats.total_amount.has_value()) {
87+
stats.total_amount = CheckedAdd(*stats.total_amount, it->second.out.nValue);
88+
}
8689
stats.nBogoSize += GetBogoSize(it->second.out.scriptPubKey);
8790
}
8891
}

src/node/coinstats.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ struct CCoinsStats {
3535
uint64_t nBogoSize{0};
3636
uint256 hashSerialized{};
3737
uint64_t nDiskSize{0};
38-
CAmount nTotalAmount{0};
38+
//! The total amount, or nullopt if an overflow occurred calculating it
39+
std::optional<CAmount> total_amount{0};
3940

4041
//! The number of coins contained.
4142
uint64_t coins_count{0};

src/rpc/blockchain.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1244,7 +1244,8 @@ static RPCHelpMan gettxoutsetinfo()
12441244
if (hash_type == CoinStatsHashType::MUHASH) {
12451245
ret.pushKV("muhash", stats.hashSerialized.GetHex());
12461246
}
1247-
ret.pushKV("total_amount", ValueFromAmount(stats.nTotalAmount));
1247+
CHECK_NONFATAL(stats.total_amount.has_value());
1248+
ret.pushKV("total_amount", ValueFromAmount(stats.total_amount.value()));
12481249
if (!stats.index_used) {
12491250
ret.pushKV("transactions", static_cast<int64_t>(stats.nTransactions));
12501251
ret.pushKV("disk_size", stats.nDiskSize);

0 commit comments

Comments
 (0)