Bitcoin Core 30.99.0
P2P Digital Currency
coins_tests.cpp
Go to the documentation of this file.
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>
10#include <test/util/random.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
24using namespace util::hex_literals;
25
26int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out);
27void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
28
29namespace
30{
32bool operator==(const Coin &a, const Coin &b) {
33 // Empty Coin objects are always equal.
34 if (a.IsSpent() && b.IsSpent()) return true;
35 return a.fCoinBase == b.fCoinBase &&
36 a.nHeight == b.nHeight &&
37 a.out == b.out;
38}
39
40class CCoinsViewTest : public CCoinsView
41{
42 FastRandomContext& m_rng;
43 uint256 hashBestBlock_;
44 std::map<COutPoint, Coin> map_;
45
46public:
47 CCoinsViewTest(FastRandomContext& rng) : m_rng{rng} {}
48
49 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override
50 {
51 if (auto it{map_.find(outpoint)}; it != map_.end() && !it->second.IsSpent()) return it->second;
52 return std::nullopt;
53 }
54
55 uint256 GetBestBlock() const override { return hashBestBlock_; }
56
57 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock) override
58 {
59 for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)){
60 if (it->second.IsDirty()) {
61 // Same optimization used in CCoinsViewDB is to only write dirty entries.
62 map_[it->first] = it->second.coin;
63 if (it->second.coin.IsSpent() && m_rng.randrange(3) == 0) {
64 // Randomly delete empty entries on write.
65 map_.erase(it->first);
66 }
67 }
68 }
69 if (!hashBlock.IsNull())
70 hashBestBlock_ = hashBlock;
71 }
72};
73
74class CCoinsViewCacheTest : public CCoinsViewCache
75{
76public:
77 explicit CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}
78
79 void SelfTest(bool sanity_check = true) const
80 {
81 // Manually recompute the dynamic usage of the whole data, and compare it.
82 size_t ret = memusage::DynamicUsage(cacheCoins);
83 size_t count = 0;
84 for (const auto& entry : cacheCoins) {
85 ret += entry.second.coin.DynamicMemoryUsage();
86 ++count;
87 }
90 if (sanity_check) {
92 }
93 }
94
95 CCoinsMap& map() const { return cacheCoins; }
96 CoinsCachePair& sentinel() const { return m_sentinel; }
97 size_t& usage() const { return cachedCoinsUsage; }
98};
99
100} // namespace
101
102static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;
103
105// This is a large randomized insert/remove simulation test on a variable-size
106// stack of caches on top of CCoinsViewTest.
107//
108// It will randomly create/update/delete Coin entries to a tip of caches, with
109// txids picked from a limited list of random 256-bit hashes. Occasionally, a
110// new tip is added to the stack of caches, or the tip is flushed and removed.
111//
112// During the process, booleans are kept to make sure that the randomized
113// operation hits all branches.
114//
115// If fake_best_block is true, assign a random uint256 to mock the recording
116// of best block on flush. This is necessary when using CCoinsViewDB as the base,
117// otherwise we'll hit an assertion in BatchWrite.
118//
119void SimulationTest(CCoinsView* base, bool fake_best_block)
120{
121 // Various coverage trackers.
122 bool removed_all_caches = false;
123 bool reached_4_caches = false;
124 bool added_an_entry = false;
125 bool added_an_unspendable_entry = false;
126 bool removed_an_entry = false;
127 bool updated_an_entry = false;
128 bool found_an_entry = false;
129 bool missed_an_entry = false;
130 bool uncached_an_entry = false;
131 bool flushed_without_erase = false;
132
133 // A simple map to track what we expect the cache stack to represent.
134 std::map<COutPoint, Coin> result;
135
136 // The cache stack.
137 std::vector<std::unique_ptr<CCoinsViewCacheTest>> stack; // A stack of CCoinsViewCaches on top.
138 stack.push_back(std::make_unique<CCoinsViewCacheTest>(base)); // Start with one cache.
139
140 // Use a limited set of random transaction ids, so we do test overwriting entries.
141 std::vector<Txid> txids;
142 txids.resize(NUM_SIMULATION_ITERATIONS / 8);
143 for (unsigned int i = 0; i < txids.size(); i++) {
144 txids[i] = Txid::FromUint256(m_rng.rand256());
145 }
146
147 for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
148 // Do a random modification.
149 {
150 auto txid = txids[m_rng.randrange(txids.size())]; // txid we're going to modify in this iteration.
151 Coin& coin = result[COutPoint(txid, 0)];
152
153 // Determine whether to test HaveCoin before or after Access* (or both). As these functions
154 // can influence each other's behaviour by pulling things into the cache, all combinations
155 // are tested.
156 bool test_havecoin_before = m_rng.randbits(2) == 0;
157 bool test_havecoin_after = m_rng.randbits(2) == 0;
158
159 bool result_havecoin = test_havecoin_before ? stack.back()->HaveCoin(COutPoint(txid, 0)) : false;
160
161 // Infrequently, test usage of AccessByTxid instead of AccessCoin - the
162 // former just delegates to the latter and returns the first unspent in a txn.
163 const Coin& entry = (m_rng.randrange(500) == 0) ?
164 AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
165 BOOST_CHECK(coin == entry);
166
167 if (test_havecoin_before) {
168 BOOST_CHECK(result_havecoin == !entry.IsSpent());
169 }
170
171 if (test_havecoin_after) {
172 bool ret = stack.back()->HaveCoin(COutPoint(txid, 0));
173 BOOST_CHECK(ret == !entry.IsSpent());
174 }
175
176 if (m_rng.randrange(5) == 0 || coin.IsSpent()) {
177 Coin newcoin;
178 newcoin.out.nValue = RandMoney(m_rng);
179 newcoin.nHeight = 1;
180
181 // Infrequently test adding unspendable coins.
182 if (m_rng.randrange(16) == 0 && coin.IsSpent()) {
185 added_an_unspendable_entry = true;
186 } else {
187 // Random sizes so we can test memory usage accounting
188 newcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
189 (coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
190 coin = newcoin;
191 }
192 bool is_overwrite = !coin.IsSpent() || m_rng.rand32() & 1;
193 stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), is_overwrite);
194 } else {
195 // Spend the coin.
196 removed_an_entry = true;
197 coin.Clear();
198 BOOST_CHECK(stack.back()->SpendCoin(COutPoint(txid, 0)));
199 }
200 }
201
202 // Once every 10 iterations, remove a random entry from the cache
203 if (m_rng.randrange(10) == 0) {
204 COutPoint out(txids[m_rng.rand32() % txids.size()], 0);
205 int cacheid = m_rng.rand32() % stack.size();
206 stack[cacheid]->Uncache(out);
207 uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
208 }
209
210 // Once every 1000 iterations and at the end, verify the full cache.
211 if (m_rng.randrange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
212 for (const auto& entry : result) {
213 bool have = stack.back()->HaveCoin(entry.first);
214 const Coin& coin = stack.back()->AccessCoin(entry.first);
215 BOOST_CHECK(have == !coin.IsSpent());
216 BOOST_CHECK(coin == entry.second);
217 if (coin.IsSpent()) {
218 missed_an_entry = true;
219 } else {
220 BOOST_CHECK(stack.back()->HaveCoinInCache(entry.first));
221 found_an_entry = true;
222 }
223 }
224 for (const auto& test : stack) {
225 test->SelfTest();
226 }
227 }
228
229 if (m_rng.randrange(100) == 0) {
230 // Every 100 iterations, flush an intermediate cache
231 if (stack.size() > 1 && m_rng.randbool() == 0) {
232 unsigned int flushIndex = m_rng.randrange(stack.size() - 1);
233 if (fake_best_block) stack[flushIndex]->SetBestBlock(m_rng.rand256());
234 bool should_erase = m_rng.randrange(4) < 3;
235 should_erase ? stack[flushIndex]->Flush() : stack[flushIndex]->Sync();
236 flushed_without_erase |= !should_erase;
237 }
238 }
239 if (m_rng.randrange(100) == 0) {
240 // Every 100 iterations, change the cache stack.
241 if (stack.size() > 0 && m_rng.randbool() == 0) {
242 //Remove the top cache
243 if (fake_best_block) stack.back()->SetBestBlock(m_rng.rand256());
244 bool should_erase = m_rng.randrange(4) < 3;
245 should_erase ? stack.back()->Flush() : stack.back()->Sync();
246 flushed_without_erase |= !should_erase;
247 stack.pop_back();
248 }
249 if (stack.size() == 0 || (stack.size() < 4 && m_rng.randbool())) {
250 //Add a new cache
251 CCoinsView* tip = base;
252 if (stack.size() > 0) {
253 tip = stack.back().get();
254 } else {
255 removed_all_caches = true;
256 }
257 stack.push_back(std::make_unique<CCoinsViewCacheTest>(tip));
258 if (stack.size() == 4) {
259 reached_4_caches = true;
260 }
261 }
262 }
263 }
264
265 // Verify coverage.
266 BOOST_CHECK(removed_all_caches);
267 BOOST_CHECK(reached_4_caches);
268 BOOST_CHECK(added_an_entry);
269 BOOST_CHECK(added_an_unspendable_entry);
270 BOOST_CHECK(removed_an_entry);
271 BOOST_CHECK(updated_an_entry);
272 BOOST_CHECK(found_an_entry);
273 BOOST_CHECK(missed_an_entry);
274 BOOST_CHECK(uncached_an_entry);
275 BOOST_CHECK(flushed_without_erase);
276}
277}; // struct CacheTest
278
280
281// Run the above simulation for multiple base types.
282BOOST_FIXTURE_TEST_CASE(coins_cache_base_simulation_test, CacheTest)
283{
284 CCoinsViewTest base{m_rng};
285 SimulationTest(&base, false);
286}
287
289
291
292BOOST_FIXTURE_TEST_CASE(coins_cache_dbbase_simulation_test, CacheTest)
293{
294 CCoinsViewDB db_base{{.path = "test", .cache_bytes = 1 << 23, .memory_only = true}, {}};
295 SimulationTest(&db_base, true);
296}
297
299
301
303// Store of all necessary tx and undo data for next test
304typedef std::map<COutPoint, std::tuple<CTransaction,CTxUndo,Coin>> UtxoData;
306
307UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
308 assert(utxoSet.size());
309 auto utxoSetIt = utxoSet.lower_bound(COutPoint(Txid::FromUint256(m_rng.rand256()), 0));
310 if (utxoSetIt == utxoSet.end()) {
311 utxoSetIt = utxoSet.begin();
312 }
313 auto utxoDataIt = utxoData.find(*utxoSetIt);
314 assert(utxoDataIt != utxoData.end());
315 return utxoDataIt;
316}
317}; // struct UpdateTest
318
319
320// This test is similar to the previous test
321// except the emphasis is on testing the functionality of UpdateCoins
322// random txs are created and UpdateCoins is used to update the cache stack
323// In particular it is tested that spending a duplicate coinbase tx
324// has the expected effect (the other duplicate is overwritten at all cache levels)
325BOOST_FIXTURE_TEST_CASE(updatecoins_simulation_test, UpdateTest)
326{
327 SeedRandomForTest(SeedRand::ZEROS);
328
329 bool spent_a_duplicate_coinbase = false;
330 // A simple map to track what we expect the cache stack to represent.
331 std::map<COutPoint, Coin> result;
332
333 // The cache stack.
334 CCoinsViewTest base{m_rng}; // A CCoinsViewTest at the bottom.
335 std::vector<std::unique_ptr<CCoinsViewCacheTest>> stack; // A stack of CCoinsViewCaches on top.
336 stack.push_back(std::make_unique<CCoinsViewCacheTest>(&base)); // Start with one cache.
337
338 // Track the txids we've used in various sets
339 std::set<COutPoint> coinbase_coins;
340 std::set<COutPoint> disconnected_coins;
341 std::set<COutPoint> duplicate_coins;
342 std::set<COutPoint> utxoset;
343
344 for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
345 uint32_t randiter = m_rng.rand32();
346
347 // 19/20 txs add a new transaction
348 if (randiter % 20 < 19) {
350 tx.vin.resize(1);
351 tx.vout.resize(1);
352 tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
353 tx.vout[0].scriptPubKey.assign(m_rng.rand32() & 0x3F, 0); // Random sizes so we can test memory usage accounting
354 const int height{int(m_rng.rand32() >> 1)};
355 Coin old_coin;
356
357 // 2/20 times create a new coinbase
358 if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
359 // 1/10 of those times create a duplicate coinbase
360 if (m_rng.randrange(10) == 0 && coinbase_coins.size()) {
361 auto utxod = FindRandomFrom(coinbase_coins);
362 // Reuse the exact same coinbase
363 tx = CMutableTransaction{std::get<0>(utxod->second)};
364 // shouldn't be available for reconnection if it's been duplicated
365 disconnected_coins.erase(utxod->first);
366
367 duplicate_coins.insert(utxod->first);
368 }
369 else {
370 coinbase_coins.insert(COutPoint(tx.GetHash(), 0));
371 }
372 assert(CTransaction(tx).IsCoinBase());
373 }
374
375 // 17/20 times reconnect previous or add a regular tx
376 else {
377
378 COutPoint prevout;
379 // 1/20 times reconnect a previously disconnected tx
380 if (randiter % 20 == 2 && disconnected_coins.size()) {
381 auto utxod = FindRandomFrom(disconnected_coins);
382 tx = CMutableTransaction{std::get<0>(utxod->second)};
383 prevout = tx.vin[0].prevout;
384 if (!CTransaction(tx).IsCoinBase() && !utxoset.contains(prevout)) {
385 disconnected_coins.erase(utxod->first);
386 continue;
387 }
388
389 // If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
390 if (utxoset.contains(utxod->first)) {
391 assert(CTransaction(tx).IsCoinBase());
392 assert(duplicate_coins.contains(utxod->first));
393 }
394 disconnected_coins.erase(utxod->first);
395 }
396
397 // 16/20 times create a regular tx
398 else {
399 auto utxod = FindRandomFrom(utxoset);
400 prevout = utxod->first;
401
402 // Construct the tx to spend the coins of prevouthash
403 tx.vin[0].prevout = prevout;
404 assert(!CTransaction(tx).IsCoinBase());
405 }
406 // In this simple test coins only have two states, spent or unspent, save the unspent state to restore
407 old_coin = result[prevout];
408 // Update the expected result of prevouthash to know these coins are spent
409 result[prevout].Clear();
410
411 utxoset.erase(prevout);
412
413 // The test is designed to ensure spending a duplicate coinbase will work properly
414 // if that ever happens and not resurrect the previously overwritten coinbase
415 if (duplicate_coins.contains(prevout)) {
416 spent_a_duplicate_coinbase = true;
417 }
418
419 }
420 // Update the expected result to know about the new output coins
421 assert(tx.vout.size() == 1);
422 const COutPoint outpoint(tx.GetHash(), 0);
423 result[outpoint] = Coin{tx.vout[0], height, CTransaction{tx}.IsCoinBase()};
424
425 // Call UpdateCoins on the top cache
426 CTxUndo undo;
427 UpdateCoins(CTransaction{tx}, *(stack.back()), undo, height);
428
429 // Update the utxo set for future spends
430 utxoset.insert(outpoint);
431
432 // Track this tx and undo info to use later
433 utxoData.emplace(outpoint, std::make_tuple(tx,undo,old_coin));
434 } else if (utxoset.size()) {
435 //1/20 times undo a previous transaction
436 auto utxod = FindRandomFrom(utxoset);
437
438 CTransaction &tx = std::get<0>(utxod->second);
439 CTxUndo &undo = std::get<1>(utxod->second);
440 Coin &orig_coin = std::get<2>(utxod->second);
441
442 // Update the expected result
443 // Remove new outputs
444 result[utxod->first].Clear();
445 // If not coinbase restore prevout
446 if (!tx.IsCoinBase()) {
447 result[tx.vin[0].prevout] = orig_coin;
448 }
449
450 // Disconnect the tx from the current UTXO
451 // See code in DisconnectBlock
452 // remove outputs
453 BOOST_CHECK(stack.back()->SpendCoin(utxod->first));
454 // restore inputs
455 if (!tx.IsCoinBase()) {
456 const COutPoint &out = tx.vin[0].prevout;
457 Coin coin = undo.vprevout[0];
458 ApplyTxInUndo(std::move(coin), *(stack.back()), out);
459 }
460 // Store as a candidate for reconnection
461 disconnected_coins.insert(utxod->first);
462
463 // Update the utxoset
464 utxoset.erase(utxod->first);
465 if (!tx.IsCoinBase())
466 utxoset.insert(tx.vin[0].prevout);
467 }
468
469 // Once every 1000 iterations and at the end, verify the full cache.
470 if (m_rng.randrange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
471 for (const auto& entry : result) {
472 bool have = stack.back()->HaveCoin(entry.first);
473 const Coin& coin = stack.back()->AccessCoin(entry.first);
474 BOOST_CHECK(have == !coin.IsSpent());
475 BOOST_CHECK(coin == entry.second);
476 }
477 }
478
479 // One every 10 iterations, remove a random entry from the cache
480 if (utxoset.size() > 1 && m_rng.randrange(30) == 0) {
481 stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
482 }
483 if (disconnected_coins.size() > 1 && m_rng.randrange(30) == 0) {
484 stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
485 }
486 if (duplicate_coins.size() > 1 && m_rng.randrange(30) == 0) {
487 stack[m_rng.rand32() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
488 }
489
490 if (m_rng.randrange(100) == 0) {
491 // Every 100 iterations, flush an intermediate cache
492 if (stack.size() > 1 && m_rng.randbool() == 0) {
493 unsigned int flushIndex = m_rng.randrange(stack.size() - 1);
494 stack[flushIndex]->Flush();
495 }
496 }
497 if (m_rng.randrange(100) == 0) {
498 // Every 100 iterations, change the cache stack.
499 if (stack.size() > 0 && m_rng.randbool() == 0) {
500 stack.back()->Flush();
501 stack.pop_back();
502 }
503 if (stack.size() == 0 || (stack.size() < 4 && m_rng.randbool())) {
504 CCoinsView* tip = &base;
505 if (stack.size() > 0) {
506 tip = stack.back().get();
507 }
508 stack.push_back(std::make_unique<CCoinsViewCacheTest>(tip));
509 }
510 }
511 }
512
513 // Verify coverage.
514 BOOST_CHECK(spent_a_duplicate_coinbase);
515}
516
517BOOST_AUTO_TEST_CASE(ccoins_serialization)
518{
519 // Good example
520 DataStream ss1{"97f23c835800816115944e077fe7c803cfa57f29b36bf87c1d35"_hex};
521 Coin cc1;
522 ss1 >> cc1;
523 BOOST_CHECK_EQUAL(cc1.fCoinBase, false);
524 BOOST_CHECK_EQUAL(cc1.nHeight, 203998U);
525 BOOST_CHECK_EQUAL(cc1.out.nValue, CAmount{60000000000});
526 BOOST_CHECK_EQUAL(HexStr(cc1.out.scriptPubKey), HexStr(GetScriptForDestination(PKHash(uint160("816115944e077fe7c803cfa57f29b36bf87c1d35"_hex_u8)))));
527
528 // Good example
529 DataStream ss2{"8ddf77bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4"_hex};
530 Coin cc2;
531 ss2 >> cc2;
532 BOOST_CHECK_EQUAL(cc2.fCoinBase, true);
533 BOOST_CHECK_EQUAL(cc2.nHeight, 120891U);
534 BOOST_CHECK_EQUAL(cc2.out.nValue, 110397);
535 BOOST_CHECK_EQUAL(HexStr(cc2.out.scriptPubKey), HexStr(GetScriptForDestination(PKHash(uint160("8c988f1a4a4de2161e0f50aac7f17e7f9555caa4"_hex_u8)))));
536
537 // Smallest possible example
538 DataStream ss3{"000006"_hex};
539 Coin cc3;
540 ss3 >> cc3;
541 BOOST_CHECK_EQUAL(cc3.fCoinBase, false);
542 BOOST_CHECK_EQUAL(cc3.nHeight, 0U);
545
546 // scriptPubKey that ends beyond the end of the stream
547 DataStream ss4{"000007"_hex};
548 try {
549 Coin cc4;
550 ss4 >> cc4;
551 BOOST_CHECK_MESSAGE(false, "We should have thrown");
552 } catch (const std::ios_base::failure&) {
553 }
554
555 // Very large scriptPubKey (3*10^9 bytes) past the end of the stream
556 DataStream tmp{};
557 uint64_t x = 3000000000ULL;
558 tmp << VARINT(x);
559 BOOST_CHECK_EQUAL(HexStr(tmp), "8a95c0bb00");
560 DataStream ss5{"00008a95c0bb00"_hex};
561 try {
562 Coin cc5;
563 ss5 >> cc5;
564 BOOST_CHECK_MESSAGE(false, "We should have thrown");
565 } catch (const std::ios_base::failure&) {
566 }
567}
568
569const static COutPoint OUTPOINT;
570constexpr CAmount SPENT {-1};
571constexpr CAmount ABSENT{-2};
572constexpr CAmount VALUE1{100};
573constexpr CAmount VALUE2{200};
574constexpr CAmount VALUE3{300};
575
576struct CoinEntry {
577 enum class State { CLEAN, DIRTY, FRESH, DIRTY_FRESH };
578
581
582 constexpr CoinEntry(const CAmount v, const State s) : value{v}, state{s} {}
583
584 bool operator==(const CoinEntry& o) const = default;
585 friend std::ostream& operator<<(std::ostream& os, const CoinEntry& e) { return os << e.value << ", " << e.state; }
586
587 constexpr bool IsDirtyFresh() const { return state == State::DIRTY_FRESH; }
588 constexpr bool IsDirty() const { return state == State::DIRTY || IsDirtyFresh(); }
589 constexpr bool IsFresh() const { return state == State::FRESH || IsDirtyFresh(); }
590
591 static constexpr State ToState(const bool is_dirty, const bool is_fresh) {
592 if (is_dirty && is_fresh) return State::DIRTY_FRESH;
593 if (is_dirty) return State::DIRTY;
594 if (is_fresh) return State::FRESH;
595 return State::CLEAN;
596 }
597};
598
599using MaybeCoin = std::optional<CoinEntry>;
600using CoinOrError = std::variant<MaybeCoin, std::string>;
601
602constexpr MaybeCoin MISSING {std::nullopt};
617
618constexpr auto EX_OVERWRITE_UNSPENT{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"};
619constexpr auto EX_FRESH_MISAPPLIED {"FRESH flag misapplied to coin that exists in parent cache"};
620
621static void SetCoinsValue(const CAmount value, Coin& coin)
622{
623 assert(value != ABSENT);
624 coin.Clear();
625 assert(coin.IsSpent());
626 if (value != SPENT) {
627 coin.out.nValue = value;
628 coin.nHeight = 1;
629 assert(!coin.IsSpent());
630 }
631}
632
633static size_t InsertCoinsMapEntry(CCoinsMap& map, CoinsCachePair& sentinel, const CoinEntry& cache_coin)
634{
635 CCoinsCacheEntry entry;
636 SetCoinsValue(cache_coin.value, entry.coin);
637 auto [iter, inserted] = map.emplace(OUTPOINT, std::move(entry));
638 assert(inserted);
639 if (cache_coin.IsDirty()) CCoinsCacheEntry::SetDirty(*iter, sentinel);
640 if (cache_coin.IsFresh()) CCoinsCacheEntry::SetFresh(*iter, sentinel);
641 return iter->second.coin.DynamicMemoryUsage();
642}
643
644static MaybeCoin GetCoinsMapEntry(const CCoinsMap& map, const COutPoint& outp = OUTPOINT)
645{
646 if (auto it{map.find(outp)}; it != map.end()) {
647 return CoinEntry{
648 it->second.coin.IsSpent() ? SPENT : it->second.coin.out.nValue,
649 CoinEntry::ToState(it->second.IsDirty(), it->second.IsFresh())};
650 }
651 return MISSING;
652}
653
654static void WriteCoinsViewEntry(CCoinsView& view, const MaybeCoin& cache_coin)
655{
656 CoinsCachePair sentinel{};
657 sentinel.second.SelfRef(sentinel);
659 CCoinsMap map{0, CCoinsMap::hasher{}, CCoinsMap::key_equal{}, &resource};
660 if (cache_coin) InsertCoinsMapEntry(map, sentinel, *cache_coin);
661 auto cursor{CoinsViewCacheCursor(sentinel, map, /*will_erase=*/true)};
662 view.BatchWrite(cursor, {});
663}
664
666{
667public:
668 SingleEntryCacheTest(const CAmount base_value, const MaybeCoin& cache_coin)
669 {
670 auto base_cache_coin{base_value == ABSENT ? MISSING : CoinEntry{base_value, CoinEntry::State::DIRTY}};
671 WriteCoinsViewEntry(base, base_cache_coin);
672 if (cache_coin) cache.usage() += InsertCoinsMapEntry(cache.map(), cache.sentinel(), *cache_coin);
673 }
674
676 CCoinsViewCacheTest base{&root};
677 CCoinsViewCacheTest cache{&base};
678};
679
680static void CheckAccessCoin(const CAmount base_value, const MaybeCoin& cache_coin, const MaybeCoin& expected)
681{
682 SingleEntryCacheTest test{base_value, cache_coin};
683 auto& coin = test.cache.AccessCoin(OUTPOINT);
684 BOOST_CHECK_EQUAL(coin.IsSpent(), !test.cache.GetCoin(OUTPOINT));
685 test.cache.SelfTest(/*sanity_check=*/false);
686 BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), expected);
687}
688
690{
691 /* Check AccessCoin behavior, requesting a coin from a cache view layered on
692 * top of a base view, and checking the resulting entry in the cache after
693 * the access.
694 * Base Cache Expected
695 */
696 for (auto base_value : {ABSENT, SPENT, VALUE1}) {
697 CheckAccessCoin(base_value, MISSING, base_value == VALUE1 ? VALUE1_CLEAN : MISSING);
698
703
708 }
709}
710
711static void CheckSpendCoins(const CAmount base_value, const MaybeCoin& cache_coin, const MaybeCoin& expected)
712{
713 SingleEntryCacheTest test{base_value, cache_coin};
714 test.cache.SpendCoin(OUTPOINT);
715 test.cache.SelfTest();
716 BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), expected);
717}
718
720{
721 /* Check SpendCoin behavior, requesting a coin from a cache view layered on
722 * top of a base view, spending, and then checking
723 * the resulting entry in the cache after the modification.
724 * Base Cache Expected
725 */
726 for (auto base_value : {ABSENT, SPENT, VALUE1}) {
727 CheckSpendCoins(base_value, MISSING, base_value == VALUE1 ? SPENT_DIRTY : MISSING);
728
730 CheckSpendCoins(base_value, SPENT_FRESH, MISSING );
733
735 CheckSpendCoins(base_value, VALUE2_FRESH, MISSING );
738 }
739}
740
741static void CheckAddCoin(const CAmount base_value, const MaybeCoin& cache_coin, const CAmount modify_value, const CoinOrError& expected, const bool coinbase)
742{
743 SingleEntryCacheTest test{base_value, cache_coin};
744 bool possible_overwrite{coinbase};
745 auto add_coin{[&] { test.cache.AddCoin(OUTPOINT, Coin{CTxOut{modify_value, CScript{}}, 1, coinbase}, possible_overwrite); }};
746 if (auto* expected_coin{std::get_if<MaybeCoin>(&expected)}) {
747 add_coin();
748 test.cache.SelfTest();
749 BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), *expected_coin);
750 } else {
751 BOOST_CHECK_EXCEPTION(add_coin(), std::logic_error, HasReason(std::get<std::string>(expected)));
752 }
753}
754
756{
757 /* Check AddCoin behavior, requesting a new coin from a cache view,
758 * writing a modification to the coin, and then checking the resulting
759 * entry in the cache after the modification. Verify behavior with the
760 * AddCoin coinbase argument set to false, and to true.
761 * Base Cache Write Expected Coinbase
762 */
763 for (auto base_value : {ABSENT, SPENT, VALUE1}) {
764 CheckAddCoin(base_value, MISSING, VALUE3, VALUE3_DIRTY_FRESH, false);
765 CheckAddCoin(base_value, MISSING, VALUE3, VALUE3_DIRTY, true );
766
768 CheckAddCoin(base_value, SPENT_CLEAN, VALUE3, VALUE3_DIRTY, true );
771 CheckAddCoin(base_value, SPENT_DIRTY, VALUE3, VALUE3_DIRTY, false);
772 CheckAddCoin(base_value, SPENT_DIRTY, VALUE3, VALUE3_DIRTY, true );
775
777 CheckAddCoin(base_value, VALUE2_CLEAN, VALUE3, VALUE3_DIRTY, true );
781 CheckAddCoin(base_value, VALUE2_DIRTY, VALUE3, VALUE3_DIRTY, true );
784 }
785}
786
787static void CheckWriteCoins(const MaybeCoin& parent, const MaybeCoin& child, const CoinOrError& expected)
788{
789 SingleEntryCacheTest test{ABSENT, parent};
790 auto write_coins{[&] { WriteCoinsViewEntry(test.cache, child); }};
791 if (auto* expected_coin{std::get_if<MaybeCoin>(&expected)}) {
792 write_coins();
793 test.cache.SelfTest(/*sanity_check=*/false);
794 BOOST_CHECK_EQUAL(GetCoinsMapEntry(test.cache.map()), *expected_coin);
795 } else {
796 BOOST_CHECK_EXCEPTION(write_coins(), std::logic_error, HasReason(std::get<std::string>(expected)));
797 }
798}
799
801{
802 /* Check BatchWrite behavior, flushing one entry from a child cache to a
803 * parent cache, and checking the resulting entry in the parent cache
804 * after the write.
805 * Parent Child Expected
806 */
816
825
834
847
856
857 // The checks above omit cases where the child state is not DIRTY, since
858 // they would be too repetitive (the parent cache is never updated in these
859 // cases). The loop below covers these cases and makes sure the parent cache
860 // is always left unchanged.
861 for (const MaybeCoin& parent : {MISSING,
864 for (const MaybeCoin& child : {MISSING,
867 auto expected{CoinOrError{parent}}; // TODO test failure cases as well
868 CheckWriteCoins(parent, child, expected);
869 }
870 }
871}
872
875{
876 Coin coin;
877 coin.out.nValue = m_rng.rand32();
878 coin.nHeight = m_rng.randrange(4096);
879 coin.fCoinBase = 0;
880 return coin;
881}
882
883
895 CCoinsViewCacheTest* view,
896 CCoinsViewDB& base,
897 std::vector<std::unique_ptr<CCoinsViewCacheTest>>& all_caches,
898 bool do_erasing_flush)
899{
900 size_t cache_usage;
901 size_t cache_size;
902
903 auto flush_all = [this, &all_caches](bool erase) {
904 // Flush in reverse order to ensure that flushes happen from children up.
905 for (auto i = all_caches.rbegin(); i != all_caches.rend(); ++i) {
906 auto& cache = *i;
907 cache->SanityCheck();
908 // hashBlock must be filled before flushing to disk; value is
909 // unimportant here. This is normally done during connect/disconnect block.
910 cache->SetBestBlock(m_rng.rand256());
911 erase ? cache->Flush() : cache->Sync();
912 }
913 };
914
916 COutPoint outp = COutPoint(txid, 0);
917 Coin coin = MakeCoin();
918 // Ensure the coins views haven't seen this coin before.
919 BOOST_CHECK(!base.HaveCoin(outp));
920 BOOST_CHECK(!view->HaveCoin(outp));
921
922 // --- 1. Adding a random coin to the child cache
923 //
924 view->AddCoin(outp, Coin(coin), false);
925
926 cache_usage = view->DynamicMemoryUsage();
927 cache_size = view->map().size();
928
929 // `base` shouldn't have coin (no flush yet) but `view` should have cached it.
930 BOOST_CHECK(!base.HaveCoin(outp));
931 BOOST_CHECK(view->HaveCoin(outp));
932
933 BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::DIRTY_FRESH));
934
935 // --- 2. Flushing all caches (without erasing)
936 //
937 flush_all(/*erase=*/ false);
938
939 // CoinsMap usage should be unchanged since we didn't erase anything.
940 BOOST_CHECK_EQUAL(cache_usage, view->DynamicMemoryUsage());
941 BOOST_CHECK_EQUAL(cache_size, view->map().size());
942
943 // --- 3. Ensuring the entry still exists in the cache and has been written to parent
944 //
945 BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::CLEAN)); // State should have been wiped.
946
947 // Both views should now have the coin.
948 BOOST_CHECK(base.HaveCoin(outp));
949 BOOST_CHECK(view->HaveCoin(outp));
950
951 if (do_erasing_flush) {
952 // --- 4. Flushing the caches again (with erasing)
953 //
954 flush_all(/*erase=*/ true);
955
956 // Memory does not necessarily go down due to the map using a memory pool
957 BOOST_TEST(view->DynamicMemoryUsage() <= cache_usage);
958 // Size of the cache must go down though
959 BOOST_TEST(view->map().size() < cache_size);
960
961 // --- 5. Ensuring the entry is no longer in the cache
962 //
963 BOOST_CHECK(!GetCoinsMapEntry(view->map(), outp));
964 view->AccessCoin(outp);
965 BOOST_CHECK_EQUAL(GetCoinsMapEntry(view->map(), outp), CoinEntry(coin.out.nValue, CoinEntry::State::CLEAN));
966 }
967
968 // Can't overwrite an entry without specifying that an overwrite is
969 // expected.
971 view->AddCoin(outp, Coin(coin), /*possible_overwrite=*/ false),
972 std::logic_error);
973
974 // --- 6. Spend the coin.
975 //
976 BOOST_CHECK(view->SpendCoin(outp));
977
978 // The coin should be in the cache, but spent and marked dirty.
980 BOOST_CHECK(!view->HaveCoin(outp)); // Coin should be considered spent in `view`.
981 BOOST_CHECK(base.HaveCoin(outp)); // But coin should still be unspent in `base`.
982
983 flush_all(/*erase=*/ false);
984
985 // Coin should be considered spent in both views.
986 BOOST_CHECK(!view->HaveCoin(outp));
987 BOOST_CHECK(!base.HaveCoin(outp));
988
989 // Spent coin should not be spendable.
990 BOOST_CHECK(!view->SpendCoin(outp));
991
992 // --- Bonus check: ensure that a coin added to the base view via one cache
993 // can be spent by another cache which has never seen it.
994 //
996 outp = COutPoint(txid, 0);
997 coin = MakeCoin();
998 BOOST_CHECK(!base.HaveCoin(outp));
999 BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
1000 BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
1001
1002 all_caches[0]->AddCoin(outp, std::move(coin), false);
1003 all_caches[0]->Sync();
1004 BOOST_CHECK(base.HaveCoin(outp));
1005 BOOST_CHECK(all_caches[0]->HaveCoin(outp));
1006 BOOST_CHECK(!all_caches[1]->HaveCoinInCache(outp));
1007
1008 BOOST_CHECK(all_caches[1]->SpendCoin(outp));
1009 flush_all(/*erase=*/ false);
1010 BOOST_CHECK(!base.HaveCoin(outp));
1011 BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
1012 BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
1013
1014 flush_all(/*erase=*/ true); // Erase all cache content.
1015
1016 // --- Bonus check 2: ensure that a FRESH, spent coin is deleted by Sync()
1017 //
1019 outp = COutPoint(txid, 0);
1020 coin = MakeCoin();
1021 CAmount coin_val = coin.out.nValue;
1022 BOOST_CHECK(!base.HaveCoin(outp));
1023 BOOST_CHECK(!all_caches[0]->HaveCoin(outp));
1024 BOOST_CHECK(!all_caches[1]->HaveCoin(outp));
1025
1026 // Add and spend from same cache without flushing.
1027 all_caches[0]->AddCoin(outp, std::move(coin), false);
1028
1029 // Coin should be FRESH in the cache.
1030 BOOST_CHECK_EQUAL(GetCoinsMapEntry(all_caches[0]->map(), outp), CoinEntry(coin_val, CoinEntry::State::DIRTY_FRESH));
1031 // Base shouldn't have seen coin.
1032 BOOST_CHECK(!base.HaveCoin(outp));
1033
1034 BOOST_CHECK(all_caches[0]->SpendCoin(outp));
1035 all_caches[0]->Sync();
1036
1037 // Ensure there is no sign of the coin after spend/flush.
1038 BOOST_CHECK(!GetCoinsMapEntry(all_caches[0]->map(), outp));
1039 BOOST_CHECK(!all_caches[0]->HaveCoinInCache(outp));
1040 BOOST_CHECK(!base.HaveCoin(outp));
1041}
1042}; // struct FlushTest
1043
1044BOOST_FIXTURE_TEST_CASE(ccoins_flush_behavior, FlushTest)
1045{
1046 // Create two in-memory caches atop a leveldb view.
1047 CCoinsViewDB base{{.path = "test", .cache_bytes = 1 << 23, .memory_only = true}, {}};
1048 std::vector<std::unique_ptr<CCoinsViewCacheTest>> caches;
1049 caches.push_back(std::make_unique<CCoinsViewCacheTest>(&base));
1050 caches.push_back(std::make_unique<CCoinsViewCacheTest>(caches.back().get()));
1051
1052 for (const auto& view : caches) {
1053 TestFlushBehavior(view.get(), base, caches, /*do_erasing_flush=*/false);
1054 TestFlushBehavior(view.get(), base, caches, /*do_erasing_flush=*/true);
1055 }
1056}
1057
1058BOOST_AUTO_TEST_CASE(coins_resource_is_used)
1059{
1060 CCoinsMapMemoryResource resource;
1062
1063 {
1064 CCoinsMap map{0, CCoinsMap::hasher{}, CCoinsMap::key_equal{}, &resource};
1065 BOOST_TEST(memusage::DynamicUsage(map) >= resource.ChunkSizeBytes());
1066
1067 map.reserve(1000);
1068
1069 // The resource has preallocated a chunk, so we should have space for at several nodes without the need to allocate anything else.
1070 const auto usage_before = memusage::DynamicUsage(map);
1071
1072 COutPoint out_point{};
1073 for (size_t i = 0; i < 1000; ++i) {
1074 out_point.n = i;
1075 map[out_point];
1076 }
1077 BOOST_TEST(usage_before == memusage::DynamicUsage(map));
1078 }
1079
1081}
1082
1083BOOST_AUTO_TEST_CASE(ccoins_addcoin_exception_keeps_usage_balanced)
1084{
1085 CCoinsView root;
1086 CCoinsViewCacheTest cache{&root};
1087
1088 const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
1089
1090 const Coin coin1{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
1091 cache.AddCoin(outpoint, Coin{coin1}, /*possible_overwrite=*/false);
1092 cache.SelfTest();
1093
1094 const Coin coin2{CTxOut{m_rng.randrange(20), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 2)}, 2, false};
1095 BOOST_CHECK_THROW(cache.AddCoin(outpoint, Coin{coin2}, /*possible_overwrite=*/false), std::logic_error);
1096 cache.SelfTest();
1097
1098 BOOST_CHECK(cache.AccessCoin(outpoint) == coin1);
1099}
1100
1101BOOST_AUTO_TEST_CASE(ccoins_emplace_duplicate_keeps_usage_balanced)
1102{
1103 CCoinsView root;
1104 CCoinsViewCacheTest cache{&root};
1105
1106 const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
1107
1108 const Coin coin1{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
1109 cache.EmplaceCoinInternalDANGER(COutPoint{outpoint}, Coin{coin1});
1110 cache.SelfTest();
1111
1112 const Coin coin2{CTxOut{m_rng.randrange(20), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 2)}, 2, false};
1113 cache.EmplaceCoinInternalDANGER(COutPoint{outpoint}, Coin{coin2});
1114 cache.SelfTest();
1115
1116 BOOST_CHECK(cache.AccessCoin(outpoint) == coin1);
1117}
1118
1119BOOST_AUTO_TEST_CASE(ccoins_reset_guard)
1120{
1121 CCoinsViewTest root{m_rng};
1122 CCoinsViewCache root_cache{&root};
1123 uint256 base_best_block{m_rng.rand256()};
1124 root_cache.SetBestBlock(base_best_block);
1125 root_cache.Flush();
1126
1127 CCoinsViewCache cache{&root};
1128
1129 const COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), m_rng.rand32()};
1130
1131 const Coin coin{CTxOut{m_rng.randrange(10), CScript{} << m_rng.randbytes(CScriptBase::STATIC_SIZE + 1)}, 1, false};
1132 cache.EmplaceCoinInternalDANGER(COutPoint{outpoint}, Coin{coin});
1133
1134 uint256 cache_best_block{m_rng.rand256()};
1135 cache.SetBestBlock(cache_best_block);
1136
1137 {
1138 const auto reset_guard{cache.CreateResetGuard()};
1139 BOOST_CHECK(cache.AccessCoin(outpoint) == coin);
1140 BOOST_CHECK(!cache.AccessCoin(outpoint).IsSpent());
1141 BOOST_CHECK_EQUAL(cache.GetCacheSize(), 1);
1142 BOOST_CHECK_EQUAL(cache.GetBestBlock(), cache_best_block);
1143 BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
1144 }
1145
1146 BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
1147 BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
1148 BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
1149 BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
1150
1151 // Using a reset guard again is idempotent
1152 {
1153 const auto reset_guard{cache.CreateResetGuard()};
1154 }
1155
1156 BOOST_CHECK(cache.AccessCoin(outpoint).IsSpent());
1157 BOOST_CHECK_EQUAL(cache.GetCacheSize(), 0);
1158 BOOST_CHECK_EQUAL(cache.GetBestBlock(), base_best_block);
1159 BOOST_CHECK(!root_cache.HaveCoinInCache(outpoint));
1160}
1161
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int ret
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:355
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:297
size_t cachedCoinsUsage
Definition: coins.h:371
CoinsCachePair m_sentinel
Definition: coins.h:367
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:49
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition: coins.cpp:323
CCoinsMap cacheCoins
Definition: coins.h:368
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:35
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: txdb.cpp:77
Abstract view on the open txout dataset.
Definition: coins.h:302
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:17
virtual void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:20
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:18
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
uint32_t n
Definition: transaction.h:32
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:563
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
bool IsCoinBase() const
Definition: transaction.h:341
const std::vector< CTxIn > vin
Definition: transaction.h:291
An output of a transaction.
Definition: transaction.h:140
CScript scriptPubKey
Definition: transaction.h:143
CAmount nValue
Definition: transaction.h:142
Undo information for a CTransaction.
Definition: undo.h:53
std::vector< Coin > vprevout
Definition: undo.h:56
A UTXO entry.
Definition: coins.h:34
void Clear()
Definition: coins.h:49
CTxOut out
unspent transaction output
Definition: coins.h:37
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:82
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:43
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:40
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:130
Fast randomness source.
Definition: random.h:386
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:293
static void CheckAllDataAccountedFor(const PoolResource< MAX_BLOCK_SIZE_BYTES, ALIGN_BYTES > &resource)
Once all blocks are given back to the resource, tests that the freelists are consistent:
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
uint256 rand256() noexcept
generate a random uint256.
Definition: random.h:317
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:325
std::vector< B > randbytes(size_t len) noexcept
Generate random bytes.
Definition: random.h:297
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:314
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:204
CCoinsViewCacheTest cache
CCoinsViewCacheTest base
CCoinsView root
SingleEntryCacheTest(const CAmount base_value, const MaybeCoin &cache_coin)
constexpr bool IsNull() const
Definition: uint256.h:48
size_type size() const
Definition: prevector.h:247
static constexpr unsigned int STATIC_SIZE
Definition: prevector.h:41
void assign(size_type n, const T &val)
Definition: prevector.h:176
static transaction_identifier FromUint256(const uint256 &id)
160-bit opaque blob.
Definition: uint256.h:183
256-bit opaque blob.
Definition: uint256.h:195
static void add_coin(const CAmount &nValue, int nInput, std::vector< OutputGroup > &set)
const Coin & AccessByTxid(const CCoinsViewCache &view, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:358
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:92
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< CoinsCachePair, sizeof(CoinsCachePair)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
Definition: coins.h:223
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:225
constexpr CAmount VALUE2
BOOST_AUTO_TEST_CASE(ccoins_serialization)
constexpr MaybeCoin VALUE2_DIRTY
constexpr CAmount ABSENT
std::optional< CoinEntry > MaybeCoin
constexpr MaybeCoin VALUE2_CLEAN
constexpr MaybeCoin MISSING
static MaybeCoin GetCoinsMapEntry(const CCoinsMap &map, const COutPoint &outp=OUTPOINT)
static const COutPoint OUTPOINT
constexpr MaybeCoin VALUE2_DIRTY_FRESH
static void WriteCoinsViewEntry(CCoinsView &view, const MaybeCoin &cache_coin)
static void CheckWriteCoins(const MaybeCoin &parent, const MaybeCoin &child, const CoinOrError &expected)
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
static const unsigned int NUM_SIMULATION_ITERATIONS
constexpr MaybeCoin VALUE1_CLEAN
constexpr CAmount VALUE1
constexpr MaybeCoin SPENT_DIRTY_FRESH
constexpr MaybeCoin SPENT_CLEAN
constexpr auto EX_OVERWRITE_UNSPENT
constexpr MaybeCoin VALUE1_DIRTY
constexpr MaybeCoin VALUE1_FRESH
static size_t InsertCoinsMapEntry(CCoinsMap &map, CoinsCachePair &sentinel, const CoinEntry &cache_coin)
static void CheckSpendCoins(const CAmount base_value, const MaybeCoin &cache_coin, const MaybeCoin &expected)
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
constexpr CAmount VALUE3
constexpr MaybeCoin VALUE2_FRESH
constexpr MaybeCoin VALUE3_DIRTY_FRESH
static void CheckAccessCoin(const CAmount base_value, const MaybeCoin &cache_coin, const MaybeCoin &expected)
constexpr MaybeCoin VALUE3_DIRTY
constexpr MaybeCoin VALUE1_DIRTY_FRESH
constexpr MaybeCoin SPENT_DIRTY
constexpr auto EX_FRESH_MISAPPLIED
std::variant< MaybeCoin, std::string > CoinOrError
static void SetCoinsValue(const CAmount value, Coin &coin)
BOOST_FIXTURE_TEST_CASE(coins_cache_base_simulation_test, CacheTest)
constexpr MaybeCoin SPENT_FRESH
constexpr CAmount SPENT
static void CheckAddCoin(const CAmount base_value, const MaybeCoin &cache_coin, const CAmount modify_value, const CoinOrError &expected, const bool coinbase)
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
unsigned int nHeight
static bool sanity_check(const std::vector< CTransactionRef > &transactions, const std::map< COutPoint, CAmount > &bumpfees)
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:31
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
Definition: strencodings.h:400
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:603
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition: object.cpp:18
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#define BOOST_CHECK(expr)
Definition: object.cpp:16
@ OP_RETURN
Definition: script.h:111
#define VARINT(obj)
Definition: serialize.h:491
Basic testing setup.
Definition: setup_common.h:64
FastRandomContext m_rng
Definition: setup_common.h:68
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:109
Coin coin
Definition: coins.h:141
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:172
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:171
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::vector< CTxIn > vin
Definition: transaction.h:359
void SimulationTest(CCoinsView *base, bool fake_best_block)
const CAmount value
constexpr bool IsDirty() const
friend std::ostream & operator<<(std::ostream &os, const CoinEntry &e)
bool operator==(const CoinEntry &o) const =default
constexpr bool IsDirtyFresh() const
State
@ DIRTY
@ FRESH
@ CLEAN
@ DIRTY_FRESH
static constexpr State ToState(const bool is_dirty, const bool is_fresh)
constexpr bool IsFresh() const
const State state
constexpr CoinEntry(const CAmount v, const State s)
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:260
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:277
CoinsCachePair * Begin() const noexcept
Definition: coins.h:273
CoinsCachePair * End() const noexcept
Definition: coins.h:274
void TestFlushBehavior(CCoinsViewCacheTest *view, CCoinsViewDB &base, std::vector< std::unique_ptr< CCoinsViewCacheTest > > &all_caches, bool do_erasing_flush)
For CCoinsViewCache instances backed by either another cache instance or leveldb, test cache behavior...
Coin MakeCoin()
std::map< COutPoint, std::tuple< CTransaction, CTxUndo, Coin > > UtxoData
UtxoData::iterator FindRandomFrom(const std::set< COutPoint > &utxoSet)
UtxoData utxoData
@ ZEROS
Seed with a compile time constant of zeros.
CAmount RandMoney(Rng &&rng)
Definition: random.h:35
static int count
assert(!tx.IsCoinBase())