LCOV - code coverage report
Current view: top level - src/test - coins_tests.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 98.2 % 609 598
Test Date: 2026-01-16 04:47:09 Functions: 95.6 % 45 43
Branches: 54.6 % 2186 1194

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

Generated by: LCOV version 2.0-1