diff --git a/src/coins.cpp b/src/coins.cpp index 24a102b0bc1..b545ec560b0 100644 --- a/src/coins.cpp +++ b/src/coins.cpp @@ -111,9 +111,12 @@ void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possi } void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) { - cachedCoinsUsage += coin.DynamicMemoryUsage(); + const auto mem_usage{coin.DynamicMemoryUsage()}; auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint), std::move(coin)); - if (inserted) CCoinsCacheEntry::SetDirty(*it, m_sentinel); + if (inserted) { + CCoinsCacheEntry::SetDirty(*it, m_sentinel); + cachedCoinsUsage += mem_usage; + } } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) { diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp index 6ce0c7996f8..d66c62248bb 100644 --- a/src/test/coins_tests.cpp +++ b/src/test/coins_tests.cpp @@ -194,8 +194,11 @@ void SimulationTest(CCoinsView* base, bool fake_best_block) (coin.IsSpent() ? added_an_entry : updated_an_entry) = true; coin = newcoin; } - bool is_overwrite = !coin.IsSpent() || m_rng.rand32() & 1; - stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), is_overwrite); + if (COutPoint op(txid, 0); !stack.back()->map().contains(op) && !coin.IsSpent() && m_rng.randbool()) { + stack.back()->EmplaceCoinInternalDANGER(std::move(op), std::move(newcoin)); + } else { + stack.back()->AddCoin(std::move(op), std::move(newcoin), /*possible_overwrite=*/!coin.IsSpent() || m_rng.randbool()); + } } else { // Spend the coin. removed_an_entry = true;