LCOV - code coverage report
Current view: top level - src/test - coins_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 98.1 % 585 574
Test Date: 2025-08-01 05:08:13 Functions: 95.1 % 41 39
Branches: 55.5 % 1868 1037

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

Generated by: LCOV version 2.0-1