LCOV - code coverage report
Current view: top level - src/test - coins_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 98.8 % 661 653
Test Date: 2026-08-21 06:28:42 Functions: 98.1 % 52 51
Branches: 54.1 % 2606 1409

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2014-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <addresstype.h>
       6                 :             : #include <clientversion.h>
       7                 :             : #include <coins.h>
       8                 :             : #include <streams.h>
       9                 :             : #include <test/util/coins.h>
      10                 :             : #include <test/util/common.h>
      11                 :             : #include <test/util/poolresourcetester.h>
      12                 :             : #include <test/util/random.h>
      13                 :             : #include <test/util/setup_common.h>
      14                 :             : #include <txdb.h>
      15                 :             : #include <uint256.h>
      16                 :             : #include <undo.h>
      17                 :             : #include <util/byte_units.h>
      18                 :             : #include <util/check.h>
      19                 :             : #include <util/strencodings.h>
      20                 :             : 
      21                 :             : #include <map>
      22                 :             : #include <string>
      23                 :             : #include <variant>
      24                 :             : #include <vector>
      25                 :             : 
      26                 :             : #include <boost/test/unit_test.hpp>
      27                 :             : 
      28                 :             : using namespace util::hex_literals;
      29                 :             : 
      30                 :             : int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out);
      31                 :             : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
      32                 :             : 
      33                 :             : namespace
      34                 :             : {
      35                 :             : 
      36                 :           4 : class CCoinsViewTest : public CoinsViewEmpty
      37                 :             : {
      38                 :             :     FastRandomContext& m_rng;
      39                 :             :     uint256 hashBestBlock_;
      40                 :             :     std::map<COutPoint, Coin> map_;
      41                 :             : 
      42                 :             : public:
      43                 :           4 :     explicit CCoinsViewTest(FastRandomContext& rng) : m_rng{rng} {}
      44                 :             : 
      45                 :     6034611 :     std::optional<Coin> GetCoin(const COutPoint& outpoint) const override
      46                 :             :     {
      47   [ +  +  +  + ]:     6034611 :         if (auto it{map_.find(outpoint)}; it != map_.end() && !it->second.IsSpent()) return it->second;
      48                 :     5899426 :         return std::nullopt;
      49                 :             :     }
      50                 :             : 
      51                 :           2 :     uint256 GetBestBlock() const override { return hashBestBlock_; }
      52                 :             : 
      53                 :         278 :     void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override
      54                 :             :     {
      55         [ +  + ]:       83682 :         for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)){
      56         [ +  - ]:       83404 :             if (it->second.IsDirty()) {
      57                 :             :                 // Same optimization used in CCoinsViewDB is to only write dirty entries.
      58                 :       83404 :                 map_[it->first] = it->second.coin;
      59   [ +  +  +  + ]:       83404 :                 if (it->second.coin.IsSpent() && m_rng.randrange(3) == 0) {
      60                 :             :                     // Randomly delete empty entries on write.
      61                 :       12511 :                     map_.erase(it->first);
      62                 :             :                 }
      63                 :             :             }
      64                 :             :         }
      65         [ +  + ]:         556 :         if (!block_hash.IsNull())
      66                 :           2 :             hashBestBlock_ = block_hash;
      67                 :         278 :     }
      68                 :             : };
      69                 :             : 
      70                 :           0 : class CCoinsViewCacheTest : public CCoinsViewCache
      71                 :             : {
      72                 :             : public:
      73   [ +  -  +  -  :         611 :     explicit CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}
             +  -  +  - ]
      74                 :             : 
      75                 :         374 :     void SelfTest(bool sanity_check = true) const
      76                 :             :     {
      77                 :             :         // Manually recompute the dynamic usage of the whole data, and compare it.
      78                 :         374 :         size_t ret = memusage::DynamicUsage(cacheCoins);
      79                 :         374 :         size_t count = 0;
      80   [ +  +  +  + ]:      490438 :         for (const auto& entry : cacheCoins) {
      81         [ +  + ]:      490064 :             ret += entry.second.coin.DynamicMemoryUsage();
      82                 :      490064 :             ++count;
      83                 :             :         }
      84         [ +  - ]:         374 :         BOOST_CHECK_EQUAL(GetCacheSize(), count);
      85         [ +  - ]:         374 :         BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
      86         [ +  + ]:         374 :         if (sanity_check) {
      87                 :         265 :             SanityCheck();
      88                 :             :         }
      89                 :         374 :     }
      90                 :             : 
      91         [ +  - ]:       47952 :     CCoinsMap& map() const { return cacheCoins; }
      92         [ +  - ]:         176 :     CoinsCachePair& sentinel() const { return m_sentinel; }
      93                 :         176 :     size_t& usage() const { return cachedCoinsUsage; }
      94                 :         176 :     size_t& dirty() const { return m_dirty_count; }
      95                 :             : };
      96                 :             : 
      97                 :             : } // namespace
      98                 :             : 
      99                 :             : static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;
     100                 :             : 
     101                 :           4 : struct CacheTest : BasicTestingSetup {
     102                 :             : // This is a large randomized insert/remove simulation test on a variable-size
     103                 :             : // stack of caches on top of CCoinsViewTest.
     104                 :             : //
     105                 :             : // It will randomly create/update/delete Coin entries to a tip of caches, with
     106                 :             : // txids picked from a limited list of random 256-bit hashes. Occasionally, a
     107                 :             : // new tip is added to the stack of caches, or the tip is flushed and removed.
     108                 :             : //
     109                 :             : // During the process, booleans are kept to make sure that the randomized
     110                 :             : // operation hits all branches.
     111                 :             : //
     112                 :             : // If fake_best_block is true, assign a random uint256 to mock the recording
     113                 :             : // of best block on flush. This is necessary when using CCoinsViewDB as the base,
     114                 :             : // otherwise we'll hit an assertion in BatchWrite.
     115                 :             : //
     116                 :           2 : void SimulationTest(CCoinsView* base, bool fake_best_block)
     117                 :             : {
     118                 :             :     // Various coverage trackers.
     119                 :           2 :     bool removed_all_caches = false;
     120                 :           2 :     bool reached_4_caches = false;
     121                 :           2 :     bool added_an_entry = false;
     122                 :           2 :     bool added_an_unspendable_entry = false;
     123                 :           2 :     bool removed_an_entry = false;
     124                 :           2 :     bool updated_an_entry = false;
     125                 :           2 :     bool found_an_entry = false;
     126                 :           2 :     bool missed_an_entry = false;
     127                 :           2 :     bool uncached_an_entry = false;
     128                 :           2 :     bool flushed_without_erase = false;
     129                 :             : 
     130                 :             :     // A simple map to track what we expect the cache stack to represent.
     131         [ +  - ]:           2 :     std::map<COutPoint, Coin> result;
     132                 :             : 
     133                 :             :     // The cache stack.
     134                 :           2 :     std::vector<std::unique_ptr<CCoinsViewCacheTest>> stack; // A stack of CCoinsViewCaches on top.
     135         [ +  - ]:           4 :     stack.push_back(std::make_unique<CCoinsViewCacheTest>(base)); // Start with one cache.
     136                 :             : 
     137                 :             :     // Use a limited set of random transaction ids, so we do test overwriting entries.
     138                 :           2 :     std::vector<Txid> txids;
     139         [ +  - ]:           2 :     txids.resize(NUM_SIMULATION_ITERATIONS / 8);
     140   [ -  +  +  + ]:       10002 :     for (unsigned int i = 0; i < txids.size(); i++) {
     141                 :       10000 :         txids[i] = Txid::FromUint256(m_rng.rand256());
     142                 :             :     }
     143                 :             : 
     144         [ +  + ]:       80002 :     for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
     145                 :             :         // Do a random modification.
     146                 :       80000 :         {
     147   [ -  +  +  - ]:       80000 :             auto txid = txids[m_rng.randrange(txids.size())]; // txid we're going to modify in this iteration.
     148         [ +  - ]:       80000 :             Coin& coin = result[COutPoint(txid, 0)];
     149                 :             : 
     150                 :             :             // Determine whether to test HaveCoin before or after Access* (or both). As these functions
     151                 :             :             // can influence each other's behaviour by pulling things into the cache, all combinations
     152                 :             :             // are tested.
     153                 :       80000 :             bool test_havecoin_before = m_rng.randbits(2) == 0;
     154                 :       80000 :             bool test_havecoin_after = m_rng.randbits(2) == 0;
     155                 :             : 
     156   [ +  +  +  - ]:       80000 :             bool result_havecoin = test_havecoin_before ? stack.back()->HaveCoin(COutPoint(txid, 0)) : false;
     157                 :             : 
     158                 :             :             // Infrequently, test usage of AccessByTxid instead of AccessCoin - the
     159                 :             :             // former just delegates to the latter and returns the first unspent in a txn.
     160         [ +  + ]:       80000 :             const Coin& entry = (m_rng.randrange(500) == 0) ?
     161   [ +  -  +  - ]:       80000 :                 AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
     162   [ +  -  +  - ]:       80000 :             BOOST_CHECK_EQUAL(coin, entry);
     163                 :             : 
     164         [ +  + ]:       80000 :             if (test_havecoin_before) {
     165   [ +  -  +  - ]:       40180 :                 BOOST_CHECK(result_havecoin == !entry.IsSpent());
     166                 :             :             }
     167                 :             : 
     168         [ +  + ]:       80000 :             if (test_havecoin_after) {
     169         [ +  - ]:       19896 :                 bool ret = stack.back()->HaveCoin(COutPoint(txid, 0));
     170   [ +  -  +  - ]:       39792 :                 BOOST_CHECK(ret == !entry.IsSpent());
     171                 :             :             }
     172                 :             : 
     173   [ +  +  +  + ]:       80000 :             if (m_rng.randrange(5) == 0 || coin.IsSpent()) {
     174                 :       47942 :                 Coin newcoin;
     175                 :       47942 :                 newcoin.out.nValue = RandMoney(m_rng);
     176                 :       47942 :                 newcoin.nHeight = 1;
     177                 :             : 
     178                 :             :                 // Infrequently test adding unspendable coins.
     179   [ +  +  +  + ]:       47942 :                 if (m_rng.randrange(16) == 0 && coin.IsSpent()) {
     180                 :        2504 :                     newcoin.out.scriptPubKey.assign(1 + m_rng.randbits(6), OP_RETURN);
     181   [ +  -  +  - ]:        5008 :                     BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
     182                 :        2504 :                     added_an_unspendable_entry = true;
     183                 :             :                 } else {
     184                 :             :                     // Random sizes so we can test memory usage accounting
     185                 :       45438 :                     newcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
     186         [ +  + ]:       45438 :                     (coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
     187                 :       45438 :                     coin = newcoin;
     188                 :             :                 }
     189   [ +  +  +  +  :       47942 :                 if (COutPoint op(txid, 0); !stack.back()->map().contains(op) && !newcoin.out.scriptPubKey.IsUnspendable() && m_rng.randbool()) {
                   +  + ]
     190         [ +  - ]:       18018 :                     stack.back()->EmplaceCoinInternalDANGER(op, std::move(newcoin));
     191                 :             :                 } else {
     192   [ +  +  +  +  :       31133 :                     stack.back()->AddCoin(op, std::move(newcoin), /*possible_overwrite=*/!coin.IsSpent() || m_rng.randbool());
                   +  - ]
     193                 :             :                 }
     194                 :       47942 :             } else {
     195                 :             :                 // Spend the coin.
     196                 :       32058 :                 removed_an_entry = true;
     197                 :       32058 :                 coin.Clear();
     198   [ +  -  +  -  :       64116 :                 BOOST_CHECK(stack.back()->SpendCoin(COutPoint(txid, 0)));
                   +  - ]
     199                 :             :             }
     200                 :             :         }
     201                 :             : 
     202                 :             :         // Once every 10 iterations, remove a random entry from the cache
     203         [ +  + ]:       80000 :         if (m_rng.randrange(10) == 0) {
     204         [ -  + ]:        7958 :             COutPoint out(txids[m_rng.rand32() % txids.size()], 0);
     205         [ -  + ]:        7958 :             int cacheid = m_rng.rand32() % stack.size();
     206         [ +  - ]:        7958 :             stack[cacheid]->Uncache(out);
     207         [ +  - ]:        7958 :             uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
     208                 :             :         }
     209                 :             : 
     210                 :             :         // Once every 1000 iterations and at the end, verify the full cache.
     211   [ +  +  +  + ]:       80000 :         if (m_rng.randrange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
     212         [ +  + ]:      389864 :             for (const auto& entry : result) {
     213         [ +  - ]:      389780 :                 bool have = stack.back()->HaveCoin(entry.first);
     214         [ +  - ]:      389780 :                 const Coin& coin = stack.back()->AccessCoin(entry.first);
     215   [ +  -  +  -  :      779560 :                 BOOST_CHECK(have == !coin.IsSpent());
                   +  - ]
     216   [ +  -  +  - ]:      389780 :                 BOOST_CHECK_EQUAL(coin, entry.second);
     217         [ +  + ]:      389780 :                 if (coin.IsSpent()) {
     218                 :             :                     missed_an_entry = true;
     219                 :             :                 } else {
     220   [ +  -  +  -  :      439476 :                     BOOST_CHECK(stack.back()->HaveCoinInCache(entry.first));
                   +  - ]
     221                 :      219738 :                     found_an_entry = true;
     222                 :             :                 }
     223                 :             :             }
     224         [ +  + ]:         276 :             for (const auto& test : stack) {
     225         [ +  - ]:         192 :                 test->SelfTest();
     226                 :             :             }
     227                 :             :         }
     228                 :             : 
     229         [ +  + ]:       80000 :         if (m_rng.randrange(100) == 0) {
     230                 :             :             // Every 100 iterations, flush an intermediate cache
     231   [ -  +  +  +  :         778 :             if (stack.size() > 1 && m_rng.randbool() == 0) {
                   +  + ]
     232         [ -  + ]:         255 :                 unsigned int flushIndex = m_rng.randrange(stack.size() - 1);
     233   [ +  +  +  - ]:         255 :                 if (fake_best_block) stack[flushIndex]->SetBestBlock(m_rng.rand256());
     234                 :         255 :                 bool should_erase = m_rng.randrange(4) < 3;
     235   [ +  +  +  -  :         255 :                 should_erase ? stack[flushIndex]->Flush() : stack[flushIndex]->Sync();
                   +  - ]
     236                 :         255 :                 flushed_without_erase |= !should_erase;
     237                 :             :             }
     238                 :             :         }
     239         [ +  + ]:       80000 :         if (m_rng.randrange(100) == 0) {
     240                 :             :             // Every 100 iterations, change the cache stack.
     241   [ -  +  +  -  :         786 :             if (stack.size() > 0 && m_rng.randbool() == 0) {
                   +  + ]
     242                 :             :                 //Remove the top cache
     243   [ +  +  +  - ]:         403 :                 if (fake_best_block) stack.back()->SetBestBlock(m_rng.rand256());
     244                 :         403 :                 bool should_erase = m_rng.randrange(4) < 3;
     245   [ +  +  +  -  :         403 :                 should_erase ? stack.back()->Flush() : stack.back()->Sync();
                   +  - ]
     246                 :         403 :                 flushed_without_erase |= !should_erase;
     247                 :         403 :                 stack.pop_back();
     248                 :             :             }
     249   [ -  +  +  +  :         786 :             if (stack.size() == 0 || (stack.size() < 4 && m_rng.randbool())) {
             +  +  +  + ]
     250                 :             :                 //Add a new cache
     251                 :         409 :                 CCoinsView* tip = base;
     252   [ -  +  +  + ]:         409 :                 if (stack.size() > 0) {
     253                 :         292 :                     tip = stack.back().get();
     254                 :             :                 } else {
     255                 :             :                     removed_all_caches = true;
     256                 :             :                 }
     257         [ +  - ]:         818 :                 stack.push_back(std::make_unique<CCoinsViewCacheTest>(tip));
     258   [ -  +  +  + ]:         409 :                 if (stack.size() == 4) {
     259                 :          97 :                     reached_4_caches = true;
     260                 :             :                 }
     261                 :             :             }
     262                 :             :         }
     263                 :             :     }
     264                 :             : 
     265                 :             :     // Verify coverage.
     266   [ +  -  +  -  :           4 :     BOOST_CHECK(removed_all_caches);
                   +  - ]
     267   [ +  -  +  -  :           4 :     BOOST_CHECK(reached_4_caches);
                   +  - ]
     268   [ +  -  +  -  :           4 :     BOOST_CHECK(added_an_entry);
                   +  - ]
     269   [ +  -  +  -  :           4 :     BOOST_CHECK(added_an_unspendable_entry);
                   +  - ]
     270   [ +  -  +  -  :           4 :     BOOST_CHECK(removed_an_entry);
                   +  - ]
     271   [ +  -  +  -  :           4 :     BOOST_CHECK(updated_an_entry);
                   +  - ]
     272   [ +  -  +  -  :           4 :     BOOST_CHECK(found_an_entry);
                   +  - ]
     273   [ +  -  +  -  :           4 :     BOOST_CHECK(missed_an_entry);
                   +  - ]
     274   [ +  -  +  -  :           4 :     BOOST_CHECK(uncached_an_entry);
                   +  - ]
     275   [ +  -  +  - ]:           4 :     BOOST_CHECK(flushed_without_erase);
     276                 :           2 : }
     277                 :             : }; // struct CacheTest
     278                 :             : 
     279                 :             : BOOST_FIXTURE_TEST_SUITE(coins_tests_base, BasicTestingSetup)
     280                 :             : 
     281                 :             : // Run the above simulation for multiple base types.
     282   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(coins_cache_base_simulation_test, CacheTest)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     283                 :             : {
     284         [ +  - ]:           1 :     CCoinsViewTest base{m_rng};
     285         [ +  - ]:           1 :     SimulationTest(&base, false);
     286                 :           1 : }
     287                 :             : 
     288                 :             : BOOST_AUTO_TEST_SUITE_END()
     289                 :             : 
     290                 :             : BOOST_FIXTURE_TEST_SUITE(coins_tests_dbbase, BasicTestingSetup)
     291                 :             : 
     292   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(coins_cache_dbbase_simulation_test, CacheTest)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     293                 :             : {
     294                 :           0 :     CCoinsViewDB db_base{{.path = "test", .cache_bytes = 8_MiB, .memory_only = true}, {}};
     295         [ +  - ]:           1 :     SimulationTest(&db_base, true);
     296         [ +  - ]:           2 : }
     297                 :             : 
     298                 :             : BOOST_AUTO_TEST_SUITE_END()
     299                 :             : 
     300                 :             : BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)
     301                 :             : 
     302                 :             : struct UpdateTest : BasicTestingSetup {
     303                 :             : // Store of all necessary tx and undo data for next test
     304                 :             : typedef std::map<COutPoint, std::tuple<CTransaction,CTxUndo,Coin>> UtxoData;
     305                 :             : UtxoData utxoData;
     306                 :             : 
     307                 :       40278 : UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
     308         [ -  + ]:       40278 :     assert(utxoSet.size());
     309                 :       40278 :     auto utxoSetIt = utxoSet.lower_bound(COutPoint(Txid::FromUint256(m_rng.rand256()), 0));
     310         [ +  + ]:       40278 :     if (utxoSetIt == utxoSet.end()) {
     311                 :         579 :         utxoSetIt = utxoSet.begin();
     312                 :             :     }
     313                 :       40278 :     auto utxoDataIt = utxoData.find(*utxoSetIt);
     314         [ -  + ]:       40278 :     assert(utxoDataIt != utxoData.end());
     315                 :       40278 :     return utxoDataIt;
     316                 :             : }
     317                 :             : }; // struct UpdateTest
     318                 :             : 
     319                 :             : 
     320                 :             : // This test is similar to the previous test
     321                 :             : // except the emphasis is on testing the functionality of UpdateCoins
     322                 :             : // random txs are created and UpdateCoins is used to update the cache stack
     323                 :             : // In particular it is tested that spending a duplicate coinbase tx
     324                 :             : // has the expected effect (the other duplicate is overwritten at all cache levels)
     325   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(updatecoins_simulation_test, UpdateTest)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     326                 :             : {
     327                 :           1 :     SeedRandomForTest(SeedRand::ZEROS);
     328                 :             : 
     329                 :           1 :     bool spent_a_duplicate_coinbase = false;
     330                 :             :     // A simple map to track what we expect the cache stack to represent.
     331         [ +  - ]:           1 :     std::map<COutPoint, Coin> result;
     332                 :             : 
     333                 :             :     // The cache stack.
     334         [ +  - ]:           1 :     CCoinsViewTest base{m_rng}; // A CCoinsViewTest at the bottom.
     335                 :           1 :     std::vector<std::unique_ptr<CCoinsViewCacheTest>> stack; // A stack of CCoinsViewCaches on top.
     336         [ +  - ]:           2 :     stack.push_back(std::make_unique<CCoinsViewCacheTest>(&base)); // Start with one cache.
     337                 :             : 
     338                 :             :     // Track the txids we've used in various sets
     339                 :           1 :     std::set<COutPoint> coinbase_coins;
     340                 :           1 :     std::set<COutPoint> disconnected_coins;
     341                 :           1 :     std::set<COutPoint> duplicate_coins;
     342                 :           1 :     std::set<COutPoint> utxoset;
     343                 :             : 
     344         [ +  + ]:       40001 :     for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
     345                 :       40000 :         uint32_t randiter = m_rng.rand32();
     346                 :             : 
     347                 :             :         // 19/20 txs add a new transaction
     348         [ +  + ]:       40000 :         if (randiter % 20 < 19) {
     349         [ +  - ]:       38029 :             CMutableTransaction tx;
     350         [ +  - ]:       38029 :             tx.vin.resize(1);
     351         [ +  - ]:       38029 :             tx.vout.resize(1);
     352                 :       38029 :             tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
     353                 :       38029 :             tx.vout[0].scriptPubKey.assign(m_rng.rand32() & 0x3F, 0); // Random sizes so we can test memory usage accounting
     354                 :       38029 :             const int height{int(m_rng.rand32() >> 1)};
     355                 :       38029 :             Coin old_coin;
     356                 :             : 
     357                 :             :             // 2/20 times create a new coinbase
     358   [ +  +  +  + ]:       38029 :             if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
     359                 :             :                 // 1/10 of those times create a duplicate coinbase
     360   [ +  +  -  + ]:        3931 :                 if (m_rng.randrange(10) == 0 && coinbase_coins.size()) {
     361                 :         400 :                     auto utxod = FindRandomFrom(coinbase_coins);
     362                 :             :                     // Reuse the exact same coinbase
     363         [ +  - ]:         400 :                     tx = CMutableTransaction{std::get<0>(utxod->second)};
     364                 :             :                     // shouldn't be available for reconnection if it's been duplicated
     365                 :         400 :                     disconnected_coins.erase(utxod->first);
     366                 :             : 
     367         [ +  - ]:         400 :                     duplicate_coins.insert(utxod->first);
     368                 :             :                 }
     369                 :             :                 else {
     370   [ +  -  +  - ]:        3531 :                     coinbase_coins.insert(COutPoint(tx.GetHash(), 0));
     371                 :             :                 }
     372   [ +  -  -  + ]:        7862 :                 assert(CTransaction(tx).IsCoinBase());
     373                 :             :             }
     374                 :             : 
     375                 :             :             // 17/20 times reconnect previous or add a regular tx
     376                 :             :             else {
     377                 :             : 
     378         [ +  + ]:       34098 :                 COutPoint prevout;
     379                 :             :                 // 1/20 times reconnect a previously disconnected tx
     380   [ +  +  +  + ]:       34098 :                 if (randiter % 20 == 2 && disconnected_coins.size()) {
     381                 :        1943 :                     auto utxod = FindRandomFrom(disconnected_coins);
     382         [ +  - ]:        1943 :                     tx = CMutableTransaction{std::get<0>(utxod->second)};
     383         [ +  - ]:        1943 :                     prevout = tx.vin[0].prevout;
     384   [ +  -  +  +  :        3886 :                     if (!CTransaction(tx).IsCoinBase() && !utxoset.contains(prevout)) {
             +  +  +  + ]
     385                 :         396 :                         disconnected_coins.erase(utxod->first);
     386                 :         396 :                         continue;
     387                 :             :                     }
     388                 :             : 
     389                 :             :                     // If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
     390         [ -  + ]:        1547 :                     if (utxoset.contains(utxod->first)) {
     391   [ #  #  #  # ]:           0 :                         assert(CTransaction(tx).IsCoinBase());
     392         [ #  # ]:           0 :                         assert(duplicate_coins.contains(utxod->first));
     393                 :             :                     }
     394                 :        1547 :                     disconnected_coins.erase(utxod->first);
     395                 :             :                 }
     396                 :             : 
     397                 :             :                 // 16/20 times create a regular tx
     398                 :             :                 else {
     399                 :       32155 :                     auto utxod = FindRandomFrom(utxoset);
     400         [ +  - ]:       32155 :                     prevout = utxod->first;
     401                 :             : 
     402                 :             :                     // Construct the tx to spend the coins of prevouthash
     403         [ +  - ]:       32155 :                     tx.vin[0].prevout = prevout;
     404   [ +  -  -  + ]:       64310 :                     assert(!CTransaction(tx).IsCoinBase());
     405                 :             :                 }
     406                 :             :                 // In this simple test coins only have two states, spent or unspent, save the unspent state to restore
     407         [ +  - ]:       33702 :                 old_coin = result[prevout];
     408                 :             :                 // Update the expected result of prevouthash to know these coins are spent
     409         [ +  - ]:       33702 :                 result[prevout].Clear();
     410                 :             : 
     411                 :       33702 :                 utxoset.erase(prevout);
     412                 :             : 
     413                 :             :                 // The test is designed to ensure spending a duplicate coinbase will work properly
     414                 :             :                 // if that ever happens and not resurrect the previously overwritten coinbase
     415         [ +  + ]:       33702 :                 if (duplicate_coins.contains(prevout)) {
     416                 :         376 :                     spent_a_duplicate_coinbase = true;
     417                 :             :                 }
     418                 :             : 
     419                 :             :             }
     420                 :             :             // Update the expected result to know about the new output coins
     421   [ -  +  -  + ]:       37633 :             assert(tx.vout.size() == 1);
     422         [ +  - ]:       37633 :             const COutPoint outpoint(tx.GetHash(), 0);
     423   [ +  -  +  - ]:       37633 :             result[outpoint] = Coin{tx.vout[0], height, CTransaction{tx}.IsCoinBase()};
     424                 :             : 
     425                 :             :             // Call UpdateCoins on the top cache
     426                 :       37633 :             CTxUndo undo;
     427   [ +  -  +  - ]:       37633 :             UpdateCoins(CTransaction{tx}, *(stack.back()), undo, height);
     428                 :             : 
     429                 :             :             // Update the utxo set for future spends
     430         [ +  - ]:       37633 :             utxoset.insert(outpoint);
     431                 :             : 
     432                 :             :             // Track this tx and undo info to use later
     433   [ +  -  +  - ]:      112899 :             utxoData.emplace(outpoint, std::make_tuple(tx,undo,old_coin));
     434         [ +  - ]:       78029 :         } else if (utxoset.size()) {
     435                 :             :             //1/20 times undo a previous transaction
     436                 :        1971 :             auto utxod = FindRandomFrom(utxoset);
     437                 :             : 
     438         [ +  - ]:        1971 :             CTransaction &tx = std::get<0>(utxod->second);
     439                 :        1971 :             CTxUndo &undo = std::get<1>(utxod->second);
     440         [ +  - ]:        1971 :             Coin &orig_coin = std::get<2>(utxod->second);
     441                 :             : 
     442                 :             :             // Update the expected result
     443                 :             :             // Remove new outputs
     444         [ +  - ]:        1971 :             result[utxod->first].Clear();
     445                 :             :             // If not coinbase restore prevout
     446         [ +  + ]:        1971 :             if (!tx.IsCoinBase()) {
     447         [ +  - ]:        1757 :                 result[tx.vin[0].prevout] = orig_coin;
     448                 :             :             }
     449                 :             : 
     450                 :             :             // Disconnect the tx from the current UTXO
     451                 :             :             // See code in DisconnectBlock
     452                 :             :             // remove outputs
     453   [ +  -  +  -  :        3942 :             BOOST_CHECK(stack.back()->SpendCoin(utxod->first));
             +  -  +  + ]
     454                 :             :             // restore inputs
     455         [ +  + ]:        1971 :             if (!tx.IsCoinBase()) {
     456                 :        1757 :                 const COutPoint &out = tx.vin[0].prevout;
     457                 :        1757 :                 Coin coin = undo.vprevout[0];
     458         [ +  - ]:        1757 :                 ApplyTxInUndo(std::move(coin), *(stack.back()), out);
     459                 :        1757 :             }
     460                 :             :             // Store as a candidate for reconnection
     461         [ +  - ]:        1971 :             disconnected_coins.insert(utxod->first);
     462                 :             : 
     463                 :             :             // Update the utxoset
     464                 :        1971 :             utxoset.erase(utxod->first);
     465         [ +  + ]:        1971 :             if (!tx.IsCoinBase())
     466         [ +  - ]:        1757 :                 utxoset.insert(tx.vin[0].prevout);
     467                 :             :         }
     468                 :             : 
     469                 :             :         // Once every 1000 iterations and at the end, verify the full cache.
     470   [ +  +  +  + ]:       39604 :         if (m_rng.randrange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
     471         [ +  + ]:      607183 :             for (const auto& entry : result) {
     472         [ +  - ]:      607146 :                 bool have = stack.back()->HaveCoin(entry.first);
     473         [ +  - ]:      607146 :                 const Coin& coin = stack.back()->AccessCoin(entry.first);
     474   [ +  -  +  -  :     1214292 :                 BOOST_CHECK(have == !coin.IsSpent());
                   +  - ]
     475   [ +  -  +  - ]:      607146 :                 BOOST_CHECK_EQUAL(coin, entry.second);
     476                 :             :             }
     477                 :             :         }
     478                 :             : 
     479                 :             :         // One every 10 iterations, remove a random entry from the cache
     480   [ +  +  +  + ]:       39604 :         if (utxoset.size() > 1 && m_rng.randrange(30) == 0) {
     481   [ -  +  +  - ]:        1346 :             stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
     482                 :             :         }
     483   [ +  +  +  + ]:       39604 :         if (disconnected_coins.size() > 1 && m_rng.randrange(30) == 0) {
     484   [ -  +  +  - ]:        1135 :             stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
     485                 :             :         }
     486   [ +  +  +  + ]:       39604 :         if (duplicate_coins.size() > 1 && m_rng.randrange(30) == 0) {
     487   [ -  +  +  - ]:        1328 :             stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
     488                 :             :         }
     489                 :             : 
     490         [ +  + ]:       39604 :         if (m_rng.randrange(100) == 0) {
     491                 :             :             // Every 100 iterations, flush an intermediate cache
     492   [ -  +  +  +  :         395 :             if (stack.size() > 1 && m_rng.randbool() == 0) {
                   +  + ]
     493         [ -  + ]:         148 :                 unsigned int flushIndex = m_rng.randrange(stack.size() - 1);
     494         [ +  - ]:         148 :                 stack[flushIndex]->Flush();
     495                 :             :             }
     496                 :             :         }
     497         [ +  + ]:       39604 :         if (m_rng.randrange(100) == 0) {
     498                 :             :             // Every 100 iterations, change the cache stack.
     499   [ -  +  +  -  :         373 :             if (stack.size() > 0 && m_rng.randbool() == 0) {
                   +  + ]
     500         [ +  - ]:         196 :                 stack.back()->Flush();
     501                 :         196 :                 stack.pop_back();
     502                 :             :             }
     503   [ -  +  +  +  :         373 :             if (stack.size() == 0 || (stack.size() < 4 && m_rng.randbool())) {
             +  +  +  + ]
     504                 :         197 :                 CCoinsView* tip = &base;
     505   [ -  +  +  + ]:         197 :                 if (stack.size() > 0) {
     506                 :         148 :                     tip = stack.back().get();
     507                 :             :                 }
     508         [ +  - ]:         394 :                 stack.push_back(std::make_unique<CCoinsViewCacheTest>(tip));
     509                 :             :             }
     510                 :             :         }
     511                 :             :     }
     512                 :             : 
     513                 :             :     // Verify coverage.
     514   [ +  -  +  - ]:           2 :     BOOST_CHECK(spent_a_duplicate_coinbase);
     515                 :           1 : }
     516                 :             : 
     517   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_serialization)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     518                 :             : {
     519                 :             :     // Good example
     520                 :           1 :     Coin cc1;
     521         [ +  - ]:           1 :     SpanReader{"97f23c835800816115944e077fe7c803cfa57f29b36bf87c1d35"_hex} >> cc1;
     522   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc1.IsCoinBase(), false);
     523   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc1.nHeight, 203998U);
     524   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc1.out.nValue, CAmount{60000000000});
     525   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(HexStr(cc1.out.scriptPubKey), HexStr(GetScriptForDestination(PKHash(uint160("816115944e077fe7c803cfa57f29b36bf87c1d35"_hex_u8)))));
          +  -  +  -  +  
                      - ]
     526                 :             : 
     527                 :             :     // Good example
     528                 :           1 :     Coin cc2;
     529         [ +  - ]:           1 :     SpanReader{"8ddf77bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4"_hex} >> cc2;
     530   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc2.IsCoinBase(), true);
     531   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc2.nHeight, 120891U);
     532   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc2.out.nValue, 110397);
     533   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(HexStr(cc2.out.scriptPubKey), HexStr(GetScriptForDestination(PKHash(uint160("8c988f1a4a4de2161e0f50aac7f17e7f9555caa4"_hex_u8)))));
          +  -  +  -  +  
                      - ]
     534                 :             : 
     535                 :             :     // Smallest possible example
     536                 :           1 :     Coin cc3;
     537         [ +  - ]:           1 :     SpanReader{"000006"_hex} >> cc3;
     538   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc3.IsCoinBase(), false);
     539   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc3.nHeight, 0U);
     540   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cc3.out.nValue, 0);
     541   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(cc3.out.scriptPubKey.size(), 0U);
                   +  - ]
     542                 :             : 
     543                 :             :     // scriptPubKey that ends beyond the end of the stream
     544   [ +  -  -  +  :           3 :     BOOST_CHECK_EXCEPTION(SpanReader{"000007"_hex} >> Coin{}, std::ios_base::failure, HasReason{"end of data"});
          -  -  -  -  -  
          +  +  -  +  -  
                   +  - ]
     545                 :             : 
     546                 :             :     // Very large scriptPubKey (3*10^9 bytes) past the end of the stream
     547                 :           1 :     DataStream tmp{};
     548                 :           1 :     uint64_t x = 3000000000ULL;
     549         [ +  - ]:           1 :     tmp << VARINT(x);
     550   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(HexStr(tmp), "8a95c0bb00");
             +  -  +  - ]
     551   [ +  -  -  +  :           3 :     BOOST_CHECK_EXCEPTION(SpanReader{"00008a95c0bb00"_hex} >> Coin{}, std::ios_base::failure, HasReason{"end of data"});
          -  -  -  -  -  
          +  +  -  +  -  
                   +  - ]
     552                 :           1 : }
     553                 :             : 
     554                 :             : const static COutPoint OUTPOINT;
     555                 :             : constexpr CAmount SPENT {-1};
     556                 :             : constexpr CAmount ABSENT{-2};
     557                 :             : constexpr CAmount VALUE1{100};
     558                 :             : constexpr CAmount VALUE2{200};
     559                 :             : constexpr CAmount VALUE3{300};
     560                 :             : 
     561                 :             : struct CoinEntry {
     562                 :             :     enum class State { CLEAN, DIRTY, FRESH, DIRTY_FRESH };
     563                 :             : 
     564                 :         167 :     const CAmount value;
     565                 :         167 :     const State state;
     566                 :             : 
     567                 :         253 :     constexpr CoinEntry(const CAmount v, const State s) : value{v}, state{s} {}
     568                 :             : 
     569   [ +  -  +  -  :         167 :     bool operator==(const CoinEntry& o) const = default;
             +  -  -  + ]
     570                 :           0 :     friend std::ostream& operator<<(std::ostream& os, const CoinEntry& e) { return os << e.value << ", " << e.state; }
     571                 :             : 
     572                 :             :     constexpr bool IsDirtyFresh() const { return state == State::DIRTY_FRESH; }
     573   [ +  +  +  +  :         416 :     constexpr bool IsDirty() const { return state == State::DIRTY || IsDirtyFresh(); }
             +  +  +  + ]
     574         [ +  + ]:         258 :     constexpr bool IsFresh() const { return state == State::FRESH || IsDirtyFresh(); }
     575                 :             : 
     576                 :         167 :     static constexpr State ToState(const bool is_dirty, const bool is_fresh) {
     577         [ +  + ]:         167 :         if (is_dirty && is_fresh) return State::DIRTY_FRESH;
     578         [ +  + ]:         110 :         if (is_dirty) return State::DIRTY;
     579         [ +  + ]:          43 :         if (is_fresh) return State::FRESH;
     580                 :             :         return State::CLEAN;
     581                 :             :     }
     582                 :             : };
     583                 :             : 
     584                 :             : using MaybeCoin   = std::optional<CoinEntry>;
     585                 :             : using CoinOrError = std::variant<MaybeCoin, std::string>;
     586                 :             : 
     587                 :             : constexpr MaybeCoin MISSING           {std::nullopt};
     588                 :             : constexpr MaybeCoin SPENT_DIRTY       {{SPENT,  CoinEntry::State::DIRTY}};
     589                 :             : constexpr MaybeCoin SPENT_DIRTY_FRESH {{SPENT,  CoinEntry::State::DIRTY_FRESH}};
     590                 :             : constexpr MaybeCoin SPENT_FRESH       {{SPENT,  CoinEntry::State::FRESH}};
     591                 :             : constexpr MaybeCoin SPENT_CLEAN       {{SPENT,  CoinEntry::State::CLEAN}};
     592                 :             : constexpr MaybeCoin VALUE1_DIRTY      {{VALUE1, CoinEntry::State::DIRTY}};
     593                 :             : constexpr MaybeCoin VALUE1_DIRTY_FRESH{{VALUE1, CoinEntry::State::DIRTY_FRESH}};
     594                 :             : constexpr MaybeCoin VALUE1_FRESH      {{VALUE1, CoinEntry::State::FRESH}};
     595                 :             : constexpr MaybeCoin VALUE1_CLEAN      {{VALUE1, CoinEntry::State::CLEAN}};
     596                 :             : constexpr MaybeCoin VALUE2_DIRTY      {{VALUE2, CoinEntry::State::DIRTY}};
     597                 :             : constexpr MaybeCoin VALUE2_DIRTY_FRESH{{VALUE2, CoinEntry::State::DIRTY_FRESH}};
     598                 :             : constexpr MaybeCoin VALUE2_FRESH      {{VALUE2, CoinEntry::State::FRESH}};
     599                 :             : constexpr MaybeCoin VALUE2_CLEAN      {{VALUE2, CoinEntry::State::CLEAN}};
     600                 :             : constexpr MaybeCoin VALUE3_DIRTY      {{VALUE3, CoinEntry::State::DIRTY}};
     601                 :             : constexpr MaybeCoin VALUE3_DIRTY_FRESH{{VALUE3, CoinEntry::State::DIRTY_FRESH}};
     602                 :             : 
     603                 :             : constexpr auto EX_OVERWRITE_UNSPENT{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"};
     604                 :             : constexpr auto EX_FRESH_MISAPPLIED {"FRESH flag misapplied to coin that exists in parent cache"};
     605                 :             : 
     606                 :         320 : static void SetCoinsValue(const CAmount value, Coin& coin)
     607                 :             : {
     608         [ -  + ]:         320 :     assert(value != ABSENT);
     609                 :         320 :     coin.Clear();
     610         [ -  + ]:         320 :     assert(coin.IsSpent());
     611         [ +  + ]:         320 :     if (value != SPENT) {
     612                 :         160 :         coin.out.nValue = value;
     613                 :         160 :         coin.nHeight = 1;
     614                 :         160 :         assert(!coin.IsSpent());
     615                 :             :     }
     616                 :         320 : }
     617                 :             : 
     618                 :         320 : static size_t InsertCoinsMapEntry(CCoinsMap& map, CoinsCachePair& sentinel, const CoinEntry& cache_coin)
     619                 :             : {
     620                 :         320 :     CCoinsCacheEntry entry;
     621                 :         320 :     SetCoinsValue(cache_coin.value, entry.coin);
     622   [ +  -  -  + ]:         320 :     auto [iter, inserted] = map.emplace(OUTPOINT, std::move(entry));
     623         [ -  + ]:         320 :     assert(inserted);
     624         [ +  + ]:         382 :     if (cache_coin.IsDirty()) CCoinsCacheEntry::SetDirty(*iter, sentinel);
     625         [ +  + ]:         382 :     if (cache_coin.IsFresh()) CCoinsCacheEntry::SetFresh(*iter, sentinel);
     626         [ -  + ]:         640 :     return iter->second.coin.DynamicMemoryUsage();
     627                 :         320 : }
     628                 :             : 
     629                 :         202 : static MaybeCoin GetCoinsMapEntry(const CCoinsMap& map, const COutPoint& outp = OUTPOINT)
     630                 :             : {
     631         [ +  + ]:         202 :     if (auto it{map.find(outp)}; it != map.end()) {
     632         [ +  + ]:         167 :         return CoinEntry{
     633         [ +  + ]:         167 :             it->second.coin.IsSpent() ? SPENT : it->second.coin.out.nValue,
     634   [ +  +  +  + ]:         384 :             CoinEntry::ToState(it->second.IsDirty(), it->second.IsFresh())};
     635                 :             :     }
     636                 :          35 :     return MISSING;
     637                 :             : }
     638                 :             : 
     639                 :         288 : static void WriteCoinsViewEntry(CCoinsView& view, const MaybeCoin& cache_coin)
     640                 :             : {
     641                 :         288 :     CoinsCachePair sentinel{};
     642         [ +  - ]:         288 :     sentinel.second.SelfRef(sentinel);
     643         [ +  - ]:         288 :     CCoinsMapMemoryResource resource;
     644   [ +  -  +  - ]:         288 :     CCoinsMap map{0, CCoinsMap::hasher{}, CCoinsMap::key_equal{}, &resource};
     645   [ +  +  +  - ]:         288 :     if (cache_coin) InsertCoinsMapEntry(map, sentinel, *cache_coin);
     646   [ +  +  +  + ]:         288 :     size_t dirty_count{cache_coin && cache_coin->IsDirty()};
     647         [ +  + ]:         288 :     auto cursor{CoinsViewCacheCursor(dirty_count, sentinel, map, /*will_erase=*/true)};
     648         [ +  + ]:         288 :     view.BatchWrite(cursor, {});
     649   [ +  -  +  - ]:         280 :     BOOST_CHECK_EQUAL(dirty_count, 0U);
     650                 :         288 : }
     651                 :             : 
     652                 :             : class SingleEntryCacheTest
     653                 :             : {
     654                 :             : public:
     655                 :         198 :     SingleEntryCacheTest(const CAmount base_value, const MaybeCoin& cache_coin)
     656         [ +  - ]:         198 :     {
     657         [ +  + ]:         198 :         auto base_cache_coin{base_value == ABSENT ? MISSING : CoinEntry{base_value, CoinEntry::State::DIRTY}};
     658         [ +  - ]:         198 :         WriteCoinsViewEntry(base, base_cache_coin);
     659         [ +  + ]:         198 :         if (cache_coin) {
     660         [ +  - ]:         176 :             cache.usage() += InsertCoinsMapEntry(cache.map(), cache.sentinel(), *cache_coin);
     661         [ +  + ]:         308 :             cache.dirty() += cache_coin->IsDirty();
     662                 :             :         }
     663                 :         198 :     }
     664                 :             : 
     665                 :             :     CCoinsViewCacheTest base{&CoinsViewEmpty::Get()};
     666                 :             :     CCoinsViewCacheTest cache{&base};
     667                 :             : };
     668                 :             : 
     669                 :          27 : static void CheckAccessCoin(const CAmount base_value, const MaybeCoin& cache_coin, const MaybeCoin& expected)
     670                 :             : {
     671                 :          27 :     SingleEntryCacheTest test{base_value, cache_coin};
     672         [ +  - ]:          27 :     auto& coin = test.cache.AccessCoin(OUTPOINT);
     673   [ +  -  +  -  :          27 :     BOOST_CHECK_EQUAL(coin.IsSpent(), !test.cache.GetCoin(OUTPOINT));
                   +  - ]
     674         [ +  - ]:          27 :     test.cache.SelfTest(/*sanity_check=*/false);
     675   [ +  -  +  - ]:          27 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), expected);
     676                 :          27 : }
     677                 :             : 
     678   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_access)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     679                 :             : {
     680                 :             :     /* Check AccessCoin behavior, requesting a coin from a cache view layered on
     681                 :             :      * top of a base view, and checking the resulting entry in the cache after
     682                 :             :      * the access.
     683                 :             :      *                  Base        Cache               Expected
     684                 :             :      */
     685         [ +  + ]:           4 :     for (auto base_value : {ABSENT, SPENT, VALUE1}) {
     686         [ +  + ]:           5 :         CheckAccessCoin(base_value, MISSING,            base_value == VALUE1 ? VALUE1_CLEAN : MISSING);
     687                 :             : 
     688                 :           3 :         CheckAccessCoin(base_value, SPENT_CLEAN,        SPENT_CLEAN       );
     689                 :           3 :         CheckAccessCoin(base_value, SPENT_FRESH,        SPENT_FRESH       );
     690                 :           3 :         CheckAccessCoin(base_value, SPENT_DIRTY,        SPENT_DIRTY       );
     691                 :           3 :         CheckAccessCoin(base_value, SPENT_DIRTY_FRESH,  SPENT_DIRTY_FRESH );
     692                 :             : 
     693                 :           3 :         CheckAccessCoin(base_value, VALUE2_CLEAN,       VALUE2_CLEAN      );
     694                 :           3 :         CheckAccessCoin(base_value, VALUE2_FRESH,       VALUE2_FRESH      );
     695                 :           3 :         CheckAccessCoin(base_value, VALUE2_DIRTY,       VALUE2_DIRTY      );
     696                 :           3 :         CheckAccessCoin(base_value, VALUE2_DIRTY_FRESH, VALUE2_DIRTY_FRESH);
     697                 :             :     }
     698                 :           1 : }
     699                 :             : 
     700                 :          27 : static void CheckSpendCoins(const CAmount base_value, const MaybeCoin& cache_coin, const MaybeCoin& expected)
     701                 :             : {
     702                 :          27 :     SingleEntryCacheTest test{base_value, cache_coin};
     703         [ +  - ]:          27 :     test.cache.SpendCoin(OUTPOINT);
     704         [ +  - ]:          27 :     test.cache.SelfTest();
     705   [ +  -  +  - ]:          27 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), expected);
     706                 :          27 : }
     707                 :             : 
     708   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_spend)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     709                 :             : {
     710                 :             :     /* Check SpendCoin behavior, requesting a coin from a cache view layered on
     711                 :             :      * top of a base view, spending, and then checking
     712                 :             :      * the resulting entry in the cache after the modification.
     713                 :             :      *                  Base        Cache               Expected
     714                 :             :      */
     715         [ +  + ]:           4 :     for (auto base_value : {ABSENT, SPENT, VALUE1}) {
     716         [ +  + ]:           5 :         CheckSpendCoins(base_value, MISSING,            base_value == VALUE1 ? SPENT_DIRTY : MISSING);
     717                 :             : 
     718                 :           3 :         CheckSpendCoins(base_value, SPENT_CLEAN,        SPENT_DIRTY);
     719                 :           3 :         CheckSpendCoins(base_value, SPENT_FRESH,        MISSING    );
     720                 :           3 :         CheckSpendCoins(base_value, SPENT_DIRTY,        SPENT_DIRTY);
     721                 :           3 :         CheckSpendCoins(base_value, SPENT_DIRTY_FRESH,  MISSING    );
     722                 :             : 
     723                 :           3 :         CheckSpendCoins(base_value, VALUE2_CLEAN,       SPENT_DIRTY);
     724                 :           3 :         CheckSpendCoins(base_value, VALUE2_FRESH,       MISSING    );
     725                 :           3 :         CheckSpendCoins(base_value, VALUE2_DIRTY,       SPENT_DIRTY);
     726                 :           3 :         CheckSpendCoins(base_value, VALUE2_DIRTY_FRESH, MISSING    );
     727                 :             :     }
     728                 :           1 : }
     729                 :             : 
     730                 :          54 : static void CheckAddCoin(const CAmount base_value, const MaybeCoin& cache_coin, const CAmount modify_value, const CoinOrError& expected, const bool coinbase)
     731                 :             : {
     732                 :          54 :     SingleEntryCacheTest test{base_value, cache_coin};
     733                 :          54 :     bool possible_overwrite{coinbase};
     734   [ +  -  +  + ]:         120 :     auto add_coin{[&] { test.cache.AddCoin(OUTPOINT, Coin{CTxOut{modify_value, CScript{}}, 1, coinbase}, possible_overwrite); }};
     735         [ +  + ]:          54 :     if (auto* expected_coin{std::get_if<MaybeCoin>(&expected)}) {
     736         [ +  - ]:          42 :         add_coin();
     737         [ +  - ]:          42 :         test.cache.SelfTest();
     738   [ +  -  +  - ]:          42 :         BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), *expected_coin);
     739                 :             :     } else {
     740   [ +  -  -  +  :          24 :         BOOST_CHECK_EXCEPTION(add_coin(), std::logic_error, HasReason(std::get<std::string>(expected)));
          -  -  -  -  -  
          +  +  -  -  +  
          -  +  +  -  +  
                      - ]
     741                 :             :     }
     742                 :          54 : }
     743                 :             : 
     744   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_add)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     745                 :             : {
     746                 :             :     /* Check AddCoin behavior, requesting a new coin from a cache view,
     747                 :             :      * writing a modification to the coin, and then checking the resulting
     748                 :             :      * entry in the cache after the modification. Verify behavior with the
     749                 :             :      * AddCoin coinbase argument set to false, and to true.
     750                 :             :      *               Base        Cache               Write   Expected              Coinbase
     751                 :             :      */
     752         [ +  + ]:           4 :     for (auto base_value : {ABSENT, SPENT, VALUE1}) {
     753         [ +  - ]:           3 :         CheckAddCoin(base_value, MISSING,            VALUE3, VALUE3_DIRTY_FRESH,   false);
     754         [ +  - ]:           3 :         CheckAddCoin(base_value, MISSING,            VALUE3, VALUE3_DIRTY,         true );
     755                 :             : 
     756         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_CLEAN,        VALUE3, VALUE3_DIRTY_FRESH,   false);
     757         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_CLEAN,        VALUE3, VALUE3_DIRTY,         true );
     758         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_FRESH,        VALUE3, VALUE3_DIRTY_FRESH,   false);
     759         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_FRESH,        VALUE3, VALUE3_DIRTY_FRESH,   true );
     760         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_DIRTY,        VALUE3, VALUE3_DIRTY,         false);
     761         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_DIRTY,        VALUE3, VALUE3_DIRTY,         true );
     762         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_DIRTY_FRESH,  VALUE3, VALUE3_DIRTY_FRESH,   false);
     763         [ +  - ]:           3 :         CheckAddCoin(base_value, SPENT_DIRTY_FRESH,  VALUE3, VALUE3_DIRTY_FRESH,   true );
     764                 :             : 
     765         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_CLEAN,       VALUE3, EX_OVERWRITE_UNSPENT, false);
     766         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_CLEAN,       VALUE3, VALUE3_DIRTY,         true );
     767         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_FRESH,       VALUE3, EX_OVERWRITE_UNSPENT, false);
     768         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_FRESH,       VALUE3, VALUE3_DIRTY_FRESH,   true );
     769         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_DIRTY,       VALUE3, EX_OVERWRITE_UNSPENT, false);
     770         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_DIRTY,       VALUE3, VALUE3_DIRTY,         true );
     771         [ +  - ]:           3 :         CheckAddCoin(base_value, VALUE2_DIRTY_FRESH, VALUE3, EX_OVERWRITE_UNSPENT, false);
     772         [ +  - ]:           6 :         CheckAddCoin(base_value, VALUE2_DIRTY_FRESH, VALUE3, VALUE3_DIRTY_FRESH,   true );
     773                 :             :     }
     774                 :           1 : }
     775                 :             : 
     776                 :          90 : static void CheckWriteCoins(const MaybeCoin& parent, const MaybeCoin& child, const CoinOrError& expected)
     777                 :             : {
     778                 :          90 :     SingleEntryCacheTest test{ABSENT, parent};
     779                 :         180 :     auto write_coins{[&] { WriteCoinsViewEntry(test.cache, child); }};
     780         [ +  + ]:          90 :     if (auto* expected_coin{std::get_if<MaybeCoin>(&expected)}) {
     781         [ +  - ]:          82 :         write_coins();
     782         [ +  - ]:          82 :         test.cache.SelfTest(/*sanity_check=*/false);
     783   [ +  -  +  - ]:          82 :         BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), *expected_coin);
     784                 :             :     } else {
     785   [ +  -  -  +  :          16 :         BOOST_CHECK_EXCEPTION(write_coins(), std::logic_error, HasReason(std::get<std::string>(expected)));
          -  -  -  -  -  
          +  +  -  -  +  
          -  +  +  -  +  
                      - ]
     786                 :             :     }
     787                 :          90 : }
     788                 :             : 
     789   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_write)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     790                 :             : {
     791                 :             :     /* Check BatchWrite behavior, flushing one entry from a child cache to a
     792                 :             :      * parent cache, and checking the resulting entry in the parent cache
     793                 :             :      * after the write.
     794                 :             :      *              Parent              Child               Expected
     795                 :             :      */
     796         [ +  - ]:           1 :     CheckWriteCoins(MISSING,            MISSING,            MISSING            );
     797         [ +  - ]:           1 :     CheckWriteCoins(MISSING,            SPENT_DIRTY,        SPENT_DIRTY        );
     798         [ +  - ]:           1 :     CheckWriteCoins(MISSING,            SPENT_DIRTY_FRESH,  MISSING            );
     799         [ +  - ]:           1 :     CheckWriteCoins(MISSING,            VALUE2_DIRTY,       VALUE2_DIRTY       );
     800         [ +  - ]:           1 :     CheckWriteCoins(MISSING,            VALUE2_DIRTY_FRESH, VALUE2_DIRTY_FRESH );
     801         [ +  - ]:           1 :     CheckWriteCoins(SPENT_CLEAN,        MISSING,            SPENT_CLEAN        );
     802         [ +  - ]:           1 :     CheckWriteCoins(SPENT_FRESH,        MISSING,            SPENT_FRESH        );
     803         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY,        MISSING,            SPENT_DIRTY        );
     804         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY_FRESH,  MISSING,            SPENT_DIRTY_FRESH  );
     805                 :             : 
     806         [ +  - ]:           1 :     CheckWriteCoins(SPENT_CLEAN,        SPENT_DIRTY,        SPENT_DIRTY        );
     807         [ +  - ]:           1 :     CheckWriteCoins(SPENT_CLEAN,        SPENT_DIRTY_FRESH,  SPENT_DIRTY        );
     808         [ +  - ]:           1 :     CheckWriteCoins(SPENT_FRESH,        SPENT_DIRTY,        MISSING            );
     809         [ +  - ]:           1 :     CheckWriteCoins(SPENT_FRESH,        SPENT_DIRTY_FRESH,  MISSING            );
     810         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY,        SPENT_DIRTY,        SPENT_DIRTY        );
     811         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY,        SPENT_DIRTY_FRESH,  SPENT_DIRTY        );
     812         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY_FRESH,  SPENT_DIRTY,        MISSING            );
     813         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY_FRESH,  SPENT_DIRTY_FRESH,  MISSING            );
     814                 :             : 
     815         [ +  - ]:           1 :     CheckWriteCoins(SPENT_CLEAN,        VALUE2_DIRTY,       VALUE2_DIRTY       );
     816         [ +  - ]:           1 :     CheckWriteCoins(SPENT_CLEAN,        VALUE2_DIRTY_FRESH, VALUE2_DIRTY       );
     817         [ +  - ]:           1 :     CheckWriteCoins(SPENT_FRESH,        VALUE2_DIRTY,       VALUE2_DIRTY_FRESH );
     818         [ +  - ]:           1 :     CheckWriteCoins(SPENT_FRESH,        VALUE2_DIRTY_FRESH, VALUE2_DIRTY_FRESH );
     819         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY,        VALUE2_DIRTY,       VALUE2_DIRTY       );
     820         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY,        VALUE2_DIRTY_FRESH, VALUE2_DIRTY       );
     821         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY_FRESH,  VALUE2_DIRTY,       VALUE2_DIRTY_FRESH );
     822         [ +  - ]:           1 :     CheckWriteCoins(SPENT_DIRTY_FRESH,  VALUE2_DIRTY_FRESH, VALUE2_DIRTY_FRESH );
     823                 :             : 
     824         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_CLEAN,       MISSING,            VALUE1_CLEAN       );
     825         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_FRESH,       MISSING,            VALUE1_FRESH       );
     826         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY,       MISSING,            VALUE1_DIRTY       );
     827         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY_FRESH, MISSING,            VALUE1_DIRTY_FRESH );
     828         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_CLEAN,       SPENT_DIRTY,        SPENT_DIRTY        );
     829         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_CLEAN,       SPENT_DIRTY_FRESH,  EX_FRESH_MISAPPLIED);
     830         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_FRESH,       SPENT_DIRTY,        MISSING            );
     831         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_FRESH,       SPENT_DIRTY_FRESH,  EX_FRESH_MISAPPLIED);
     832         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY,       SPENT_DIRTY,        SPENT_DIRTY        );
     833         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY,       SPENT_DIRTY_FRESH,  EX_FRESH_MISAPPLIED);
     834         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY_FRESH, SPENT_DIRTY,        MISSING            );
     835         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY_FRESH, SPENT_DIRTY_FRESH,  EX_FRESH_MISAPPLIED);
     836                 :             : 
     837         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_CLEAN,       VALUE2_DIRTY,       VALUE2_DIRTY       );
     838         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_CLEAN,       VALUE2_DIRTY_FRESH, EX_FRESH_MISAPPLIED);
     839         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_FRESH,       VALUE2_DIRTY,       VALUE2_DIRTY_FRESH );
     840         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_FRESH,       VALUE2_DIRTY_FRESH, EX_FRESH_MISAPPLIED);
     841         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY,       VALUE2_DIRTY,       VALUE2_DIRTY       );
     842         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY,       VALUE2_DIRTY_FRESH, EX_FRESH_MISAPPLIED);
     843         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY_FRESH, VALUE2_DIRTY,       VALUE2_DIRTY_FRESH );
     844         [ +  - ]:           1 :     CheckWriteCoins(VALUE1_DIRTY_FRESH, VALUE2_DIRTY_FRESH, EX_FRESH_MISAPPLIED);
     845                 :             : 
     846                 :             :     // The checks above omit cases where the child state is not DIRTY, since
     847                 :             :     // they would be too repetitive (the parent cache is never updated in these
     848                 :             :     // cases). The loop below covers these cases and makes sure the parent cache
     849                 :             :     // is always left unchanged.
     850                 :           9 :     for (const MaybeCoin& parent : {MISSING,
     851                 :             :                                     SPENT_CLEAN, SPENT_DIRTY, SPENT_FRESH, SPENT_DIRTY_FRESH,
     852         [ +  + ]:          10 :                                     VALUE1_CLEAN, VALUE1_DIRTY, VALUE1_FRESH, VALUE1_DIRTY_FRESH}) {
     853                 :          99 :         for (const MaybeCoin& child : {MISSING,
     854                 :             :                                        SPENT_CLEAN, SPENT_FRESH,
     855         [ +  + ]:          54 :                                        VALUE2_CLEAN, VALUE2_FRESH}) {
     856         [ +  - ]:          45 :             auto expected{CoinOrError{parent}}; // TODO test failure cases as well
     857         [ +  - ]:          45 :             CheckWriteCoins(parent, child, expected);
     858                 :          45 :         }
     859                 :             :     }
     860                 :           1 : }
     861                 :             : 
     862                 :           4 : struct FlushTest : BasicTestingSetup {
     863                 :          13 : Coin MakeCoin()
     864                 :             : {
     865                 :          13 :     Coin coin;
     866                 :          13 :     coin.out.nValue = m_rng.rand32();
     867                 :          13 :     coin.nHeight = m_rng.randrange(4096);
     868                 :          13 :     coin.fCoinBase = false;
     869                 :          13 :     return coin;
     870                 :             : }
     871                 :             : 
     872                 :             : 
     873                 :             : //! For CCoinsViewCache instances backed by either another cache instance or
     874                 :             : //! leveldb, test cache behavior and flag state (DIRTY/FRESH) by
     875                 :             : //!
     876                 :             : //! 1. Adding a random coin to the child-most cache,
     877                 :             : //! 2. Flushing all caches (without erasing),
     878                 :             : //! 3. Ensure the entry still exists in the cache and has been written to parent,
     879                 :             : //! 4. (if `do_erasing_flush`) Flushing the caches again (with erasing),
     880                 :             : //! 5. (if `do_erasing_flush`) Ensure the entry has been written to the parent and is no longer in the cache,
     881                 :             : //! 6. Spend the coin, ensure it no longer exists in the parent.
     882                 :             : //!
     883                 :           4 : void TestFlushBehavior(
     884                 :             :     CCoinsViewCacheTest* view,
     885                 :             :     CCoinsViewDB& base,
     886                 :             :     std::vector<std::unique_ptr<CCoinsViewCacheTest>>& all_caches,
     887                 :             :     bool do_erasing_flush)
     888                 :             : {
     889                 :           4 :     size_t cache_usage;
     890                 :           4 :     size_t cache_size;
     891                 :             : 
     892                 :          22 :     auto flush_all = [this, &all_caches](bool erase) {
     893                 :             :         // Flush in reverse order to ensure that flushes happen from children up.
     894         [ +  + ]:          54 :         for (auto i = all_caches.rbegin(); i != all_caches.rend(); ++i) {
     895                 :          36 :             auto& cache = *i;
     896                 :          36 :             cache->SanityCheck();
     897                 :             :             // block_hash must be filled before flushing to disk; value is
     898                 :             :             // unimportant here. This is normally done during connect/disconnect block.
     899                 :          36 :             cache->SetBestBlock(m_rng.rand256());
     900         [ +  + ]:          36 :             erase ? cache->Flush() : cache->Sync();
     901                 :             :         }
     902                 :          22 :     };
     903                 :             : 
     904                 :           4 :     Txid txid = Txid::FromUint256(m_rng.rand256());
     905                 :           4 :     COutPoint outp = COutPoint(txid, 0);
     906                 :           4 :     Coin coin = MakeCoin();
     907                 :             :     // Ensure the coins views haven't seen this coin before.
     908   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
     909   [ +  -  +  -  :           8 :     BOOST_CHECK(!view->HaveCoin(outp));
                   +  - ]
     910                 :             : 
     911                 :             :     // --- 1. Adding a random coin to the child cache
     912                 :             :     //
     913         [ +  - ]:           4 :     view->AddCoin(outp, Coin(coin), false);
     914                 :             : 
     915         [ +  - ]:           4 :     cache_usage = view->DynamicMemoryUsage();
     916         [ +  - ]:           4 :     cache_size = view->map().size();
     917                 :             : 
     918                 :             :     // `base` shouldn't have coin (no flush yet) but `view` should have cached it.
     919   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
     920   [ +  -  +  -  :           8 :     BOOST_CHECK(view->HaveCoin(outp));
             +  -  +  - ]
     921                 :             : 
     922   [ +  -  +  - ]:           4 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::DIRTY_FRESH));
     923                 :             : 
     924                 :             :     // --- 2. Flushing all caches (without erasing)
     925                 :             :     //
     926         [ +  - ]:           4 :     flush_all(/*erase=*/ false);
     927                 :             : 
     928                 :             :     // CoinsMap usage should be unchanged since we didn't erase anything.
     929   [ +  -  +  -  :           4 :     BOOST_CHECK_EQUAL(cache_usage, view->DynamicMemoryUsage());
                   +  - ]
     930   [ +  -  +  - ]:           4 :     BOOST_CHECK_EQUAL(cache_size, view->map().size());
     931                 :             : 
     932                 :             :     // --- 3. Ensuring the entry still exists in the cache and has been written to parent
     933                 :             :     //
     934   [ +  -  +  - ]:           4 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::CLEAN)); // State should have been wiped.
     935                 :             : 
     936                 :             :     // Both views should now have the coin.
     937   [ +  -  +  -  :           8 :     BOOST_CHECK(base.HaveCoin(outp));
             +  -  +  - ]
     938   [ +  -  +  -  :           8 :     BOOST_CHECK(view->HaveCoin(outp));
             +  -  +  + ]
     939                 :             : 
     940         [ +  + ]:           4 :     if (do_erasing_flush) {
     941                 :             :         // --- 4. Flushing the caches again (with erasing)
     942                 :             :         //
     943         [ +  - ]:           2 :         flush_all(/*erase=*/ true);
     944                 :             : 
     945                 :             :         // Memory does not necessarily go down due to the map using a memory pool
     946   [ +  -  +  -  :           4 :         BOOST_TEST(view->DynamicMemoryUsage() <= cache_usage);
          +  -  +  -  +  
                      - ]
     947                 :             :         // Size of the cache must go down though
     948   [ +  -  +  -  :           4 :         BOOST_TEST(view->map().size() < cache_size);
             +  -  +  - ]
     949                 :             : 
     950                 :             :         // --- 5. Ensuring the entry is no longer in the cache
     951                 :             :         //
     952   [ +  -  +  -  :           4 :         BOOST_CHECK(!GetCoinsMapEntry(view->map(), outp));
                   +  - ]
     953         [ +  - ]:           2 :         view->AccessCoin(outp);
     954   [ +  -  +  - ]:           2 :         BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::CLEAN));
     955                 :             :     }
     956                 :             : 
     957                 :             :     // Can't overwrite an entry without specifying that an overwrite is
     958                 :             :     // expected.
     959   [ +  -  -  +  :          12 :     BOOST_CHECK_THROW(
          -  -  -  -  -  
             +  +  -  +  
                      - ]
     960                 :             :         view->AddCoin(outp, Coin(coin), /*possible_overwrite=*/ false),
     961                 :             :         std::logic_error);
     962                 :             : 
     963                 :             :     // --- 6. Spend the coin.
     964                 :             :     //
     965   [ +  -  +  -  :           8 :     BOOST_CHECK(view->SpendCoin(outp));
             +  -  +  - ]
     966                 :             : 
     967                 :             :     // The coin should be in the cache, but spent and marked dirty.
     968   [ +  -  +  - ]:           4 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), SPENT_DIRTY);
     969   [ +  -  +  -  :           8 :     BOOST_CHECK(!view->HaveCoin(outp)); // Coin should be considered spent in `view`.
             +  -  +  - ]
     970   [ +  -  +  -  :           8 :     BOOST_CHECK(base.HaveCoin(outp));  // But coin should still be unspent in `base`.
             +  -  +  - ]
     971                 :             : 
     972         [ +  - ]:           4 :     flush_all(/*erase=*/ false);
     973                 :             : 
     974                 :             :     // Coin should be considered spent in both views.
     975   [ +  -  +  -  :           8 :     BOOST_CHECK(!view->HaveCoin(outp));
             +  -  +  - ]
     976   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
     977                 :             : 
     978                 :             :     // Spent coin should not be spendable.
     979   [ +  -  +  -  :           8 :     BOOST_CHECK(!view->SpendCoin(outp));
                   +  - ]
     980                 :             : 
     981                 :             :     // --- Bonus check: ensure that a coin added to the base view via one cache
     982                 :             :     //     can be spent by another cache which has never seen it.
     983                 :             :     //
     984                 :           4 :     txid = Txid::FromUint256(m_rng.rand256());
     985                 :           4 :     outp = COutPoint(txid, 0);
     986                 :           4 :     coin = MakeCoin();
     987   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
     988   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
             +  -  +  - ]
     989   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
             +  -  +  - ]
     990                 :             : 
     991         [ +  - ]:           4 :     all_caches[0]->AddCoin(outp, std::move(coin), false);
     992         [ +  - ]:           4 :     all_caches[0]->Sync();
     993   [ +  -  +  -  :           8 :     BOOST_CHECK(base.HaveCoin(outp));
             +  -  +  - ]
     994   [ +  -  +  -  :           8 :     BOOST_CHECK(all_caches[0]->HaveCoin(outp));
             +  -  +  - ]
     995   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[1]->HaveCoinInCache(outp));
             +  -  +  - ]
     996                 :             : 
     997   [ +  -  +  -  :           8 :     BOOST_CHECK(all_caches[1]->SpendCoin(outp));
             +  -  +  - ]
     998         [ +  - ]:           4 :     flush_all(/*erase=*/ false);
     999   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
    1000   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
             +  -  +  - ]
    1001   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
             +  -  +  - ]
    1002                 :             : 
    1003         [ +  - ]:           4 :     flush_all(/*erase=*/ true); // Erase all cache content.
    1004                 :             : 
    1005                 :             :     // --- Bonus check 2: ensure that a FRESH, spent coin is deleted by Sync()
    1006                 :             :     //
    1007                 :           4 :     txid = Txid::FromUint256(m_rng.rand256());
    1008                 :           4 :     outp = COutPoint(txid, 0);
    1009                 :           4 :     coin = MakeCoin();
    1010                 :           4 :     CAmount coin_val = coin.out.nValue;
    1011   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
    1012   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
             +  -  +  - ]
    1013   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
             +  -  +  - ]
    1014                 :             : 
    1015                 :             :     // Add and spend from same cache without flushing.
    1016         [ +  - ]:           4 :     all_caches[0]->AddCoin(outp, std::move(coin), false);
    1017                 :             : 
    1018                 :             :     // Coin should be FRESH in the cache.
    1019   [ +  -  +  - ]:           4 :     BOOST_CHECK_EQUAL(GetCoinsMapEntry(all_caches[0]->map(), outp), CoinEntry(coin_val, CoinEntry::State::DIRTY_FRESH));
    1020                 :             :     // Base shouldn't have seen coin.
    1021   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
             +  -  +  - ]
    1022                 :             : 
    1023   [ +  -  +  -  :           8 :     BOOST_CHECK(all_caches[0]->SpendCoin(outp));
             +  -  +  - ]
    1024         [ +  - ]:           4 :     all_caches[0]->Sync();
    1025                 :             : 
    1026                 :             :     // Ensure there is no sign of the coin after spend/flush.
    1027   [ +  -  +  -  :           8 :     BOOST_CHECK(!GetCoinsMapEntry(all_caches[0]->map(), outp));
                   +  - ]
    1028   [ +  -  +  -  :           8 :     BOOST_CHECK(!all_caches[0]->HaveCoinInCache(outp));
             +  -  +  - ]
    1029   [ +  -  +  -  :           8 :     BOOST_CHECK(!base.HaveCoin(outp));
                   +  - ]
    1030                 :           4 : }
    1031                 :             : }; // struct FlushTest
    1032                 :             : 
    1033   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(ccoins_flush_behavior, FlushTest)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1034                 :             : {
    1035                 :             :     // Create two in-memory caches atop a leveldb view.
    1036                 :           0 :     CCoinsViewDB base{{.path = "test", .cache_bytes = 8_MiB, .memory_only = true}, {}};
    1037                 :           1 :     std::vector<std::unique_ptr<CCoinsViewCacheTest>> caches;
    1038         [ +  - ]:           2 :     caches.push_back(std::make_unique<CCoinsViewCacheTest>(&base));
    1039         [ +  - ]:           2 :     caches.push_back(std::make_unique<CCoinsViewCacheTest>(caches.back().get()));
    1040                 :             : 
    1041         [ +  + ]:           3 :     for (const auto& view : caches) {
    1042         [ +  - ]:           2 :         TestFlushBehavior(view.get(), base, caches, /*do_erasing_flush=*/false);
    1043         [ +  - ]:           2 :         TestFlushBehavior(view.get(), base, caches, /*do_erasing_flush=*/true);
    1044                 :             :     }
    1045         [ +  - ]:           2 : }
    1046                 :             : 
    1047   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(coins_db_leveldb_layout, FlushTest)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1048                 :             : {
    1049                 :           3 :     auto level2_files{[](CCoinsViewDB& base) {
    1050   [ +  -  -  +  :           4 :         return *Assert(ToIntegral<int>(*Assert(base.GetDBProperty("leveldb.num-files-at-level2"))));
                   -  + ]
    1051                 :             :     }};
    1052                 :           1 :     const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), 0};
    1053                 :           1 :     const Coin coin{MakeCoin()};
    1054                 :           1 :     const uint256 block_hash{m_rng.rand256()};
    1055                 :             : 
    1056                 :           1 :     CCoinsViewDB base{{.path = m_args.GetDataDirBase() / "coins_db_leveldb_layout", .cache_bytes = 1_MiB, .wipe_data = true}, {}};
    1057         [ +  - ]:           1 :     CCoinsViewCache cache{&base};
    1058                 :             : 
    1059         [ +  - ]:           1 :     cache.EmplaceCoinInternalDANGER(COutPoint{outpoint}, Coin{coin});
    1060         [ +  - ]:           1 :     cache.SetBestBlock(block_hash);
    1061         [ +  - ]:           1 :     cache.Sync();
    1062                 :             : 
    1063   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(level2_files(base), 0);
                   +  - ]
    1064   [ +  -  +  - ]:           3 :     WITH_LOCK(::cs_main, return base.CompactFullAsync()).wait();
    1065   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(level2_files(base), 1);
                   +  - ]
    1066                 :             : 
    1067   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(*Assert(base.GetCoin(outpoint)), coin);
                   +  - ]
    1068   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(base.GetBestBlock(), block_hash);
                   +  - ]
    1069   [ +  -  +  - ]:           3 : }
    1070                 :             : 
    1071   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(coins_resource_is_used)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1072                 :             : {
    1073                 :           1 :     CCoinsMapMemoryResource resource;
    1074         [ +  - ]:           1 :     PoolResourceTester::CheckAllDataAccountedFor(resource);
    1075                 :             : 
    1076                 :           1 :     {
    1077   [ +  -  +  - ]:           1 :         CCoinsMap map{0, CCoinsMap::hasher{}, CCoinsMap::key_equal{}, &resource};
    1078   [ +  -  +  -  :           2 :         BOOST_TEST(memusage::DynamicUsage(map) >= resource.ChunkSizeBytes());
             +  -  +  - ]
    1079                 :             : 
    1080         [ +  - ]:           1 :         map.reserve(1000);
    1081                 :             : 
    1082                 :             :         // The resource has preallocated a chunk, so we should have space for at several nodes without the need to allocate anything else.
    1083                 :           1 :         const auto usage_before = memusage::DynamicUsage(map);
    1084                 :             : 
    1085                 :           1 :         COutPoint out_point{};
    1086         [ +  + ]:        1001 :         for (size_t i = 0; i < 1000; ++i) {
    1087                 :        1000 :             out_point.n = i;
    1088         [ +  - ]:        1000 :             map[out_point];
    1089                 :             :         }
    1090   [ +  -  +  -  :           2 :         BOOST_TEST(usage_before == memusage::DynamicUsage(map));
                   +  - ]
    1091                 :           0 :     }
    1092                 :             : 
    1093         [ +  - ]:           1 :     PoolResourceTester::CheckAllDataAccountedFor(resource);
    1094                 :           1 : }
    1095                 :             : 
    1096   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_addcoin_exception_keeps_usage_balanced)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1097                 :             : {
    1098                 :           1 :     CCoinsViewCacheTest cache{&CoinsViewEmpty::Get()};
    1099                 :             : 
    1100                 :           1 :     const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
    1101                 :             : 
    1102   [ -  +  +  - ]:           1 :     const Coin coin1{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
    1103         [ +  - ]:           1 :     cache.AddCoin(outpoint, Coin{coin1}, /*possible_overwrite=*/false);
    1104         [ +  - ]:           1 :     cache.SelfTest();
    1105                 :             : 
    1106   [ -  +  +  - ]:           1 :     const Coin coin2{CTxOut{m_rng.randrange(20), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 2)}, 2, false};
    1107   [ +  -  -  +  :           3 :     BOOST_CHECK_THROW(cache.AddCoin(outpoint, Coin{coin2}, /*possible_overwrite=*/false), std::logic_error);
          -  -  -  -  -  
             +  +  -  +  
                      - ]
    1108         [ +  - ]:           1 :     cache.SelfTest();
    1109                 :             : 
    1110   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.AccessCoin(outpoint), coin1);
                   +  - ]
    1111                 :           1 : }
    1112                 :             : 
    1113   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_emplace_duplicate_keeps_usage_balanced)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1114                 :             : {
    1115                 :           1 :     CCoinsViewCacheTest cache{&CoinsViewEmpty::Get()};
    1116                 :             : 
    1117                 :           1 :     const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
    1118                 :             : 
    1119   [ -  +  +  - ]:           1 :     const Coin coin1{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
    1120         [ +  - ]:           1 :     cache.EmplaceCoinInternalDANGER(outpoint, Coin{coin1});
    1121         [ +  - ]:           1 :     cache.SelfTest();
    1122                 :             : 
    1123   [ -  +  +  - ]:           1 :     const Coin coin2{CTxOut{m_rng.randrange(20), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 2)}, 2, false};
    1124         [ +  - ]:           1 :     cache.EmplaceCoinInternalDANGER(outpoint, Coin{coin2});
    1125         [ +  - ]:           1 :     cache.SelfTest();
    1126                 :             : 
    1127   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.AccessCoin(outpoint), coin1);
                   +  - ]
    1128                 :           1 : }
    1129                 :             : 
    1130   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_reset_guard)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1131                 :             : {
    1132         [ +  - ]:           1 :     CCoinsViewTest root{m_rng};
    1133         [ +  - ]:           1 :     CCoinsViewCache root_cache{&root};
    1134                 :           1 :     uint256 base_best_block{m_rng.rand256()};
    1135         [ +  - ]:           1 :     root_cache.SetBestBlock(base_best_block);
    1136         [ +  - ]:           1 :     root_cache.Flush();
    1137                 :             : 
    1138         [ +  - ]:           1 :     CCoinsViewCache cache{&root};
    1139                 :             : 
    1140                 :           1 :     const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
    1141                 :             : 
    1142   [ -  +  +  - ]:           1 :     const Coin coin{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
    1143         [ +  - ]:           1 :     cache.EmplaceCoinInternalDANGER(outpoint, Coin{coin});
    1144   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cache.GetDirtyCount(), 1U);
    1145                 :             : 
    1146                 :           1 :     uint256 cache_best_block{m_rng.rand256()};
    1147         [ +  - ]:           1 :     cache.SetBestBlock(cache_best_block);
    1148                 :             : 
    1149                 :           1 :     {
    1150         [ +  - ]:           1 :         const auto reset_guard{cache.CreateResetGuard()};
    1151   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(cache.AccessCoin(outpoint), coin);
                   +  - ]
    1152   [ +  -  +  -  :           2 :         BOOST_CHECK(!cache.AccessCoin(outpoint).IsSpent());
             +  -  +  - ]
    1153   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(cache.GetCacheSize(), 1);
                   +  - ]
    1154   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(cache.GetDirtyCount(), 1);
    1155   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(cache.GetBestBlock(), cache_best_block);
                   +  - ]
    1156   [ +  -  +  -  :           2 :         BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
                   +  - ]
    1157                 :           0 :     }
    1158                 :             : 
    1159   [ +  -  +  -  :           2 :     BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
             +  -  +  - ]
    1160   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
                   +  - ]
    1161   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cache.GetDirtyCount(), 0);
    1162   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
                   +  - ]
    1163   [ +  -  +  -  :           2 :     BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
                   +  - ]
    1164                 :             : 
    1165                 :             :     // Using a reset guard again is idempotent
    1166                 :           1 :     {
    1167                 :           1 :         const auto reset_guard{cache.CreateResetGuard()};
    1168                 :           1 :     }
    1169                 :             : 
    1170   [ +  -  +  -  :           2 :     BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
             +  -  +  - ]
    1171   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
                   +  - ]
    1172   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cache.GetDirtyCount(), 0U);
    1173   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
                   +  - ]
    1174   [ +  -  +  -  :           2 :     BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
             +  -  +  - ]
    1175                 :             : 
    1176                 :             :     // Flush should be a no-op after reset.
    1177         [ +  - ]:           1 :     cache.Flush();
    1178   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(cache.GetDirtyCount(), 0U);
    1179                 :           1 : }
    1180                 :             : 
    1181   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ccoins_peekcoin)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
    1182                 :             : {
    1183                 :           1 :     CCoinsViewTest base{m_rng};
    1184                 :             : 
    1185                 :             :     // Populate the base view with a coin.
    1186                 :           1 :     const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
    1187         [ +  - ]:           1 :     const Coin coin{CTxOut{m_rng.randrange(10), CScript{}}, 1, false};
    1188                 :           1 :     {
    1189         [ +  - ]:           1 :         CCoinsViewCache cache{&base};
    1190         [ +  - ]:           1 :         cache.AddCoin(outpoint, Coin{coin}, /*possible_overwrite=*/false);
    1191         [ +  - ]:           1 :         cache.Flush();
    1192                 :           1 :     }
    1193                 :             : 
    1194                 :             :     // Verify PeekCoin can read through the cache stack without mutating the intermediate cache.
    1195         [ +  - ]:           1 :     CCoinsViewCacheTest main_cache{&base};
    1196         [ +  - ]:           1 :     const auto fetched{main_cache.PeekCoin(outpoint)};
    1197   [ +  -  +  -  :           2 :     BOOST_CHECK(fetched.has_value());
                   +  - ]
    1198   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(*fetched, coin);
    1199   [ +  -  +  -  :           2 :     BOOST_CHECK(!main_cache.HaveCoinInCache(outpoint));
                   +  - ]
    1200                 :           1 : }
    1201                 :             : 
    1202                 :             : BOOST_AUTO_TEST_SUITE_END()
        

Generated by: LCOV version 2.0-1