repo_id
stringlengths
0
42
file_path
stringlengths
15
97
content
stringlengths
2
2.41M
__index_level_0__
int64
0
0
bitcoin/src
bitcoin/src/test/flatfile_tests.cpp
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <common/args.h> #include <flatfile.h> #include <streams.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(flatfile_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(flatfile_filename) { const auto data_dir = m_args.GetDataDirBase(); FlatFilePos pos(456, 789); FlatFileSeq seq1(data_dir, "a", 16 * 1024); BOOST_CHECK_EQUAL(seq1.FileName(pos), data_dir / "a00456.dat"); FlatFileSeq seq2(data_dir / "a", "b", 16 * 1024); BOOST_CHECK_EQUAL(seq2.FileName(pos), data_dir / "a" / "b00456.dat"); // Check default constructor IsNull assert(FlatFilePos{}.IsNull()); } BOOST_AUTO_TEST_CASE(flatfile_open) { const auto data_dir = m_args.GetDataDirBase(); FlatFileSeq seq(data_dir, "a", 16 * 1024); std::string line1("A purely peer-to-peer version of electronic cash would allow online " "payments to be sent directly from one party to another without going " "through a financial institution."); std::string line2("Digital signatures provide part of the solution, but the main benefits are " "lost if a trusted third party is still required to prevent double-spending."); size_t pos1 = 0; size_t pos2 = pos1 + GetSerializeSize(line1); // Write first line to file. { AutoFile file{seq.Open(FlatFilePos(0, pos1))}; file << LIMITED_STRING(line1, 256); } // Attempt to append to file opened in read-only mode. { AutoFile file{seq.Open(FlatFilePos(0, pos2), true)}; BOOST_CHECK_THROW(file << LIMITED_STRING(line2, 256), std::ios_base::failure); } // Append second line to file. { AutoFile file{seq.Open(FlatFilePos(0, pos2))}; file << LIMITED_STRING(line2, 256); } // Read text from file in read-only mode. { std::string text; AutoFile file{seq.Open(FlatFilePos(0, pos1), true)}; file >> LIMITED_STRING(text, 256); BOOST_CHECK_EQUAL(text, line1); file >> LIMITED_STRING(text, 256); BOOST_CHECK_EQUAL(text, line2); } // Read text from file with position offset. { std::string text; AutoFile file{seq.Open(FlatFilePos(0, pos2))}; file >> LIMITED_STRING(text, 256); BOOST_CHECK_EQUAL(text, line2); } // Ensure another file in the sequence has no data. { std::string text; AutoFile file{seq.Open(FlatFilePos(1, pos2))}; BOOST_CHECK_THROW(file >> LIMITED_STRING(text, 256), std::ios_base::failure); } } BOOST_AUTO_TEST_CASE(flatfile_allocate) { const auto data_dir = m_args.GetDataDirBase(); FlatFileSeq seq(data_dir, "a", 100); bool out_of_space; BOOST_CHECK_EQUAL(seq.Allocate(FlatFilePos(0, 0), 1, out_of_space), 100U); BOOST_CHECK_EQUAL(fs::file_size(seq.FileName(FlatFilePos(0, 0))), 100U); BOOST_CHECK(!out_of_space); BOOST_CHECK_EQUAL(seq.Allocate(FlatFilePos(0, 99), 1, out_of_space), 0U); BOOST_CHECK_EQUAL(fs::file_size(seq.FileName(FlatFilePos(0, 99))), 100U); BOOST_CHECK(!out_of_space); BOOST_CHECK_EQUAL(seq.Allocate(FlatFilePos(0, 99), 2, out_of_space), 101U); BOOST_CHECK_EQUAL(fs::file_size(seq.FileName(FlatFilePos(0, 99))), 200U); BOOST_CHECK(!out_of_space); } BOOST_AUTO_TEST_CASE(flatfile_flush) { const auto data_dir = m_args.GetDataDirBase(); FlatFileSeq seq(data_dir, "a", 100); bool out_of_space; seq.Allocate(FlatFilePos(0, 0), 1, out_of_space); // Flush without finalize should not truncate file. seq.Flush(FlatFilePos(0, 1)); BOOST_CHECK_EQUAL(fs::file_size(seq.FileName(FlatFilePos(0, 1))), 100U); // Flush with finalize should truncate file. seq.Flush(FlatFilePos(0, 1), true); BOOST_CHECK_EQUAL(fs::file_size(seq.FileName(FlatFilePos(0, 1))), 1U); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/txvalidation_tests.cpp
// Copyright (c) 2017-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include <key_io.h> #include <policy/packages.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <script/script.h> #include <test/util/setup_common.h> #include <validation.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(txvalidation_tests) /** * Ensure that the mempool won't accept coinbase transactions. */ BOOST_FIXTURE_TEST_CASE(tx_mempool_reject_coinbase, TestChain100Setup) { CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; CMutableTransaction coinbaseTx; coinbaseTx.nVersion = 1; coinbaseTx.vin.resize(1); coinbaseTx.vout.resize(1); coinbaseTx.vin[0].scriptSig = CScript() << OP_11 << OP_EQUAL; coinbaseTx.vout[0].nValue = 1 * CENT; coinbaseTx.vout[0].scriptPubKey = scriptPubKey; BOOST_CHECK(CTransaction(coinbaseTx).IsCoinBase()); LOCK(cs_main); unsigned int initialPoolSize = m_node.mempool->size(); const MempoolAcceptResult result = m_node.chainman->ProcessTransaction(MakeTransactionRef(coinbaseTx)); BOOST_CHECK(result.m_result_type == MempoolAcceptResult::ResultType::INVALID); // Check that the transaction hasn't been added to mempool. BOOST_CHECK_EQUAL(m_node.mempool->size(), initialPoolSize); // Check that the validation state reflects the unsuccessful attempt. BOOST_CHECK(result.m_state.IsInvalid()); BOOST_CHECK_EQUAL(result.m_state.GetRejectReason(), "coinbase"); BOOST_CHECK(result.m_state.GetResult() == TxValidationResult::TX_CONSENSUS); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/cuckoocache_tests.cpp
// Copyright (c) 2012-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <cuckoocache.h> #include <random.h> #include <script/sigcache.h> #include <test/util/random.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> #include <deque> #include <mutex> #include <shared_mutex> #include <thread> #include <vector> /** Test Suite for CuckooCache * * 1. All tests should have a deterministic result (using insecure rand * with deterministic seeds) * 2. Some test methods are templated to allow for easier testing * against new versions / comparing * 3. Results should be treated as a regression test, i.e., did the behavior * change significantly from what was expected. This can be OK, depending on * the nature of the change, but requires updating the tests to reflect the new * expected behavior. For example improving the hit rate may cause some tests * using BOOST_CHECK_CLOSE to fail. * */ BOOST_AUTO_TEST_SUITE(cuckoocache_tests); /* Test that no values not inserted into the cache are read out of it. * * There are no repeats in the first 200000 insecure_GetRandHash calls */ BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes) { SeedInsecureRand(SeedRand::ZEROS); CuckooCache::cache<uint256, SignatureCacheHasher> cc{}; size_t megabytes = 4; cc.setup_bytes(megabytes << 20); for (int x = 0; x < 100000; ++x) { cc.insert(InsecureRand256()); } for (int x = 0; x < 100000; ++x) { BOOST_CHECK(!cc.contains(InsecureRand256(), false)); } }; /** This helper returns the hit rate when megabytes*load worth of entries are * inserted into a megabytes sized cache */ template <typename Cache> static double test_cache(size_t megabytes, double load) { SeedInsecureRand(SeedRand::ZEROS); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = InsecureRand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; /** Do the insert */ for (const uint256& h : hashes_insert_copy) set.insert(h); /** Count the hits */ uint32_t count = 0; for (const uint256& h : hashes) count += set.contains(h, false); double hit_rate = ((double)count) / ((double)n_insert); return hit_rate; } /** The normalized hit rate for a given load. * * The semantics are a little confusing, so please see the below * explanation. * * Examples: * * 1. at load 0.5, we expect a perfect hit rate, so we multiply by * 1.0 * 2. at load 2.0, we expect to see half the entries, so a perfect hit rate * would be 0.5. Therefore, if we see a hit rate of 0.4, 0.4*2.0 = 0.8 is the * normalized hit rate. * * This is basically the right semantics, but has a bit of a glitch depending on * how you measure around load 1.0 as after load 1.0 your normalized hit rate * becomes effectively perfect, ignoring freshness. */ static double normalize_hit_rate(double hits, double load) { return hits * std::max(load, 1.0); } /** Check the hit rate on loads ranging from 0.1 to 1.6 */ BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok) { /** Arbitrarily selected Hit Rate threshold that happens to work for this test * as a lower bound on performance. */ double HitRateThresh = 0.98; size_t megabytes = 4; for (double load = 0.1; load < 2; load *= 2) { double hits = test_cache<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes, load); BOOST_CHECK(normalize_hit_rate(hits, load) > HitRateThresh); } } /** This helper checks that erased elements are preferentially inserted onto and * that the hit rate of "fresher" keys is reasonable*/ template <typename Cache> static void test_cache_erase(size_t megabytes) { double load = 1; SeedInsecureRand(SeedRand::ZEROS); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = InsecureRand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; /** Insert the first half */ for (uint32_t i = 0; i < (n_insert / 2); ++i) set.insert(hashes_insert_copy[i]); /** Erase the first quarter */ for (uint32_t i = 0; i < (n_insert / 4); ++i) BOOST_CHECK(set.contains(hashes[i], true)); /** Insert the second half */ for (uint32_t i = (n_insert / 2); i < n_insert; ++i) set.insert(hashes_insert_copy[i]); /** elements that we marked as erased but are still there */ size_t count_erased_but_contained = 0; /** elements that we did not erase but are older */ size_t count_stale = 0; /** elements that were most recently inserted */ size_t count_fresh = 0; for (uint32_t i = 0; i < (n_insert / 4); ++i) count_erased_but_contained += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i) count_stale += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 2); i < n_insert; ++i) count_fresh += set.contains(hashes[i], false); double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0); double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0); double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0); // Check that our hit_rate_fresh is perfect BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0); // Check that we have a more than 2x better hit rate on stale elements than // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } BOOST_AUTO_TEST_CASE(cuckoocache_erase_ok) { size_t megabytes = 4; test_cache_erase<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes); } template <typename Cache> static void test_cache_erase_parallel(size_t megabytes) { double load = 1; SeedInsecureRand(SeedRand::ZEROS); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = InsecureRand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; std::shared_mutex mtx; { /** Grab lock to make sure we release inserts */ std::unique_lock<std::shared_mutex> l(mtx); /** Insert the first half */ for (uint32_t i = 0; i < (n_insert / 2); ++i) set.insert(hashes_insert_copy[i]); } /** Spin up 3 threads to run contains with erase. */ std::vector<std::thread> threads; /** Erase the first quarter */ for (uint32_t x = 0; x < 3; ++x) /** Each thread is emplaced with x copy-by-value */ threads.emplace_back([&, x] { std::shared_lock<std::shared_mutex> l(mtx); size_t ntodo = (n_insert/4)/3; size_t start = ntodo*x; size_t end = ntodo*(x+1); for (uint32_t i = start; i < end; ++i) { bool contains = set.contains(hashes[i], true); assert(contains); } }); /** Wait for all threads to finish */ for (std::thread& t : threads) t.join(); /** Grab lock to make sure we observe erases */ std::unique_lock<std::shared_mutex> l(mtx); /** Insert the second half */ for (uint32_t i = (n_insert / 2); i < n_insert; ++i) set.insert(hashes_insert_copy[i]); /** elements that we marked erased but that are still there */ size_t count_erased_but_contained = 0; /** elements that we did not erase but are older */ size_t count_stale = 0; /** elements that were most recently inserted */ size_t count_fresh = 0; for (uint32_t i = 0; i < (n_insert / 4); ++i) count_erased_but_contained += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i) count_stale += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 2); i < n_insert; ++i) count_fresh += set.contains(hashes[i], false); double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0); double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0); double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0); // Check that our hit_rate_fresh is perfect BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0); // Check that we have a more than 2x better hit rate on stale elements than // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } BOOST_AUTO_TEST_CASE(cuckoocache_erase_parallel_ok) { size_t megabytes = 4; test_cache_erase_parallel<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes); } template <typename Cache> static void test_cache_generations() { // This test checks that for a simulation of network activity, the fresh hit // rate is never below 99%, and the number of times that it is worse than // 99.9% are less than 1% of the time. double min_hit_rate = 0.99; double tight_hit_rate = 0.999; double max_rate_less_than_tight_hit_rate = 0.01; // A cache that meets this specification is therefore shown to have a hit // rate of at least tight_hit_rate * (1 - max_rate_less_than_tight_hit_rate) + // min_hit_rate*max_rate_less_than_tight_hit_rate = 0.999*99%+0.99*1% == 99.89% // hit rate with low variance. // We use deterministic values, but this test has also passed on many // iterations with non-deterministic values, so it isn't "overfit" to the // specific entropy in FastRandomContext(true) and implementation of the // cache. SeedInsecureRand(SeedRand::ZEROS); // block_activity models a chunk of network activity. n_insert elements are // added to the cache. The first and last n/4 are stored for removal later // and the middle n/2 are not stored. This models a network which uses half // the signatures of recently (since the last block) added transactions // immediately and never uses the other half. struct block_activity { std::vector<uint256> reads; block_activity(uint32_t n_insert, Cache& c) : reads() { std::vector<uint256> inserts; inserts.resize(n_insert); reads.reserve(n_insert / 2); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)inserts[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = InsecureRand32(); } for (uint32_t i = 0; i < n_insert / 4; ++i) reads.push_back(inserts[i]); for (uint32_t i = n_insert - (n_insert / 4); i < n_insert; ++i) reads.push_back(inserts[i]); for (const auto& h : inserts) c.insert(h); } }; const uint32_t BLOCK_SIZE = 1000; // We expect window size 60 to perform reasonably given that each epoch // stores 45% of the cache size (~472k). const uint32_t WINDOW_SIZE = 60; const uint32_t POP_AMOUNT = (BLOCK_SIZE / WINDOW_SIZE) / 2; const double load = 10; const size_t megabytes = 4; const size_t bytes = megabytes * (1 << 20); const uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); std::vector<block_activity> hashes; Cache set{}; set.setup_bytes(bytes); hashes.reserve(n_insert / BLOCK_SIZE); std::deque<block_activity> last_few; uint32_t out_of_tight_tolerance = 0; uint32_t total = n_insert / BLOCK_SIZE; // we use the deque last_few to model a sliding window of blocks. at each // step, each of the last WINDOW_SIZE block_activities checks the cache for // POP_AMOUNT of the hashes that they inserted, and marks these erased. for (uint32_t i = 0; i < total; ++i) { if (last_few.size() == WINDOW_SIZE) last_few.pop_front(); last_few.emplace_back(BLOCK_SIZE, set); uint32_t count = 0; for (auto& act : last_few) for (uint32_t k = 0; k < POP_AMOUNT; ++k) { count += set.contains(act.reads.back(), true); act.reads.pop_back(); } // We use last_few.size() rather than WINDOW_SIZE for the correct // behavior on the first WINDOW_SIZE iterations where the deque is not // full yet. double hit = (double(count)) / (last_few.size() * POP_AMOUNT); // Loose Check that hit rate is above min_hit_rate BOOST_CHECK(hit > min_hit_rate); // Tighter check, count number of times we are less than tight_hit_rate // (and implicitly, greater than min_hit_rate) out_of_tight_tolerance += hit < tight_hit_rate; } // Check that being out of tolerance happens less than // max_rate_less_than_tight_hit_rate of the time BOOST_CHECK(double(out_of_tight_tolerance) / double(total) < max_rate_less_than_tight_hit_rate); } BOOST_AUTO_TEST_CASE(cuckoocache_generations) { test_cache_generations<CuckooCache::cache<uint256, SignatureCacheHasher>>(); } BOOST_AUTO_TEST_SUITE_END();
0
bitcoin/src
bitcoin/src/test/reverselock_tests.cpp
// Copyright (c) 2015-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sync.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> #include <stdexcept> BOOST_AUTO_TEST_SUITE(reverselock_tests) BOOST_AUTO_TEST_CASE(reverselock_basics) { Mutex mutex; WAIT_LOCK(mutex, lock); BOOST_CHECK(lock.owns_lock()); { REVERSE_LOCK(lock); BOOST_CHECK(!lock.owns_lock()); } BOOST_CHECK(lock.owns_lock()); } BOOST_AUTO_TEST_CASE(reverselock_multiple) { Mutex mutex2; Mutex mutex; WAIT_LOCK(mutex2, lock2); WAIT_LOCK(mutex, lock); // Make sure undoing two locks succeeds { REVERSE_LOCK(lock); BOOST_CHECK(!lock.owns_lock()); REVERSE_LOCK(lock2); BOOST_CHECK(!lock2.owns_lock()); } BOOST_CHECK(lock.owns_lock()); BOOST_CHECK(lock2.owns_lock()); } BOOST_AUTO_TEST_CASE(reverselock_errors) { Mutex mutex2; Mutex mutex; WAIT_LOCK(mutex2, lock2); WAIT_LOCK(mutex, lock); #ifdef DEBUG_LOCKORDER bool prev = g_debug_lockorder_abort; g_debug_lockorder_abort = false; // Make sure trying to reverse lock a previous lock fails BOOST_CHECK_EXCEPTION(REVERSE_LOCK(lock2), std::logic_error, HasReason("lock2 was not most recent critical section locked")); BOOST_CHECK(lock2.owns_lock()); g_debug_lockorder_abort = prev; #endif // Make sure trying to reverse lock an unlocked lock fails lock.unlock(); BOOST_CHECK(!lock.owns_lock()); bool failed = false; try { REVERSE_LOCK(lock); } catch(...) { failed = true; } BOOST_CHECK(failed); BOOST_CHECK(!lock.owns_lock()); // Locking the original lock after it has been taken by a reverse lock // makes no sense. Ensure that the original lock no longer owns the lock // after giving it to a reverse one. lock.lock(); BOOST_CHECK(lock.owns_lock()); { REVERSE_LOCK(lock); BOOST_CHECK(!lock.owns_lock()); } BOOST_CHECK(failed); BOOST_CHECK(lock.owns_lock()); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/blockencodings_tests.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <blockencodings.h> #include <chainparams.h> #include <consensus/merkle.h> #include <pow.h> #include <streams.h> #include <test/util/random.h> #include <test/util/txmempool.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> std::vector<std::pair<uint256, CTransactionRef>> extra_txn; BOOST_FIXTURE_TEST_SUITE(blockencodings_tests, RegTestingSetup) static CBlock BuildBlockTestCase() { CBlock block; CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].scriptSig.resize(10); tx.vout.resize(1); tx.vout[0].nValue = 42; block.vtx.resize(3); block.vtx[0] = MakeTransactionRef(tx); block.nVersion = 42; block.hashPrevBlock = InsecureRand256(); block.nBits = 0x207fffff; tx.vin[0].prevout.hash = Txid::FromUint256(InsecureRand256()); tx.vin[0].prevout.n = 0; block.vtx[1] = MakeTransactionRef(tx); tx.vin.resize(10); for (size_t i = 0; i < tx.vin.size(); i++) { tx.vin[i].prevout.hash = Txid::FromUint256(InsecureRand256()); tx.vin[i].prevout.n = 0; } block.vtx[2] = MakeTransactionRef(tx); bool mutated; block.hashMerkleRoot = BlockMerkleRoot(block, &mutated); assert(!mutated); while (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) ++block.nNonce; return block; } // Number of shared use_counts we expect for a tx we haven't touched // (block + mempool entry + mempool txns_randomized + our copy from the GetSharedTx call) constexpr long SHARED_TX_OFFSET{4}; BOOST_AUTO_TEST_CASE(SimpleRoundTripTest) { CTxMemPool& pool = *Assert(m_node.mempool); TestMemPoolEntryHelper entry; CBlock block(BuildBlockTestCase()); LOCK2(cs_main, pool.cs); pool.addUnchecked(entry.FromTx(block.vtx[2])); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 0); // Do a simple ShortTxIDs RT { CBlockHeaderAndShortTxIDs shortIDs{block}; DataStream stream{}; stream << shortIDs; CBlockHeaderAndShortTxIDs shortIDs2; stream >> shortIDs2; PartiallyDownloadedBlock partialBlock(&pool); BOOST_CHECK(partialBlock.InitData(shortIDs2, extra_txn) == READ_STATUS_OK); BOOST_CHECK( partialBlock.IsTxAvailable(0)); BOOST_CHECK(!partialBlock.IsTxAvailable(1)); BOOST_CHECK( partialBlock.IsTxAvailable(2)); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 1); size_t poolSize = pool.size(); pool.removeRecursive(*block.vtx[2], MemPoolRemovalReason::REPLACED); BOOST_CHECK_EQUAL(pool.size(), poolSize - 1); CBlock block2; { PartiallyDownloadedBlock tmp = partialBlock; BOOST_CHECK(partialBlock.FillBlock(block2, {}) == READ_STATUS_INVALID); // No transactions partialBlock = tmp; } // Wrong transaction { PartiallyDownloadedBlock tmp = partialBlock; partialBlock.FillBlock(block2, {block.vtx[2]}); // Current implementation doesn't check txn here, but don't require that partialBlock = tmp; } bool mutated; BOOST_CHECK(block.hashMerkleRoot != BlockMerkleRoot(block2, &mutated)); CBlock block3; BOOST_CHECK(partialBlock.FillBlock(block3, {block.vtx[1]}) == READ_STATUS_OK); BOOST_CHECK_EQUAL(block.GetHash().ToString(), block3.GetHash().ToString()); BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block3, &mutated).ToString()); BOOST_CHECK(!mutated); } } class TestHeaderAndShortIDs { // Utility to encode custom CBlockHeaderAndShortTxIDs public: CBlockHeader header; uint64_t nonce; std::vector<uint64_t> shorttxids; std::vector<PrefilledTransaction> prefilledtxn; explicit TestHeaderAndShortIDs(const CBlockHeaderAndShortTxIDs& orig) { DataStream stream{}; stream << orig; stream >> *this; } explicit TestHeaderAndShortIDs(const CBlock& block) : TestHeaderAndShortIDs(CBlockHeaderAndShortTxIDs{block}) {} uint64_t GetShortID(const uint256& txhash) const { DataStream stream{}; stream << *this; CBlockHeaderAndShortTxIDs base; stream >> base; return base.GetShortID(txhash); } SERIALIZE_METHODS(TestHeaderAndShortIDs, obj) { READWRITE(obj.header, obj.nonce, Using<VectorFormatter<CustomUintFormatter<CBlockHeaderAndShortTxIDs::SHORTTXIDS_LENGTH>>>(obj.shorttxids), obj.prefilledtxn); } }; BOOST_AUTO_TEST_CASE(NonCoinbasePreforwardRTTest) { CTxMemPool& pool = *Assert(m_node.mempool); TestMemPoolEntryHelper entry; CBlock block(BuildBlockTestCase()); LOCK2(cs_main, pool.cs); pool.addUnchecked(entry.FromTx(block.vtx[2])); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 0); uint256 txhash; // Test with pre-forwarding tx 1, but not coinbase { TestHeaderAndShortIDs shortIDs(block); shortIDs.prefilledtxn.resize(1); shortIDs.prefilledtxn[0] = {1, block.vtx[1]}; shortIDs.shorttxids.resize(2); shortIDs.shorttxids[0] = shortIDs.GetShortID(block.vtx[0]->GetHash()); shortIDs.shorttxids[1] = shortIDs.GetShortID(block.vtx[2]->GetHash()); DataStream stream{}; stream << shortIDs; CBlockHeaderAndShortTxIDs shortIDs2; stream >> shortIDs2; PartiallyDownloadedBlock partialBlock(&pool); BOOST_CHECK(partialBlock.InitData(shortIDs2, extra_txn) == READ_STATUS_OK); BOOST_CHECK(!partialBlock.IsTxAvailable(0)); BOOST_CHECK( partialBlock.IsTxAvailable(1)); BOOST_CHECK( partialBlock.IsTxAvailable(2)); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 1); // +1 because of partialBlock CBlock block2; { PartiallyDownloadedBlock tmp = partialBlock; BOOST_CHECK(partialBlock.FillBlock(block2, {}) == READ_STATUS_INVALID); // No transactions partialBlock = tmp; } // Wrong transaction { PartiallyDownloadedBlock tmp = partialBlock; partialBlock.FillBlock(block2, {block.vtx[1]}); // Current implementation doesn't check txn here, but don't require that partialBlock = tmp; } BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 2); // +2 because of partialBlock and block2 bool mutated; BOOST_CHECK(block.hashMerkleRoot != BlockMerkleRoot(block2, &mutated)); CBlock block3; PartiallyDownloadedBlock partialBlockCopy = partialBlock; BOOST_CHECK(partialBlock.FillBlock(block3, {block.vtx[0]}) == READ_STATUS_OK); BOOST_CHECK_EQUAL(block.GetHash().ToString(), block3.GetHash().ToString()); BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block3, &mutated).ToString()); BOOST_CHECK(!mutated); BOOST_CHECK_EQUAL(pool.get(block.vtx[2]->GetHash()).use_count(), SHARED_TX_OFFSET + 3); // +2 because of partialBlock and block2 and block3 txhash = block.vtx[2]->GetHash(); block.vtx.clear(); block2.vtx.clear(); block3.vtx.clear(); BOOST_CHECK_EQUAL(pool.get(txhash).use_count(), SHARED_TX_OFFSET + 1 - 1); // + 1 because of partialBlock; -1 because of block. } BOOST_CHECK_EQUAL(pool.get(txhash).use_count(), SHARED_TX_OFFSET - 1); // -1 because of block } BOOST_AUTO_TEST_CASE(SufficientPreforwardRTTest) { CTxMemPool& pool = *Assert(m_node.mempool); TestMemPoolEntryHelper entry; CBlock block(BuildBlockTestCase()); LOCK2(cs_main, pool.cs); pool.addUnchecked(entry.FromTx(block.vtx[1])); BOOST_CHECK_EQUAL(pool.get(block.vtx[1]->GetHash()).use_count(), SHARED_TX_OFFSET + 0); uint256 txhash; // Test with pre-forwarding coinbase + tx 2 with tx 1 in mempool { TestHeaderAndShortIDs shortIDs(block); shortIDs.prefilledtxn.resize(2); shortIDs.prefilledtxn[0] = {0, block.vtx[0]}; shortIDs.prefilledtxn[1] = {1, block.vtx[2]}; // id == 1 as it is 1 after index 1 shortIDs.shorttxids.resize(1); shortIDs.shorttxids[0] = shortIDs.GetShortID(block.vtx[1]->GetHash()); DataStream stream{}; stream << shortIDs; CBlockHeaderAndShortTxIDs shortIDs2; stream >> shortIDs2; PartiallyDownloadedBlock partialBlock(&pool); BOOST_CHECK(partialBlock.InitData(shortIDs2, extra_txn) == READ_STATUS_OK); BOOST_CHECK( partialBlock.IsTxAvailable(0)); BOOST_CHECK( partialBlock.IsTxAvailable(1)); BOOST_CHECK( partialBlock.IsTxAvailable(2)); BOOST_CHECK_EQUAL(pool.get(block.vtx[1]->GetHash()).use_count(), SHARED_TX_OFFSET + 1); CBlock block2; PartiallyDownloadedBlock partialBlockCopy = partialBlock; BOOST_CHECK(partialBlock.FillBlock(block2, {}) == READ_STATUS_OK); BOOST_CHECK_EQUAL(block.GetHash().ToString(), block2.GetHash().ToString()); bool mutated; BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block2, &mutated).ToString()); BOOST_CHECK(!mutated); txhash = block.vtx[1]->GetHash(); block.vtx.clear(); block2.vtx.clear(); BOOST_CHECK_EQUAL(pool.get(txhash).use_count(), SHARED_TX_OFFSET + 1 - 1); // + 1 because of partialBlock; -1 because of block. } BOOST_CHECK_EQUAL(pool.get(txhash).use_count(), SHARED_TX_OFFSET - 1); // -1 because of block } BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest) { CTxMemPool& pool = *Assert(m_node.mempool); CMutableTransaction coinbase; coinbase.vin.resize(1); coinbase.vin[0].scriptSig.resize(10); coinbase.vout.resize(1); coinbase.vout[0].nValue = 42; CBlock block; block.vtx.resize(1); block.vtx[0] = MakeTransactionRef(std::move(coinbase)); block.nVersion = 42; block.hashPrevBlock = InsecureRand256(); block.nBits = 0x207fffff; bool mutated; block.hashMerkleRoot = BlockMerkleRoot(block, &mutated); assert(!mutated); while (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) ++block.nNonce; // Test simple header round-trip with only coinbase { CBlockHeaderAndShortTxIDs shortIDs{block}; DataStream stream{}; stream << shortIDs; CBlockHeaderAndShortTxIDs shortIDs2; stream >> shortIDs2; PartiallyDownloadedBlock partialBlock(&pool); BOOST_CHECK(partialBlock.InitData(shortIDs2, extra_txn) == READ_STATUS_OK); BOOST_CHECK(partialBlock.IsTxAvailable(0)); CBlock block2; std::vector<CTransactionRef> vtx_missing; BOOST_CHECK(partialBlock.FillBlock(block2, vtx_missing) == READ_STATUS_OK); BOOST_CHECK_EQUAL(block.GetHash().ToString(), block2.GetHash().ToString()); BOOST_CHECK_EQUAL(block.hashMerkleRoot.ToString(), BlockMerkleRoot(block2, &mutated).ToString()); BOOST_CHECK(!mutated); } } BOOST_AUTO_TEST_CASE(TransactionsRequestSerializationTest) { BlockTransactionsRequest req1; req1.blockhash = InsecureRand256(); req1.indexes.resize(4); req1.indexes[0] = 0; req1.indexes[1] = 1; req1.indexes[2] = 3; req1.indexes[3] = 4; DataStream stream{}; stream << req1; BlockTransactionsRequest req2; stream >> req2; BOOST_CHECK_EQUAL(req1.blockhash.ToString(), req2.blockhash.ToString()); BOOST_CHECK_EQUAL(req1.indexes.size(), req2.indexes.size()); BOOST_CHECK_EQUAL(req1.indexes[0], req2.indexes[0]); BOOST_CHECK_EQUAL(req1.indexes[1], req2.indexes[1]); BOOST_CHECK_EQUAL(req1.indexes[2], req2.indexes[2]); BOOST_CHECK_EQUAL(req1.indexes[3], req2.indexes[3]); } BOOST_AUTO_TEST_CASE(TransactionsRequestDeserializationMaxTest) { // Check that the highest legal index is decoded correctly BlockTransactionsRequest req0; req0.blockhash = InsecureRand256(); req0.indexes.resize(1); req0.indexes[0] = 0xffff; DataStream stream{}; stream << req0; BlockTransactionsRequest req1; stream >> req1; BOOST_CHECK_EQUAL(req0.indexes.size(), req1.indexes.size()); BOOST_CHECK_EQUAL(req0.indexes[0], req1.indexes[0]); } BOOST_AUTO_TEST_CASE(TransactionsRequestDeserializationOverflowTest) { // Any set of index deltas that starts with N values that sum to (0x10000 - N) // causes the edge-case overflow that was originally not checked for. Such // a request cannot be created by serializing a real BlockTransactionsRequest // due to the overflow, so here we'll serialize from raw deltas. BlockTransactionsRequest req0; req0.blockhash = InsecureRand256(); req0.indexes.resize(3); req0.indexes[0] = 0x7000; req0.indexes[1] = 0x10000 - 0x7000 - 2; req0.indexes[2] = 0; DataStream stream{}; stream << req0.blockhash; WriteCompactSize(stream, req0.indexes.size()); WriteCompactSize(stream, req0.indexes[0]); WriteCompactSize(stream, req0.indexes[1]); WriteCompactSize(stream, req0.indexes[2]); BlockTransactionsRequest req1; try { stream >> req1; // before patch: deserialize above succeeds and this check fails, demonstrating the overflow BOOST_CHECK(req1.indexes[1] < req1.indexes[2]); // this shouldn't be reachable before or after patch BOOST_CHECK(0); } catch(std::ios_base::failure &) { // deserialize should fail BOOST_CHECK(true); // Needed to suppress "Test case [...] did not check any assertions" } } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/bip324_tests.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bip324.h> #include <chainparams.h> #include <key.h> #include <pubkey.h> #include <span.h> #include <test/util/random.h> #include <test/util/setup_common.h> #include <util/strencodings.h> #include <array> #include <cstddef> #include <cstdint> #include <vector> #include <boost/test/unit_test.hpp> namespace { void TestBIP324PacketVector( uint32_t in_idx, const std::string& in_priv_ours_hex, const std::string& in_ellswift_ours_hex, const std::string& in_ellswift_theirs_hex, bool in_initiating, const std::string& in_contents_hex, uint32_t in_multiply, const std::string& in_aad_hex, bool in_ignore, const std::string& mid_send_garbage_hex, const std::string& mid_recv_garbage_hex, const std::string& out_session_id_hex, const std::string& out_ciphertext_hex, const std::string& out_ciphertext_endswith_hex) { // Convert input from hex to char/byte vectors/arrays. const auto in_priv_ours = ParseHex(in_priv_ours_hex); const auto in_ellswift_ours = ParseHex<std::byte>(in_ellswift_ours_hex); const auto in_ellswift_theirs = ParseHex<std::byte>(in_ellswift_theirs_hex); const auto in_contents = ParseHex<std::byte>(in_contents_hex); const auto in_aad = ParseHex<std::byte>(in_aad_hex); const auto mid_send_garbage = ParseHex<std::byte>(mid_send_garbage_hex); const auto mid_recv_garbage = ParseHex<std::byte>(mid_recv_garbage_hex); const auto out_session_id = ParseHex<std::byte>(out_session_id_hex); const auto out_ciphertext = ParseHex<std::byte>(out_ciphertext_hex); const auto out_ciphertext_endswith = ParseHex<std::byte>(out_ciphertext_endswith_hex); // Load keys CKey key; key.Set(in_priv_ours.begin(), in_priv_ours.end(), true); EllSwiftPubKey ellswift_ours(in_ellswift_ours); EllSwiftPubKey ellswift_theirs(in_ellswift_theirs); // Instantiate encryption BIP324 cipher. BIP324Cipher cipher(key, ellswift_ours); BOOST_CHECK(!cipher); BOOST_CHECK(cipher.GetOurPubKey() == ellswift_ours); cipher.Initialize(ellswift_theirs, in_initiating); BOOST_CHECK(cipher); // Compare session variables. BOOST_CHECK(Span{out_session_id} == cipher.GetSessionID()); BOOST_CHECK(Span{mid_send_garbage} == cipher.GetSendGarbageTerminator()); BOOST_CHECK(Span{mid_recv_garbage} == cipher.GetReceiveGarbageTerminator()); // Vector of encrypted empty messages, encrypted in order to seek to the right position. std::vector<std::vector<std::byte>> dummies(in_idx); // Seek to the numbered packet. for (uint32_t i = 0; i < in_idx; ++i) { dummies[i].resize(cipher.EXPANSION); cipher.Encrypt({}, {}, true, dummies[i]); } // Construct contents and encrypt it. std::vector<std::byte> contents; for (uint32_t i = 0; i < in_multiply; ++i) { contents.insert(contents.end(), in_contents.begin(), in_contents.end()); } std::vector<std::byte> ciphertext(contents.size() + cipher.EXPANSION); cipher.Encrypt(contents, in_aad, in_ignore, ciphertext); // Verify ciphertext. Note that the test vectors specify either out_ciphertext (for short // messages) or out_ciphertext_endswith (for long messages), so only check the relevant one. if (!out_ciphertext.empty()) { BOOST_CHECK(out_ciphertext == ciphertext); } else { BOOST_CHECK(ciphertext.size() >= out_ciphertext_endswith.size()); BOOST_CHECK(Span{out_ciphertext_endswith} == Span{ciphertext}.last(out_ciphertext_endswith.size())); } for (unsigned error = 0; error <= 12; ++error) { // error selects a type of error introduced: // - error=0: no errors, decryption should be successful // - error=1: wrong side // - error=2..9: bit error in ciphertext // - error=10: bit error in aad // - error=11: extra 0x00 at end of aad // - error=12: message index wrong // Instantiate self-decrypting BIP324 cipher. BIP324Cipher dec_cipher(key, ellswift_ours); BOOST_CHECK(!dec_cipher); BOOST_CHECK(dec_cipher.GetOurPubKey() == ellswift_ours); dec_cipher.Initialize(ellswift_theirs, (error == 1) ^ in_initiating, /*self_decrypt=*/true); BOOST_CHECK(dec_cipher); // Compare session variables. BOOST_CHECK((Span{out_session_id} == dec_cipher.GetSessionID()) == (error != 1)); BOOST_CHECK((Span{mid_send_garbage} == dec_cipher.GetSendGarbageTerminator()) == (error != 1)); BOOST_CHECK((Span{mid_recv_garbage} == dec_cipher.GetReceiveGarbageTerminator()) == (error != 1)); // Seek to the numbered packet. if (in_idx == 0 && error == 12) continue; uint32_t dec_idx = in_idx ^ (error == 12 ? (1U << InsecureRandRange(16)) : 0); for (uint32_t i = 0; i < dec_idx; ++i) { unsigned use_idx = i < in_idx ? i : 0; bool dec_ignore{false}; dec_cipher.DecryptLength(Span{dummies[use_idx]}.first(cipher.LENGTH_LEN)); dec_cipher.Decrypt(Span{dummies[use_idx]}.subspan(cipher.LENGTH_LEN), {}, dec_ignore, {}); } // Construct copied (and possibly damaged) copy of ciphertext. // Decrypt length auto to_decrypt = ciphertext; if (error >= 2 && error <= 9) { to_decrypt[InsecureRandRange(to_decrypt.size())] ^= std::byte(1U << (error - 2)); } // Decrypt length and resize ciphertext to accommodate. uint32_t dec_len = dec_cipher.DecryptLength(MakeByteSpan(to_decrypt).first(cipher.LENGTH_LEN)); to_decrypt.resize(dec_len + cipher.EXPANSION); // Construct copied (and possibly damaged) copy of aad. auto dec_aad = in_aad; if (error == 10) { if (in_aad.size() == 0) continue; dec_aad[InsecureRandRange(dec_aad.size())] ^= std::byte(1U << InsecureRandRange(8)); } if (error == 11) dec_aad.push_back({}); // Decrypt contents. std::vector<std::byte> decrypted(dec_len); bool dec_ignore{false}; bool dec_ok = dec_cipher.Decrypt(Span{to_decrypt}.subspan(cipher.LENGTH_LEN), dec_aad, dec_ignore, decrypted); // Verify result. BOOST_CHECK(dec_ok == !error); if (dec_ok) { BOOST_CHECK(decrypted == contents); BOOST_CHECK(dec_ignore == in_ignore); } } } } // namespace BOOST_FIXTURE_TEST_SUITE(bip324_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(packet_test_vectors) { // BIP324 key derivation uses network magic in the HKDF process. We use mainnet params here // as that is what the test vectors are written for. SelectParams(ChainType::MAIN); // The test vectors are converted using the following Python code in the BIP bip-0324/ directory: // // import sys // import csv // with open('packet_encoding_test_vectors.csv', newline='', encoding='utf-8') as csvfile: // reader = csv.DictReader(csvfile) // quote = lambda x: "\"" + x + "\"" // for row in reader: // args = [ // row['in_idx'], // quote(row['in_priv_ours']), // quote(row['in_ellswift_ours']), // quote(row['in_ellswift_theirs']), // "true" if int(row['in_initiating']) else "false", // quote(row['in_contents']), // row['in_multiply'], // quote(row['in_aad']), // "true" if int(row['in_ignore']) else "false", // quote(row['mid_send_garbage_terminator']), // quote(row['mid_recv_garbage_terminator']), // quote(row['out_session_id']), // quote(row['out_ciphertext']), // quote(row['out_ciphertext_endswith']) // ] // print(" TestBIP324PacketVector(\n " + ",\n ".join(args) + ");") TestBIP324PacketVector( 1, "61062ea5071d800bbfd59e2e8b53d47d194b095ae5a4df04936b49772ef0d4d7", "ec0adff257bbfe500c188c80b4fdd640f6b45a482bbc15fc7cef5931deff0aa186f6eb9bba7b85dc4dcc28b28722de1e3d9108b985e2967045668f66098e475b", "a4a94dfce69b4a2a0a099313d10f9f7e7d649d60501c9e1d274c300e0d89aafaffffffffffffffffffffffffffffffffffffffffffffffffffffffff8faf88d5", true, "8e", 1, "", false, "faef555dfcdb936425d84aba524758f3", "02cb8ff24307a6e27de3b4e7ea3fa65b", "ce72dffb015da62b0d0f5474cab8bc72605225b0cee3f62312ec680ec5f41ba5", "7530d2a18720162ac09c25329a60d75adf36eda3c3", ""); TestBIP324PacketVector( 999, "1f9c581b35231838f0f17cf0c979835baccb7f3abbbb96ffcc318ab71e6e126f", "a1855e10e94e00baa23041d916e259f7044e491da6171269694763f018c7e63693d29575dcb464ac816baa1be353ba12e3876cba7628bd0bd8e755e721eb0140", "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f0000000000000000000000000000000000000000000000000000000000000000", false, "3eb1d4e98035cfd8eeb29bac969ed3824a", 1, "", false, "efb64fd80acd3825ac9bc2a67216535a", "b3cb553453bceb002897e751ff7588bf", "9267c54560607de73f18c563b76a2442718879c52dd39852885d4a3c9912c9ea", "1da1bcf589f9b61872f45b7fa5371dd3f8bdf5d515b0c5f9fe9f0044afb8dc0aa1cd39a8c4", ""); TestBIP324PacketVector( 0, "0286c41cd30913db0fdff7a64ebda5c8e3e7cef10f2aebc00a7650443cf4c60d", "d1ee8a93a01130cbf299249a258f94feb5f469e7d0f2f28f69ee5e9aa8f9b54a60f2c3ff2d023634ec7f4127a96cc11662e402894cf1f694fb9a7eaa5f1d9244", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff22d5e441524d571a52b3def126189d3f416890a99d4da6ede2b0cde1760ce2c3f98457ae", true, "054290a6c6ba8d80478172e89d32bf690913ae9835de6dcf206ff1f4d652286fe0ddf74deba41d55de3edc77c42a32af79bbea2c00bae7492264c60866ae5a", 1, "84932a55aac22b51e7b128d31d9f0550da28e6a3f394224707d878603386b2f9d0c6bcd8046679bfed7b68c517e7431e75d9dd34605727d2ef1c2babbf680ecc8d68d2c4886e9953a4034abde6da4189cd47c6bb3192242cf714d502ca6103ee84e08bc2ca4fd370d5ad4e7d06c7fbf496c6c7cc7eb19c40c61fb33df2a9ba48497a96c98d7b10c1f91098a6b7b16b4bab9687f27585ade1491ae0dba6a79e1e2d85dd9d9d45c5135ca5fca3f0f99a60ea39edbc9efc7923111c937913f225d67788d5f7e8852b697e26b92ec7bfcaa334a1665511c2b4c0a42d06f7ab98a9719516c8fd17f73804555ee84ab3b7d1762f6096b778d3cb9c799cbd49a9e4a325197b4e6cc4a5c4651f8b41ff88a92ec428354531f970263b467c77ed11312e2617d0d53fe9a8707f51f9f57a77bfb49afe3d89d85ec05ee17b9186f360c94ab8bb2926b65ca99dae1d6ee1af96cad09de70b6767e949023e4b380e66669914a741ed0fa420a48dbc7bfae5ef2019af36d1022283dd90655f25eec7151d471265d22a6d3f91dc700ba749bb67c0fe4bc0888593fbaf59d3c6fff1bf756a125910a63b9682b597c20f560ecb99c11a92c8c8c3f7fbfaa103146083a0ccaecf7a5f5e735a784a8820155914a289d57d8141870ffcaf588882332e0bcd8779efa931aa108dab6c3cce76691e345df4a91a03b71074d66333fd3591bff071ea099360f787bbe43b7b3dff2a59c41c7642eb79870222ad1c6f2e5a191ed5acea51134679587c9cf71c7d8ee290be6bf465c4ee47897a125708704ad610d8d00252d01959209d7cd04d5ecbbb1419a7e84037a55fefa13dee464b48a35c96bcb9a53e7ed461c3a1607ee00c3c302fd47cd73fda7493e947c9834a92d63dcfbd65aa7c38c3e3a2748bb5d9a58e7495d243d6b741078c8f7ee9c8813e473a323375702702b0afae1550c8341eedf5247627343a95240cb02e3e17d5dca16f8d8d3b2228e19c06399f8ec5c5e9dbe4caef6a0ea3ffb1d3c7eac03ae030e791fa12e537c80d56b55b764cadf27a8701052df1282ba8b5e3eb62b5dc7973ac40160e00722fa958d95102fc25c549d8c0e84bed95b7acb61ba65700c4de4feebf78d13b9682c52e937d23026fb4c6193e6644e2d3c99f91f4f39a8b9fc6d013f89c3793ef703987954dc0412b550652c01d922f525704d32d70d6d4079bc3551b563fb29577b3aecdc9505011701dddfd94830431e7a4918927ee44fb3831ce8c4513839e2deea1287f3fa1ab9b61a256c09637dbc7b4f0f8fbb783840f9c24526da883b0df0c473cf231656bd7bc1aaba7f321fec0971c8c2c3444bff2f55e1df7fea66ec3e440a612db9aa87bb505163a59e06b96d46f50d8120b92814ac5ab146bc78dbbf91065af26107815678ce6e33812e6bf3285d4ef3b7b04b076f21e7820dcbfdb4ad5218cf4ff6a65812d8fcb98ecc1e95e2fa58e3efe4ce26cd0bd400d6036ab2ad4f6c713082b5e3f1e04eb9e3b6c8f63f57953894b9e220e0130308e1fd91f72d398c1e7962ca2c31be83f31d6157633581a0a6910496de8d55d3d07090b6aa087159e388b7e7dec60f5d8a60d93ca2ae91296bd484d916bfaaa17c8f45ea4b1a91b37c82821199a2b7596672c37156d8701e7352aa48671d3b1bbbd2bd5f0a2268894a25b0cb2514af39c8743f8cce8ab4b523053739fd8a522222a09acf51ac704489cf17e4b7125455cb8f125b4d31af1eba1f8cf7f81a5a100a141a7ee72e8083e065616649c241f233645c5fc865d17f0285f5c52d9f45312c979bfb3ce5f2a1b951deddf280ffb3f370410cffd1583bfa90077835aa201a0712d1dcd1293ee177738b14e6b5e2a496d05220c3253bb6578d6aff774be91946a614dd7e879fb3dcf7451e0b9adb6a8c44f53c2c464bcc0019e9fad89cac7791a0a3f2974f759a9856351d4d2d7c5612c17cfc50f8479945df57716767b120a590f4bf656f4645029a525694d8a238446c5f5c2c1c995c09c1405b8b1eb9e0352ffdf766cc964f8dcf9f8f043dfab6d102cf4b298021abd78f1d9025fa1f8e1d710b38d9d1652f2d88d1305874ec41609b6617b65c5adb19b6295dc5c5da5fdf69f28144ea12f17c3c6fcce6b9b5157b3dfc969d6725fa5b098a4d9b1d31547ed4c9187452d281d0a5d456008caf1aa251fac8f950ca561982dc2dc908d3691ee3b6ad3ae3d22d002577264ca8e49c523bd51c4846be0d198ad9407bf6f7b82c79893eb2c05fe9981f687a97a4f01fe45ff8c8b7ecc551135cd960a0d6001ad35020be07ffb53cb9e731522ca8ae9364628914b9b8e8cc2f37f03393263603cc2b45295767eb0aac29b0930390eb89587ab2779d2e3decb8042acece725ba42eda650863f418f8d0d50d104e44fbbe5aa7389a4a144a8cecf00f45fb14c39112f9bfb56c0acbd44fa3ff261f5ce4acaa5134c2c1d0cca447040820c81ab1bcdc16aa075b7c68b10d06bbb7ce08b5b805e0238f24402cf24a4b4e00701935a0c68add3de090903f9b85b153cb179a582f57113bfc21c2093803f0cfa4d9d4672c2b05a24f7e4c34a8e9101b70303a7378b9c50b6cddd46814ef7fd73ef6923feceab8fc5aa8b0d185f2e83c7a99dcb1077c0ab5c1f5d5f01ba2f0420443f75c4417db9ebf1665efbb33dca224989920a64b44dc26f682cc77b4632c8454d49135e52503da855bc0f6ff8edc1145451a9772c06891f41064036b66c3119a0fc6e80dffeb65dc456108b7ca0296f4175fff3ed2b0f842cd46bd7e86f4c62dfaf1ddbf836263c00b34803de164983d0811cebfac86e7720c726d3048934c36c23189b02386a722ca9f0fe00233ab50db928d3bccea355cc681144b8b7edcaae4884d5a8f04425c0890ae2c74326e138066d8c05f4c82b29df99b034ea727afde590a1f2177ace3af99cfb1729d6539ce7f7f7314b046aab74497e63dd399e1f7d5f16517c23bd830d1fdee810f3c3b77573dd69c4b97d80d71fb5a632e00acdfa4f8e829faf3580d6a72c40b28a82172f8dcd4627663ebf6069736f21735fd84a226f427cd06bb055f94e7c92f31c48075a2955d82a5b9d2d0198ce0d4e131a112570a8ee40fb80462a81436a58e7db4e34b6e2c422e82f934ecda9949893da5730fc5c23c7c920f363f85ab28cc6a4206713c3152669b47efa8238fa826735f17b4e78750276162024ec85458cd5808e06f40dd9fd43775a456a3ff6cae90550d76d8b2899e0762ad9a371482b3e38083b1274708301d6346c22fea9bb4b73db490ff3ab05b2f7f9e187adef139a7794454b7300b8cc64d3ad76c0e4bc54e08833a4419251550655380d675bc91855aeb82585220bb97f03e976579c08f321b5f8f70988d3061f41465517d53ac571dbf1b24b94443d2e9a8e8a79b392b3d6a4ecdd7f626925c365ef6221305105ce9b5f5b6ecc5bed3d702bd4b7f5008aa8eb8c7aa3ade8ecf6251516fbefeea4e1082aa0e1848eddb31ffe44b04792d296054402826e4bd054e671f223e5557e4c94f89ca01c25c44f1a2ff2c05a70b43408250705e1b858bf0670679fdcd379203e36be3500dd981b1a6422c3cf15224f7fefdef0a5f225c5a09d15767598ecd9e262460bb33a4b5d09a64591efabc57c923d3be406979032ae0bc0997b65336a06dd75b253332ad6a8b63ef043f780a1b3fb6d0b6cad98b1ef4a02535eb39e14a866cfc5fc3a9c5deb2261300d71280ebe66a0776a151469551c3c5fa308757f956655278ec6330ae9e3625468c5f87e02cd9a6489910d4143c1f4ee13aa21a6859d907b788e28572fecee273d44e4a900fa0aa668dd861a60fb6b6b12c2c5ef3c8df1bd7ef5d4b0d1cdb8c15fffbb365b9784bd94abd001c6966216b9b67554ad7cb7f958b70092514f7800fc40244003e0fd1133a9b850fb17f4fcafde07fc87b07fb510670654a5d2d6fc9876ac74728ea41593beef003d6858786a52d3a40af7529596767c17000bfaf8dc52e871359f4ad8bf6e7b2853e5229bdf39657e213580294a5317c5df172865e1e17fe37093b585e04613f5f078f761b2b1752eb32983afda24b523af8851df9a02b37e77f543f18888a782a994a50563334282bf9cdfccc183fdf4fcd75ad86ee0d94f91ee2300a5befbccd14e03a77fc031a8cfe4f01e4c5290f5ac1da0d58ea054bd4837cfd93e5e34fc0eb16e48044ba76131f228d16cde9b0bb978ca7cdcd10653c358bdb26fdb723a530232c32ae0a4cecc06082f46e1c1d596bfe60621ad1e354e01e07b040cc7347c016653f44d926d13ca74e6cbc9d4ab4c99f4491c95c76fff5076b3936eb9d0a286b97c035ca88a3c6309f5febfd4cdaac869e4f58ed409b1e9eb4192fb2f9c2f12176d460fd98286c9d6df84598f260119fd29c63f800c07d8df83d5cc95f8c2fea2812e7890e8a0718bb1e031ecbebc0436dcf3e3b9a58bcc06b4c17f711f80fe1dffc3326a6eb6e00283055c6dabe20d311bfd5019591b7954f8163c9afad9ef8390a38f3582e0a79cdf0353de8eeb6b5f9f27b16ffdef7dd62869b4840ee226ccdce95e02c4545eb981b60571cd83f03dc5eaf8c97a0829a4318a9b3dc06c0e003db700b2260ff1fa8fee66890e637b109abb03ec901b05ca599775f48af50154c0e67d82bf0f558d7d3e0778dc38bea1eb5f74dc8d7f90abdf5511a424be66bf8b6a3cacb477d2e7ef4db68d2eba4d5289122d851f9501ba7e9c4957d8eba3be3fc8e785c4265a1d65c46f2809b70846c693864b169c9dcb78be26ea14b8613f145b01887222979a9e67aee5f800caa6f5c4229bdeefc901232ace6143c9865e4d9c07f51aa200afaf7e48a7d1d8faf366023beab12906ffcb3eaf72c0eb68075e4daf3c080e0c31911befc16f0cc4a09908bb7c1e26abab38bd7b788e1a09c0edf1a35a38d2ff1d3ed47fcdaae2f0934224694f5b56705b9409b6d3d64f3833b686f7576ec64bbdd6ff174e56c2d1edac0011f904681a73face26573fbba4e34652f7ae84acfb2fa5a5b3046f98178cd0831df7477de70e06a4c00e305f31aafc026ef064dd68fd3e4252b1b91d617b26c6d09b6891a00df68f105b5962e7f9d82da101dd595d286da721443b72b2aba2377f6e7772e33b3a5e3753da9c2578c5d1daab80187f55518c72a64ee150a7cb5649823c08c9f62cd7d020b45ec2cba8310db1a7785a46ab24785b4d54ff1660b5ca78e05a9a55edba9c60bf044737bc468101c4e8bd1480d749be5024adefca1d998abe33eaeb6b11fbb39da5d905fdd3f611b2e51517ccee4b8af72c2d948573505590d61a6783ab7278fc43fe55b1fcc0e7216444d3c8039bb8145ef1ce01c50e95a3f3feab0aee883fdb94cc13ee4d21c542aa795e18932228981690f4d4c57ca4db6eb5c092e29d8a05139d509a8aeb48baa1eb97a76e597a32b280b5e9d6c36859064c98ff96ef5126130264fa8d2f49213870d9fb036cff95da51f270311d9976208554e48ffd486470d0ecdb4e619ccbd8226147204baf8e235f54d8b1cba8fa34a9a4d055de515cdf180d2bb6739a175183c472e30b5c914d09eeb1b7dafd6872b38b48c6afc146101200e6e6a44fe5684e220adc11f5c403ddb15df8051e6bdef09117a3a5349938513776286473a3cf1d2788bb875052a2e6459fa7926da33380149c7f98d7700528a60c954e6f5ecb65842fde69d614be69eaa2040a4819ae6e756accf936e14c1e894489744a79c1f2c1eb295d13e2d767c09964b61f9cfe497649f712", false, "d4e3f18ac2e2095edb5c3b94236118ad", "4faa6c4233d9fd53d170ede4172142a8", "23f154ac43cfc59c4243e9fc68aeec8f19ad3942d74108e833b36f0dd3dcd357", "8da7de6ea7bf2a81a396a42880ba1f5756734c4821309ac9aeffa2a26ce86873b9dc4935a772de6ec5162c6d075b14536800fb174841153511bfb597e992e2fe8a450c4bce102cc550bb37fd564c4d60bf884e", ""); TestBIP324PacketVector( 223, "6c77432d1fda31e9f942f8af44607e10f3ad38a65f8a4bddae823e5eff90dc38", "d2685070c1e6376e633e825296634fd461fa9e5bdf2109bcebd735e5a91f3e587c5cb782abb797fbf6bb5074fd1542a474f2a45b673763ec2db7fb99b737bbb9", "56bd0c06f10352c3a1a9f4b4c92f6fa2b26df124b57878353c1fc691c51abea77c8817daeeb9fa546b77c8daf79d89b22b0e1b87574ece42371f00237aa9d83a", false, "7e0e78eb6990b059e6cf0ded66ea93ef82e72aa2f18ac24f2fc6ebab561ae557420729da103f64cecfa20527e15f9fb669a49bbbf274ef0389b3e43c8c44e5f60bf2ac38e2b55e7ec4273dba15ba41d21f8f5b3ee1688b3c29951218caf847a97fb50d75a86515d445699497d968164bf740012679b8962de573be941c62b7ef", 1, "", true, "cf2e25f23501399f30738d7eee652b90", "225a477a28a54ea7671d2b217a9c29db", "7ec02fea8c1484e3d0875f978c5f36d63545e2e4acf56311394422f4b66af612", "", "729847a3e9eba7a5bff454b5de3b393431ee360736b6c030d7a5bd01d1203d2e98f528543fd2bf886ccaa1ada5e215a730a36b3f4abfc4e252c89eb01d9512f94916dae8a76bf16e4da28986ffe159090fe5267ee3394300b7ccf4dfad389a26321b3a3423e4594a82ccfbad16d6561ecb8772b0cb040280ff999a29e3d9d4fd"); TestBIP324PacketVector( 448, "a6ec25127ca1aa4cf16b20084ba1e6516baae4d32422288e9b36d8bddd2de35a", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff053d7ecca53e33e185a8b9be4e7699a97c6ff4c795522e5918ab7cd6b6884f67e683f3dc", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffa7730be30000000000000000000000000000000000000000000000000000000000000000", true, "00cf68f8f7ac49ffaa02c4864fdf6dfe7bbf2c740b88d98c50ebafe32c92f3427f57601ffcb21a3435979287db8fee6c302926741f9d5e464c647eeb9b7acaeda46e00abd7506fc9a719847e9a7328215801e96198dac141a15c7c2f68e0690dd1176292a0dded04d1f548aad88f1aebdc0a8f87da4bb22df32dd7c160c225b843e83f6525d6d484f502f16d923124fc538794e21da2eb689d18d87406ecced5b9f92137239ed1d37bcfa7836641a83cf5e0a1cf63f51b06f158e499a459ede41c", 1, "", false, "fead69be77825a23daec377c362aa560", "511d4980526c5e64aa7187462faeafdd", "acb8f084ea763ddd1b92ac4ed23bf44de20b84ab677d4e4e6666a6090d40353d", "", "77b4656934a82de1a593d8481f020194ddafd8cac441f9d72aeb8721e6a14f49698ca6d9b2b6d59d07a01aa552fd4d5b68d0d1617574c77dea10bfadbaa31b83885b7ceac2fd45e3e4a331c51a74e7b1698d81b64c87c73c5b9258b4d83297f9debc2e9aa07f8572ff434dc792b83ecf07b3197de8dc9cf7be56acb59c66cff5"); TestBIP324PacketVector( 673, "0af952659ed76f80f585966b95ab6e6fd68654672827878684c8b547b1b94f5a", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffc81017fd92fd31637c26c906b42092e11cc0d3afae8d9019d2578af22735ce7bc469c72d", "9652d78baefc028cd37a6a92625b8b8f85fde1e4c944ad3f20e198bef8c02f19fffffffffffffffffffffffffffffffffffffffffffffffffffffffff2e91870", false, "5c6272ee55da855bbbf7b1246d9885aa7aa601a715ab86fa46c50da533badf82b97597c968293ae04e", 97561, "", false, "5e2375ac629b8df1e4ff3617c6255a70", "70bcbffcb62e4d29d2605d30bceef137", "7332e92a3f9d2792c4d444fac5ed888c39a073043a65eefb626318fd649328f8", "", "657a4a19711ce593c3844cb391b224f60124aba7e04266233bc50cafb971e26c7716b76e98376448f7d214dd11e629ef9a974d60e3770a695810a61c4ba66d78b936ee7892b98f0b48ddae9fcd8b599dca1c9b43e9b95e0226cf8d4459b8a7c2c4e6db80f1d58c7b20dd7208fa5c1057fb78734223ee801dbd851db601fee61e"); TestBIP324PacketVector( 1024, "f90e080c64b05824c5a24b2501d5aeaf08af3872ee860aa80bdcd430f7b63494", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff115173765dc202cf029ad3f15479735d57697af12b0131dd21430d5772e4ef11474d58b9", "12a50f3fafea7c1eeada4cf8d33777704b77361453afc83bda91eef349ae044d20126c6200547ea5a6911776c05dee2a7f1a9ba7dfbabbbd273c3ef29ef46e46", true, "5f67d15d22ca9b2804eeab0a66f7f8e3a10fa5de5809a046084348cbc5304e843ef96f59a59c7d7fdfe5946489f3ea297d941bac326225df316a25fc90f0e65b0d31a9c497e960fdbf8c482516bc8a9c1c77b7f6d0e1143810c737f76f9224e6f2c9af5186b4f7259c7e8d165b6e4fe3d38a60bdbdd4d06ecdcaaf62086070dbb68686b802d53dfd7db14b18743832605f5461ad81e2af4b7e8ff0eff0867a25b93cec7becf15c43131895fed09a83bf1ee4a87d44dd0f02a837bf5a1232e201cb882734eb9643dc2dc4d4e8b5690840766212c7ac8f38ad8a9ec47c7a9b3e022ae3eb6a32522128b518bd0d0085dd81c5", 69615, "", true, "b709dea25e0be287c50e3603482c2e98", "1f677e9d7392ebe3633fd82c9efb0f16", "889f339285564fd868401fac8380bb9887925122ec8f31c8ae51ce067def103b", "", "7c4b9e1e6c1ce69da7b01513cdc4588fd93b04dafefaf87f31561763d906c672bac3dfceb751ebd126728ac017d4d580e931b8e5c7d5dfe0123be4dc9b2d2238b655c8a7fadaf8082c31e310909b5b731efc12f0a56e849eae6bfeedcc86dd27ef9b91d159256aa8e8d2b71a311f73350863d70f18d0d7302cf551e4303c7733"); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/translation_tests.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <tinyformat.h> #include <util/translation.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(translation_tests) BOOST_AUTO_TEST_CASE(translation_namedparams) { bilingual_str arg{"original", "translated"}; bilingual_str format{"original [%s]", "translated [%s]"}; bilingual_str result{strprintf(format, arg)}; BOOST_CHECK_EQUAL(result.original, "original [original]"); BOOST_CHECK_EQUAL(result.translated, "translated [translated]"); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/merkleblock_tests.cpp
// Copyright (c) 2012-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <merkleblock.h> #include <test/util/setup_common.h> #include <uint256.h> #include <boost/test/unit_test.hpp> #include <set> #include <vector> BOOST_AUTO_TEST_SUITE(merkleblock_tests) /** * Create a CMerkleBlock using a list of txids which will be found in the * given block. */ BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_found) { CBlock block = getBlock13b8a(); std::set<Txid> txids; // Last txn in block. Txid txhash1{TxidFromString("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20")}; // Second txn in block. Txid txhash2{TxidFromString("0xf9fc751cb7dc372406a9f8d738d5e6f8f63bab71986a39cf36ee70ee17036d07")}; txids.insert(txhash1); txids.insert(txhash2); CMerkleBlock merkleBlock(block, txids); BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex()); // vMatchedTxn is only used when bloom filter is specified. BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U); std::vector<uint256> vMatched; std::vector<unsigned int> vIndex; BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex()); BOOST_CHECK_EQUAL(vMatched.size(), 2U); // Ordered by occurrence in depth-first tree traversal. BOOST_CHECK_EQUAL(vMatched[0].ToString(), txhash2.ToString()); BOOST_CHECK_EQUAL(vIndex[0], 1U); BOOST_CHECK_EQUAL(vMatched[1].ToString(), txhash1.ToString()); BOOST_CHECK_EQUAL(vIndex[1], 8U); } /** * Create a CMerkleBlock using a list of txids which will not be found in the * given block. */ BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_not_found) { CBlock block = getBlock13b8a(); std::set<Txid> txids2; txids2.insert(TxidFromString("0xc0ffee00003bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20")); CMerkleBlock merkleBlock(block, txids2); BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex()); BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U); std::vector<uint256> vMatched; std::vector<unsigned int> vIndex; BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex()); BOOST_CHECK_EQUAL(vMatched.size(), 0U); BOOST_CHECK_EQUAL(vIndex.size(), 0U); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/bswap_tests.cpp
// Copyright (c) 2016-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <compat/byteswap.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(bswap_tests) BOOST_AUTO_TEST_CASE(bswap_tests) { uint16_t u1 = 0x1234; uint32_t u2 = 0x56789abc; uint64_t u3 = 0xdef0123456789abc; uint16_t e1 = 0x3412; uint32_t e2 = 0xbc9a7856; uint64_t e3 = 0xbc9a78563412f0de; BOOST_CHECK(bswap_16(u1) == e1); BOOST_CHECK(bswap_32(u2) == e2); BOOST_CHECK(bswap_64(u3) == e3); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/serialize_tests.cpp
// Copyright (c) 2012-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <hash.h> #include <serialize.h> #include <streams.h> #include <test/util/setup_common.h> #include <util/strencodings.h> #include <stdint.h> #include <string> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(serialize_tests, BasicTestingSetup) class CSerializeMethodsTestSingle { protected: int intval; bool boolval; std::string stringval; char charstrval[16]; CTransactionRef txval; public: CSerializeMethodsTestSingle() = default; CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const uint8_t* charstrvalin, const CTransactionRef& txvalin) : intval(intvalin), boolval(boolvalin), stringval(std::move(stringvalin)), txval(txvalin) { memcpy(charstrval, charstrvalin, sizeof(charstrval)); } SERIALIZE_METHODS(CSerializeMethodsTestSingle, obj) { READWRITE(obj.intval); READWRITE(obj.boolval); READWRITE(obj.stringval); READWRITE(obj.charstrval); READWRITE(TX_WITH_WITNESS(obj.txval)); } bool operator==(const CSerializeMethodsTestSingle& rhs) const { return intval == rhs.intval && boolval == rhs.boolval && stringval == rhs.stringval && strcmp(charstrval, rhs.charstrval) == 0 && *txval == *rhs.txval; } }; class CSerializeMethodsTestMany : public CSerializeMethodsTestSingle { public: using CSerializeMethodsTestSingle::CSerializeMethodsTestSingle; SERIALIZE_METHODS(CSerializeMethodsTestMany, obj) { READWRITE(obj.intval, obj.boolval, obj.stringval, obj.charstrval, TX_WITH_WITNESS(obj.txval)); } }; BOOST_AUTO_TEST_CASE(sizes) { BOOST_CHECK_EQUAL(sizeof(unsigned char), GetSerializeSize((unsigned char)0)); BOOST_CHECK_EQUAL(sizeof(int8_t), GetSerializeSize(int8_t(0))); BOOST_CHECK_EQUAL(sizeof(uint8_t), GetSerializeSize(uint8_t(0))); BOOST_CHECK_EQUAL(sizeof(int16_t), GetSerializeSize(int16_t(0))); BOOST_CHECK_EQUAL(sizeof(uint16_t), GetSerializeSize(uint16_t(0))); BOOST_CHECK_EQUAL(sizeof(int32_t), GetSerializeSize(int32_t(0))); BOOST_CHECK_EQUAL(sizeof(uint32_t), GetSerializeSize(uint32_t(0))); BOOST_CHECK_EQUAL(sizeof(int64_t), GetSerializeSize(int64_t(0))); BOOST_CHECK_EQUAL(sizeof(uint64_t), GetSerializeSize(uint64_t(0))); // Bool is serialized as uint8_t BOOST_CHECK_EQUAL(sizeof(uint8_t), GetSerializeSize(bool(0))); // Sanity-check GetSerializeSize and c++ type matching BOOST_CHECK_EQUAL(GetSerializeSize((unsigned char)0), 1U); BOOST_CHECK_EQUAL(GetSerializeSize(int8_t(0)), 1U); BOOST_CHECK_EQUAL(GetSerializeSize(uint8_t(0)), 1U); BOOST_CHECK_EQUAL(GetSerializeSize(int16_t(0)), 2U); BOOST_CHECK_EQUAL(GetSerializeSize(uint16_t(0)), 2U); BOOST_CHECK_EQUAL(GetSerializeSize(int32_t(0)), 4U); BOOST_CHECK_EQUAL(GetSerializeSize(uint32_t(0)), 4U); BOOST_CHECK_EQUAL(GetSerializeSize(int64_t(0)), 8U); BOOST_CHECK_EQUAL(GetSerializeSize(uint64_t(0)), 8U); BOOST_CHECK_EQUAL(GetSerializeSize(bool(0)), 1U); BOOST_CHECK_EQUAL(GetSerializeSize(std::array<uint8_t, 1>{0}), 1U); BOOST_CHECK_EQUAL(GetSerializeSize(std::array<uint8_t, 2>{0, 0}), 2U); } BOOST_AUTO_TEST_CASE(varints) { // encode DataStream ss{}; DataStream::size_type size = 0; for (int i = 0; i < 100000; i++) { ss << VARINT_MODE(i, VarIntMode::NONNEGATIVE_SIGNED); size += ::GetSerializeSize(VARINT_MODE(i, VarIntMode::NONNEGATIVE_SIGNED)); BOOST_CHECK(size == ss.size()); } for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) { ss << VARINT(i); size += ::GetSerializeSize(VARINT(i)); BOOST_CHECK(size == ss.size()); } // decode for (int i = 0; i < 100000; i++) { int j = -1; ss >> VARINT_MODE(j, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i); } for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) { uint64_t j = std::numeric_limits<uint64_t>::max(); ss >> VARINT(j); BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i); } } BOOST_AUTO_TEST_CASE(varints_bitpatterns) { DataStream ss{}; ss << VARINT_MODE(0, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "00"); ss.clear(); ss << VARINT_MODE(0x7f, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear(); ss << VARINT_MODE(int8_t{0x7f}, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear(); ss << VARINT_MODE(0x80, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear(); ss << VARINT(uint8_t{0x80}); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear(); ss << VARINT_MODE(0x1234, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear(); ss << VARINT_MODE(int16_t{0x1234}, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear(); ss << VARINT_MODE(0xffff, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear(); ss << VARINT(uint16_t{0xffff}); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear(); ss << VARINT_MODE(0x123456, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear(); ss << VARINT_MODE(int32_t{0x123456}, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear(); ss << VARINT(0x80123456U); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear(); ss << VARINT(uint32_t{0x80123456U}); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear(); ss << VARINT(0xffffffff); BOOST_CHECK_EQUAL(HexStr(ss), "8efefefe7f"); ss.clear(); ss << VARINT_MODE(0x7fffffffffffffffLL, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "fefefefefefefefe7f"); ss.clear(); ss << VARINT(0xffffffffffffffffULL); BOOST_CHECK_EQUAL(HexStr(ss), "80fefefefefefefefe7f"); ss.clear(); } BOOST_AUTO_TEST_CASE(compactsize) { DataStream ss{}; std::vector<char>::size_type i, j; for (i = 1; i <= MAX_SIZE; i *= 2) { WriteCompactSize(ss, i-1); WriteCompactSize(ss, i); } for (i = 1; i <= MAX_SIZE; i *= 2) { j = ReadCompactSize(ss); BOOST_CHECK_MESSAGE((i-1) == j, "decoded:" << j << " expected:" << (i-1)); j = ReadCompactSize(ss); BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i); } } static bool isCanonicalException(const std::ios_base::failure& ex) { std::ios_base::failure expectedException("non-canonical ReadCompactSize()"); // The string returned by what() can be different for different platforms. // Instead of directly comparing the ex.what() with an expected string, // create an instance of exception to see if ex.what() matches // the expected explanatory string returned by the exception instance. return strcmp(expectedException.what(), ex.what()) == 0; } BOOST_AUTO_TEST_CASE(vector_bool) { std::vector<uint8_t> vec1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1}; std::vector<bool> vec2{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1}; BOOST_CHECK(vec1 == std::vector<uint8_t>(vec2.begin(), vec2.end())); BOOST_CHECK((HashWriter{} << vec1).GetHash() == (HashWriter{} << vec2).GetHash()); } BOOST_AUTO_TEST_CASE(array) { std::array<uint8_t, 32> array1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1}; DataStream ds; ds << array1; std::array<uint8_t, 32> array2; ds >> array2; BOOST_CHECK(array1 == array2); } BOOST_AUTO_TEST_CASE(noncanonical) { // Write some non-canonical CompactSize encodings, and // make sure an exception is thrown when read back. DataStream ss{}; std::vector<char>::size_type n; // zero encoded with three bytes: ss << Span{"\xfd\x00\x00"}.first(3); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); // 0xfc encoded with three bytes: ss << Span{"\xfd\xfc\x00"}.first(3); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); // 0xfd encoded with three bytes is OK: ss << Span{"\xfd\xfd\x00"}.first(3); n = ReadCompactSize(ss); BOOST_CHECK(n == 0xfd); // zero encoded with five bytes: ss << Span{"\xfe\x00\x00\x00\x00"}.first(5); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); // 0xffff encoded with five bytes: ss << Span{"\xfe\xff\xff\x00\x00"}.first(5); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); // zero encoded with nine bytes: ss << Span{"\xff\x00\x00\x00\x00\x00\x00\x00\x00"}.first(9); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); // 0x01ffffff encoded with nine bytes: ss << Span{"\xff\xff\xff\xff\x01\x00\x00\x00\x00"}.first(9); BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); } BOOST_AUTO_TEST_CASE(class_methods) { int intval(100); bool boolval(true); std::string stringval("testing"); const uint8_t charstrval[16]{"testing charstr"}; CMutableTransaction txval; CTransactionRef tx_ref{MakeTransactionRef(txval)}; CSerializeMethodsTestSingle methodtest1(intval, boolval, stringval, charstrval, tx_ref); CSerializeMethodsTestMany methodtest2(intval, boolval, stringval, charstrval, tx_ref); CSerializeMethodsTestSingle methodtest3; CSerializeMethodsTestMany methodtest4; DataStream ss; BOOST_CHECK(methodtest1 == methodtest2); ss << methodtest1; ss >> methodtest4; ss << methodtest2; ss >> methodtest3; BOOST_CHECK(methodtest1 == methodtest2); BOOST_CHECK(methodtest2 == methodtest3); BOOST_CHECK(methodtest3 == methodtest4); DataStream ss2; ss2 << intval << boolval << stringval << charstrval << TX_WITH_WITNESS(txval); ss2 >> methodtest3; BOOST_CHECK(methodtest3 == methodtest4); { DataStream ds; const std::string in{"ab"}; ds << Span{in} << std::byte{'c'}; std::array<std::byte, 2> out; std::byte out_3; ds >> Span{out} >> out_3; BOOST_CHECK_EQUAL(out.at(0), std::byte{'a'}); BOOST_CHECK_EQUAL(out.at(1), std::byte{'b'}); BOOST_CHECK_EQUAL(out_3, std::byte{'c'}); } } struct BaseFormat { const enum { RAW, HEX, } m_base_format; SER_PARAMS_OPFUNC }; constexpr BaseFormat RAW{BaseFormat::RAW}; constexpr BaseFormat HEX{BaseFormat::HEX}; /// (Un)serialize a number as raw byte or 2 hexadecimal chars. class Base { public: uint8_t m_base_data; Base() : m_base_data(17) {} explicit Base(uint8_t data) : m_base_data(data) {} template <typename Stream> void Serialize(Stream& s) const { if (s.GetParams().m_base_format == BaseFormat::RAW) { s << m_base_data; } else { s << Span{HexStr(Span{&m_base_data, 1})}; } } template <typename Stream> void Unserialize(Stream& s) { if (s.GetParams().m_base_format == BaseFormat::RAW) { s >> m_base_data; } else { std::string hex{"aa"}; s >> Span{hex}.first(hex.size()); m_base_data = TryParseHex<uint8_t>(hex).value().at(0); } } }; class DerivedAndBaseFormat { public: BaseFormat m_base_format; enum class DerivedFormat { LOWER, UPPER, } m_derived_format; SER_PARAMS_OPFUNC }; class Derived : public Base { public: std::string m_derived_data; SERIALIZE_METHODS_PARAMS(Derived, obj, DerivedAndBaseFormat, fmt) { READWRITE(fmt.m_base_format(AsBase<Base>(obj))); if (ser_action.ForRead()) { std::string str; s >> str; SER_READ(obj, obj.m_derived_data = str); } else { s << (fmt.m_derived_format == DerivedAndBaseFormat::DerivedFormat::LOWER ? ToLower(obj.m_derived_data) : ToUpper(obj.m_derived_data)); } } }; BOOST_AUTO_TEST_CASE(with_params_base) { Base b{0x0F}; DataStream stream; stream << RAW(b); BOOST_CHECK_EQUAL(stream.str(), "\x0F"); b.m_base_data = 0; stream >> RAW(b); BOOST_CHECK_EQUAL(b.m_base_data, 0x0F); stream.clear(); stream << HEX(b); BOOST_CHECK_EQUAL(stream.str(), "0f"); b.m_base_data = 0; stream >> HEX(b); BOOST_CHECK_EQUAL(b.m_base_data, 0x0F); } BOOST_AUTO_TEST_CASE(with_params_vector_of_base) { std::vector<Base> v{Base{0x0F}, Base{0xFF}}; DataStream stream; stream << RAW(v); BOOST_CHECK_EQUAL(stream.str(), "\x02\x0F\xFF"); v[0].m_base_data = 0; v[1].m_base_data = 0; stream >> RAW(v); BOOST_CHECK_EQUAL(v[0].m_base_data, 0x0F); BOOST_CHECK_EQUAL(v[1].m_base_data, 0xFF); stream.clear(); stream << HEX(v); BOOST_CHECK_EQUAL(stream.str(), "\x02" "0fff"); v[0].m_base_data = 0; v[1].m_base_data = 0; stream >> HEX(v); BOOST_CHECK_EQUAL(v[0].m_base_data, 0x0F); BOOST_CHECK_EQUAL(v[1].m_base_data, 0xFF); } constexpr DerivedAndBaseFormat RAW_LOWER{{BaseFormat::RAW}, DerivedAndBaseFormat::DerivedFormat::LOWER}; constexpr DerivedAndBaseFormat HEX_UPPER{{BaseFormat::HEX}, DerivedAndBaseFormat::DerivedFormat::UPPER}; BOOST_AUTO_TEST_CASE(with_params_derived) { Derived d; d.m_base_data = 0x0F; d.m_derived_data = "xY"; DataStream stream; stream << RAW_LOWER(d); stream << HEX_UPPER(d); BOOST_CHECK_EQUAL(stream.str(), "\x0F\x02xy" "0f\x02XY"); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/base32_tests.cpp
// Copyright (c) 2012-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/strencodings.h> #include <boost/test/unit_test.hpp> #include <string> using namespace std::literals; BOOST_AUTO_TEST_SUITE(base32_tests) BOOST_AUTO_TEST_CASE(base32_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"}; static const std::string vstrOutNoPadding[] = {"","my","mzxq","mzxw6","mzxw6yq","mzxw6ytb","mzxw6ytboi"}; for (unsigned int i=0; i<std::size(vstrIn); i++) { std::string strEnc = EncodeBase32(vstrIn[i]); BOOST_CHECK_EQUAL(strEnc, vstrOut[i]); strEnc = EncodeBase32(vstrIn[i], false); BOOST_CHECK_EQUAL(strEnc, vstrOutNoPadding[i]); auto dec = DecodeBase32(vstrOut[i]); BOOST_REQUIRE(dec); BOOST_CHECK_MESSAGE(MakeByteSpan(*dec) == MakeByteSpan(vstrIn[i]), vstrOut[i]); } // Decoding strings with embedded NUL characters should fail BOOST_CHECK(!DecodeBase32("invalid\0"s)); // correct size, invalid due to \0 BOOST_CHECK(DecodeBase32("AWSX3VPP"s)); // valid BOOST_CHECK(!DecodeBase32("AWSX3VPP\0invalid"s)); // correct size, invalid due to \0 BOOST_CHECK(!DecodeBase32("AWSX3VPPinvalid"s)); // invalid size } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/netbase_tests.cpp
// Copyright (c) 2012-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <net_permissions.h> #include <netaddress.h> #include <netbase.h> #include <netgroup.h> #include <protocol.h> #include <serialize.h> #include <streams.h> #include <test/util/setup_common.h> #include <util/strencodings.h> #include <util/translation.h> #include <string> #include <boost/test/unit_test.hpp> using namespace std::literals; BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup) static CNetAddr ResolveIP(const std::string& ip) { return LookupHost(ip, false).value_or(CNetAddr{}); } static CNetAddr CreateInternal(const std::string& host) { CNetAddr addr; addr.SetInternal(host); return addr; } BOOST_AUTO_TEST_CASE(netbase_networks) { BOOST_CHECK(ResolveIP("127.0.0.1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(ResolveIP("::1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(ResolveIP("8.8.8.8").GetNetwork() == NET_IPV4); BOOST_CHECK(ResolveIP("2001::8888").GetNetwork() == NET_IPV6); BOOST_CHECK(ResolveIP("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion").GetNetwork() == NET_ONION); BOOST_CHECK(CreateInternal("foo.com").GetNetwork() == NET_INTERNAL); } BOOST_AUTO_TEST_CASE(netbase_properties) { BOOST_CHECK(ResolveIP("127.0.0.1").IsIPv4()); BOOST_CHECK(ResolveIP("::FFFF:192.168.1.1").IsIPv4()); BOOST_CHECK(ResolveIP("::1").IsIPv6()); BOOST_CHECK(ResolveIP("10.0.0.1").IsRFC1918()); BOOST_CHECK(ResolveIP("192.168.1.1").IsRFC1918()); BOOST_CHECK(ResolveIP("172.31.255.255").IsRFC1918()); BOOST_CHECK(ResolveIP("198.18.0.0").IsRFC2544()); BOOST_CHECK(ResolveIP("198.19.255.255").IsRFC2544()); BOOST_CHECK(ResolveIP("2001:0DB8::").IsRFC3849()); BOOST_CHECK(ResolveIP("169.254.1.1").IsRFC3927()); BOOST_CHECK(ResolveIP("2002::1").IsRFC3964()); BOOST_CHECK(ResolveIP("FC00::").IsRFC4193()); BOOST_CHECK(ResolveIP("2001::2").IsRFC4380()); BOOST_CHECK(ResolveIP("2001:10::").IsRFC4843()); BOOST_CHECK(ResolveIP("2001:20::").IsRFC7343()); BOOST_CHECK(ResolveIP("FE80::").IsRFC4862()); BOOST_CHECK(ResolveIP("64:FF9B::").IsRFC6052()); BOOST_CHECK(ResolveIP("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion").IsTor()); BOOST_CHECK(ResolveIP("127.0.0.1").IsLocal()); BOOST_CHECK(ResolveIP("::1").IsLocal()); BOOST_CHECK(ResolveIP("8.8.8.8").IsRoutable()); BOOST_CHECK(ResolveIP("2001::1").IsRoutable()); BOOST_CHECK(ResolveIP("127.0.0.1").IsValid()); BOOST_CHECK(CreateInternal("FD6B:88C0:8724:edb1:8e4:3588:e546:35ca").IsInternal()); BOOST_CHECK(CreateInternal("bar.com").IsInternal()); } bool static TestSplitHost(const std::string& test, const std::string& host, uint16_t port, bool validPort=true) { std::string hostOut; uint16_t portOut{0}; bool validPortOut = SplitHostPort(test, portOut, hostOut); return hostOut == host && portOut == port && validPortOut == validPort; } BOOST_AUTO_TEST_CASE(netbase_splithost) { BOOST_CHECK(TestSplitHost("www.bitcoincore.org", "www.bitcoincore.org", 0)); BOOST_CHECK(TestSplitHost("[www.bitcoincore.org]", "www.bitcoincore.org", 0)); BOOST_CHECK(TestSplitHost("www.bitcoincore.org:80", "www.bitcoincore.org", 80)); BOOST_CHECK(TestSplitHost("[www.bitcoincore.org]:80", "www.bitcoincore.org", 80)); BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", 0)); BOOST_CHECK(TestSplitHost("127.0.0.1:8333", "127.0.0.1", 8333)); BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", 0)); BOOST_CHECK(TestSplitHost("[127.0.0.1]:8333", "127.0.0.1", 8333)); BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", 0)); BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:8333", "::ffff:127.0.0.1", 8333)); BOOST_CHECK(TestSplitHost("[::]:8333", "::", 8333)); BOOST_CHECK(TestSplitHost("::8333", "::8333", 0)); BOOST_CHECK(TestSplitHost(":8333", "", 8333)); BOOST_CHECK(TestSplitHost("[]:8333", "", 8333)); BOOST_CHECK(TestSplitHost("", "", 0)); BOOST_CHECK(TestSplitHost(":65535", "", 65535)); BOOST_CHECK(TestSplitHost(":65536", ":65536", 0, false)); BOOST_CHECK(TestSplitHost(":-1", ":-1", 0, false)); BOOST_CHECK(TestSplitHost("[]:70001", "[]:70001", 0, false)); BOOST_CHECK(TestSplitHost("[]:-1", "[]:-1", 0, false)); BOOST_CHECK(TestSplitHost("[]:-0", "[]:-0", 0, false)); BOOST_CHECK(TestSplitHost("[]:0", "", 0, false)); BOOST_CHECK(TestSplitHost("[]:1/2", "[]:1/2", 0, false)); BOOST_CHECK(TestSplitHost("[]:1E2", "[]:1E2", 0, false)); BOOST_CHECK(TestSplitHost("127.0.0.1:65536", "127.0.0.1:65536", 0, false)); BOOST_CHECK(TestSplitHost("127.0.0.1:0", "127.0.0.1", 0, false)); BOOST_CHECK(TestSplitHost("127.0.0.1:", "127.0.0.1:", 0, false)); BOOST_CHECK(TestSplitHost("127.0.0.1:1/2", "127.0.0.1:1/2", 0, false)); BOOST_CHECK(TestSplitHost("127.0.0.1:1E2", "127.0.0.1:1E2", 0, false)); BOOST_CHECK(TestSplitHost("www.bitcoincore.org:65536", "www.bitcoincore.org:65536", 0, false)); BOOST_CHECK(TestSplitHost("www.bitcoincore.org:0", "www.bitcoincore.org", 0, false)); BOOST_CHECK(TestSplitHost("www.bitcoincore.org:", "www.bitcoincore.org:", 0, false)); } bool static TestParse(std::string src, std::string canon) { CService addr(LookupNumeric(src, 65535)); return canon == addr.ToStringAddrPort(); } BOOST_AUTO_TEST_CASE(netbase_lookupnumeric) { BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("127.0.0.1:8333", "127.0.0.1:8333")); BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("::", "[::]:65535")); BOOST_CHECK(TestParse("[::]:8333", "[::]:8333")); BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535")); BOOST_CHECK(TestParse(":::", "[::]:0")); // verify that an internal address fails to resolve BOOST_CHECK(TestParse("[fd6b:88c0:8724:1:2:3:4:5]", "[::]:0")); // and that a one-off resolves correctly BOOST_CHECK(TestParse("[fd6c:88c0:8724:1:2:3:4:5]", "[fd6c:88c0:8724:1:2:3:4:5]:65535")); } BOOST_AUTO_TEST_CASE(embedded_test) { CNetAddr addr1(ResolveIP("1.2.3.4")); CNetAddr addr2(ResolveIP("::FFFF:0102:0304")); BOOST_CHECK(addr2.IsIPv4()); BOOST_CHECK_EQUAL(addr1.ToStringAddr(), addr2.ToStringAddr()); } BOOST_AUTO_TEST_CASE(subnet_test) { BOOST_CHECK(LookupSubNet("1.2.3.0/24") == LookupSubNet("1.2.3.0/255.255.255.0")); BOOST_CHECK(LookupSubNet("1.2.3.0/24") != LookupSubNet("1.2.4.0/255.255.255.0")); BOOST_CHECK(LookupSubNet("1.2.3.0/24").Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(!LookupSubNet("1.2.2.0/24").Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(LookupSubNet("1.2.3.4").Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(LookupSubNet("1.2.3.4/32").Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(!LookupSubNet("1.2.3.4").Match(ResolveIP("5.6.7.8"))); BOOST_CHECK(!LookupSubNet("1.2.3.4/32").Match(ResolveIP("5.6.7.8"))); BOOST_CHECK(LookupSubNet("::ffff:127.0.0.1").Match(ResolveIP("127.0.0.1"))); BOOST_CHECK(LookupSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!LookupSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:9"))); BOOST_CHECK(LookupSubNet("1:2:3:4:5:6:7:0/112").Match(ResolveIP("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(LookupSubNet("192.168.0.1/24").Match(ResolveIP("192.168.0.2"))); BOOST_CHECK(LookupSubNet("192.168.0.20/29").Match(ResolveIP("192.168.0.18"))); BOOST_CHECK(LookupSubNet("1.2.2.1/24").Match(ResolveIP("1.2.2.4"))); BOOST_CHECK(LookupSubNet("1.2.2.110/31").Match(ResolveIP("1.2.2.111"))); BOOST_CHECK(LookupSubNet("1.2.2.20/26").Match(ResolveIP("1.2.2.63"))); // All-Matching IPv6 Matches arbitrary IPv6 BOOST_CHECK(LookupSubNet("::/0").Match(ResolveIP("1:2:3:4:5:6:7:1234"))); // But not `::` or `0.0.0.0` because they are considered invalid addresses BOOST_CHECK(!LookupSubNet("::/0").Match(ResolveIP("::"))); BOOST_CHECK(!LookupSubNet("::/0").Match(ResolveIP("0.0.0.0"))); // Addresses from one network (IPv4) don't belong to subnets of another network (IPv6) BOOST_CHECK(!LookupSubNet("::/0").Match(ResolveIP("1.2.3.4"))); // All-Matching IPv4 does not Match IPv6 BOOST_CHECK(!LookupSubNet("0.0.0.0/0").Match(ResolveIP("1:2:3:4:5:6:7:1234"))); // Invalid subnets Match nothing (not even invalid addresses) BOOST_CHECK(!CSubNet().Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(!LookupSubNet("").Match(ResolveIP("4.5.6.7"))); BOOST_CHECK(!LookupSubNet("bloop").Match(ResolveIP("0.0.0.0"))); BOOST_CHECK(!LookupSubNet("bloop").Match(ResolveIP("hab"))); // Check valid/invalid BOOST_CHECK(LookupSubNet("1.2.3.0/0").IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/-1").IsValid()); BOOST_CHECK(LookupSubNet("1.2.3.0/32").IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/33").IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/300").IsValid()); BOOST_CHECK(LookupSubNet("1:2:3:4:5:6:7:8/0").IsValid()); BOOST_CHECK(LookupSubNet("1:2:3:4:5:6:7:8/33").IsValid()); BOOST_CHECK(!LookupSubNet("1:2:3:4:5:6:7:8/-1").IsValid()); BOOST_CHECK(LookupSubNet("1:2:3:4:5:6:7:8/128").IsValid()); BOOST_CHECK(!LookupSubNet("1:2:3:4:5:6:7:8/129").IsValid()); BOOST_CHECK(!LookupSubNet("fuzzy").IsValid()); //CNetAddr constructor test BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).IsValid()); BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.1"))); BOOST_CHECK(!CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.2"))); BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).ToString() == "127.0.0.1/32"); CSubNet subnet = CSubNet(ResolveIP("1.2.3.4"), 32); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32"); subnet = CSubNet(ResolveIP("1.2.3.4"), 8); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8"); subnet = CSubNet(ResolveIP("1.2.3.4"), 0); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0"); subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.255.255.255")); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32"); subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.0.0.0")); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8"); subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("0.0.0.0")); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0"); BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).IsValid()); BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:9"))); BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128"); // IPv4 address with IPv6 netmask or the other way around. BOOST_CHECK(!CSubNet(ResolveIP("1.1.1.1"), ResolveIP("ffff::")).IsValid()); BOOST_CHECK(!CSubNet(ResolveIP("::1"), ResolveIP("255.0.0.0")).IsValid()); // Create Non-IP subnets. const CNetAddr tor_addr{ ResolveIP("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion")}; subnet = CSubNet(tor_addr); BOOST_CHECK(subnet.IsValid()); BOOST_CHECK_EQUAL(subnet.ToString(), tor_addr.ToStringAddr()); BOOST_CHECK(subnet.Match(tor_addr)); BOOST_CHECK( !subnet.Match(ResolveIP("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion"))); BOOST_CHECK(!subnet.Match(ResolveIP("1.2.3.4"))); BOOST_CHECK(!CSubNet(tor_addr, 200).IsValid()); BOOST_CHECK(!CSubNet(tor_addr, ResolveIP("255.0.0.0")).IsValid()); subnet = LookupSubNet("1.2.3.4/255.255.255.255"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32"); subnet = LookupSubNet("1.2.3.4/255.255.255.254"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31"); subnet = LookupSubNet("1.2.3.4/255.255.255.252"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30"); subnet = LookupSubNet("1.2.3.4/255.255.255.248"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29"); subnet = LookupSubNet("1.2.3.4/255.255.255.240"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28"); subnet = LookupSubNet("1.2.3.4/255.255.255.224"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27"); subnet = LookupSubNet("1.2.3.4/255.255.255.192"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26"); subnet = LookupSubNet("1.2.3.4/255.255.255.128"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25"); subnet = LookupSubNet("1.2.3.4/255.255.255.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24"); subnet = LookupSubNet("1.2.3.4/255.255.254.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23"); subnet = LookupSubNet("1.2.3.4/255.255.252.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22"); subnet = LookupSubNet("1.2.3.4/255.255.248.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21"); subnet = LookupSubNet("1.2.3.4/255.255.240.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20"); subnet = LookupSubNet("1.2.3.4/255.255.224.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19"); subnet = LookupSubNet("1.2.3.4/255.255.192.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18"); subnet = LookupSubNet("1.2.3.4/255.255.128.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17"); subnet = LookupSubNet("1.2.3.4/255.255.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16"); subnet = LookupSubNet("1.2.3.4/255.254.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15"); subnet = LookupSubNet("1.2.3.4/255.252.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14"); subnet = LookupSubNet("1.2.3.4/255.248.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13"); subnet = LookupSubNet("1.2.3.4/255.240.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12"); subnet = LookupSubNet("1.2.3.4/255.224.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11"); subnet = LookupSubNet("1.2.3.4/255.192.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10"); subnet = LookupSubNet("1.2.3.4/255.128.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9"); subnet = LookupSubNet("1.2.3.4/255.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8"); subnet = LookupSubNet("1.2.3.4/254.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7"); subnet = LookupSubNet("1.2.3.4/252.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6"); subnet = LookupSubNet("1.2.3.4/248.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5"); subnet = LookupSubNet("1.2.3.4/240.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4"); subnet = LookupSubNet("1.2.3.4/224.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3"); subnet = LookupSubNet("1.2.3.4/192.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2"); subnet = LookupSubNet("1.2.3.4/128.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1"); subnet = LookupSubNet("1.2.3.4/0.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0"); subnet = LookupSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128"); subnet = LookupSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000"); BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16"); subnet = LookupSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000"); BOOST_CHECK_EQUAL(subnet.ToString(), "::/0"); // Invalid netmasks (with 1-bits after 0-bits) subnet = LookupSubNet("1.2.3.4/255.255.232.0"); BOOST_CHECK(!subnet.IsValid()); subnet = LookupSubNet("1.2.3.4/255.0.255.255"); BOOST_CHECK(!subnet.IsValid()); subnet = LookupSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f"); BOOST_CHECK(!subnet.IsValid()); } BOOST_AUTO_TEST_CASE(netbase_getgroup) { NetGroupManager netgroupman{std::vector<bool>()}; // use /16 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("127.0.0.1")) == std::vector<unsigned char>({0})); // Local -> !Routable() BOOST_CHECK(netgroupman.GetGroup(ResolveIP("257.0.0.1")) == std::vector<unsigned char>({0})); // !Valid -> !Routable() BOOST_CHECK(netgroupman.GetGroup(ResolveIP("10.0.0.1")) == std::vector<unsigned char>({0})); // RFC1918 -> !Routable() BOOST_CHECK(netgroupman.GetGroup(ResolveIP("169.254.1.1")) == std::vector<unsigned char>({0})); // RFC3927 -> !Routable() BOOST_CHECK(netgroupman.GetGroup(ResolveIP("1.2.3.4")) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // IPv4 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("::FFFF:0:102:304")) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC6145 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("64:FF9B::102:304")) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC6052 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("2002:102:304:9999:9999:9999:9999:9999")) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC3964 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("2001:0:9999:9999:9999:9999:FEFD:FCFB")) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC4380 BOOST_CHECK(netgroupman.GetGroup(ResolveIP("2001:470:abcd:9999:9999:9999:9999:9999")) == std::vector<unsigned char>({(unsigned char)NET_IPV6, 32, 1, 4, 112, 175})); //he.net BOOST_CHECK(netgroupman.GetGroup(ResolveIP("2001:2001:9999:9999:9999:9999:9999:9999")) == std::vector<unsigned char>({(unsigned char)NET_IPV6, 32, 1, 32, 1})); //IPv6 // baz.net sha256 hash: 12929400eb4607c4ac075f087167e75286b179c693eb059a01774b864e8fe505 std::vector<unsigned char> internal_group = {NET_INTERNAL, 0x12, 0x92, 0x94, 0x00, 0xeb, 0x46, 0x07, 0xc4, 0xac, 0x07}; BOOST_CHECK(netgroupman.GetGroup(CreateInternal("baz.net")) == internal_group); } BOOST_AUTO_TEST_CASE(netbase_parsenetwork) { BOOST_CHECK_EQUAL(ParseNetwork("ipv4"), NET_IPV4); BOOST_CHECK_EQUAL(ParseNetwork("ipv6"), NET_IPV6); BOOST_CHECK_EQUAL(ParseNetwork("onion"), NET_ONION); BOOST_CHECK_EQUAL(ParseNetwork("tor"), NET_ONION); BOOST_CHECK_EQUAL(ParseNetwork("cjdns"), NET_CJDNS); BOOST_CHECK_EQUAL(ParseNetwork("IPv4"), NET_IPV4); BOOST_CHECK_EQUAL(ParseNetwork("IPv6"), NET_IPV6); BOOST_CHECK_EQUAL(ParseNetwork("ONION"), NET_ONION); BOOST_CHECK_EQUAL(ParseNetwork("TOR"), NET_ONION); BOOST_CHECK_EQUAL(ParseNetwork("CJDNS"), NET_CJDNS); BOOST_CHECK_EQUAL(ParseNetwork(":)"), NET_UNROUTABLE); BOOST_CHECK_EQUAL(ParseNetwork("tÖr"), NET_UNROUTABLE); BOOST_CHECK_EQUAL(ParseNetwork("\xfe\xff"), NET_UNROUTABLE); BOOST_CHECK_EQUAL(ParseNetwork(""), NET_UNROUTABLE); } BOOST_AUTO_TEST_CASE(netpermissions_test) { bilingual_str error; NetWhitebindPermissions whitebindPermissions; NetWhitelistPermissions whitelistPermissions; // Detect invalid white bind BOOST_CHECK(!NetWhitebindPermissions::TryParse("", whitebindPermissions, error)); BOOST_CHECK(error.original.find("Cannot resolve -whitebind address") != std::string::npos); BOOST_CHECK(!NetWhitebindPermissions::TryParse("127.0.0.1", whitebindPermissions, error)); BOOST_CHECK(error.original.find("Need to specify a port with -whitebind") != std::string::npos); BOOST_CHECK(!NetWhitebindPermissions::TryParse("", whitebindPermissions, error)); // If no permission flags, assume backward compatibility BOOST_CHECK(NetWhitebindPermissions::TryParse("1.2.3.4:32", whitebindPermissions, error)); BOOST_CHECK(error.empty()); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::Implicit); BOOST_CHECK(NetPermissions::HasFlag(whitebindPermissions.m_flags, NetPermissionFlags::Implicit)); NetPermissions::ClearFlag(whitebindPermissions.m_flags, NetPermissionFlags::Implicit); BOOST_CHECK(!NetPermissions::HasFlag(whitebindPermissions.m_flags, NetPermissionFlags::Implicit)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::None); NetPermissions::AddFlag(whitebindPermissions.m_flags, NetPermissionFlags::Implicit); BOOST_CHECK(NetPermissions::HasFlag(whitebindPermissions.m_flags, NetPermissionFlags::Implicit)); // Can set one permission BOOST_CHECK(NetWhitebindPermissions::TryParse("[email protected]:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::BloomFilter); BOOST_CHECK(NetWhitebindPermissions::TryParse("@1.2.3.4:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::None); NetWhitebindPermissions noban, noban_download, download_noban, download; // "noban" implies "download" BOOST_REQUIRE(NetWhitebindPermissions::TryParse("[email protected]:32", noban, error)); BOOST_CHECK_EQUAL(noban.m_flags, NetPermissionFlags::NoBan); BOOST_CHECK(NetPermissions::HasFlag(noban.m_flags, NetPermissionFlags::Download)); BOOST_CHECK(NetPermissions::HasFlag(noban.m_flags, NetPermissionFlags::NoBan)); // "noban,download" is equivalent to "noban" BOOST_REQUIRE(NetWhitebindPermissions::TryParse("noban,[email protected]:32", noban_download, error)); BOOST_CHECK_EQUAL(noban_download.m_flags, noban.m_flags); // "download,noban" is equivalent to "noban" BOOST_REQUIRE(NetWhitebindPermissions::TryParse("download,[email protected]:32", download_noban, error)); BOOST_CHECK_EQUAL(download_noban.m_flags, noban.m_flags); // "download" excludes (does not imply) "noban" BOOST_REQUIRE(NetWhitebindPermissions::TryParse("[email protected]:32", download, error)); BOOST_CHECK_EQUAL(download.m_flags, NetPermissionFlags::Download); BOOST_CHECK(NetPermissions::HasFlag(download.m_flags, NetPermissionFlags::Download)); BOOST_CHECK(!NetPermissions::HasFlag(download.m_flags, NetPermissionFlags::NoBan)); // Happy path, can parse flags BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,[email protected]:32", whitebindPermissions, error)); // forcerelay should also activate the relay permission BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::BloomFilter | NetPermissionFlags::ForceRelay | NetPermissionFlags::Relay); BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,[email protected]:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::BloomFilter | NetPermissionFlags::Relay | NetPermissionFlags::NoBan); BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,forcerelay,[email protected]:32", whitebindPermissions, error)); BOOST_CHECK(NetWhitebindPermissions::TryParse("[email protected]:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::All); // Allow dups BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,noban,[email protected]:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::BloomFilter | NetPermissionFlags::Relay | NetPermissionFlags::NoBan | NetPermissionFlags::Download); // "noban" implies "download" // Allow empty BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,,[email protected]:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::BloomFilter | NetPermissionFlags::Relay | NetPermissionFlags::NoBan); BOOST_CHECK(NetWhitebindPermissions::TryParse(",@1.2.3.4:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::None); BOOST_CHECK(NetWhitebindPermissions::TryParse(",,@1.2.3.4:32", whitebindPermissions, error)); BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, NetPermissionFlags::None); // Detect invalid flag BOOST_CHECK(!NetWhitebindPermissions::TryParse("bloom,forcerelay,[email protected]:32", whitebindPermissions, error)); BOOST_CHECK(error.original.find("Invalid P2P permission") != std::string::npos); // Check netmask error BOOST_CHECK(!NetWhitelistPermissions::TryParse("bloom,forcerelay,[email protected]:32", whitelistPermissions, error)); BOOST_CHECK(error.original.find("Invalid netmask specified in -whitelist") != std::string::npos); // Happy path for whitelist parsing BOOST_CHECK(NetWhitelistPermissions::TryParse("[email protected]", whitelistPermissions, error)); BOOST_CHECK_EQUAL(whitelistPermissions.m_flags, NetPermissionFlags::NoBan); BOOST_CHECK(NetPermissions::HasFlag(whitelistPermissions.m_flags, NetPermissionFlags::NoBan)); BOOST_CHECK(NetWhitelistPermissions::TryParse("bloom,forcerelay,noban,[email protected]/32", whitelistPermissions, error)); BOOST_CHECK_EQUAL(whitelistPermissions.m_flags, NetPermissionFlags::BloomFilter | NetPermissionFlags::ForceRelay | NetPermissionFlags::NoBan | NetPermissionFlags::Relay); BOOST_CHECK(error.empty()); BOOST_CHECK_EQUAL(whitelistPermissions.m_subnet.ToString(), "1.2.3.4/32"); BOOST_CHECK(NetWhitelistPermissions::TryParse("bloom,forcerelay,noban,relay,[email protected]/32", whitelistPermissions, error)); const auto strings = NetPermissions::ToStrings(NetPermissionFlags::All); BOOST_CHECK_EQUAL(strings.size(), 7U); BOOST_CHECK(std::find(strings.begin(), strings.end(), "bloomfilter") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "forcerelay") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "relay") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "noban") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "mempool") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "download") != strings.end()); BOOST_CHECK(std::find(strings.begin(), strings.end(), "addr") != strings.end()); } BOOST_AUTO_TEST_CASE(netbase_dont_resolve_strings_with_embedded_nul_characters) { BOOST_CHECK(LookupHost("127.0.0.1"s, false).has_value()); BOOST_CHECK(!LookupHost("127.0.0.1\0"s, false).has_value()); BOOST_CHECK(!LookupHost("127.0.0.1\0example.com"s, false).has_value()); BOOST_CHECK(!LookupHost("127.0.0.1\0example.com\0"s, false).has_value()); BOOST_CHECK(LookupSubNet("1.2.3.0/24"s).IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/24\0"s).IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/24\0example.com"s).IsValid()); BOOST_CHECK(!LookupSubNet("1.2.3.0/24\0example.com\0"s).IsValid()); BOOST_CHECK(LookupSubNet("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"s).IsValid()); BOOST_CHECK(!LookupSubNet("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion\0"s).IsValid()); BOOST_CHECK(!LookupSubNet("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion\0example.com"s).IsValid()); BOOST_CHECK(!LookupSubNet("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion\0example.com\0"s).IsValid()); } // Since CNetAddr (un)ser is tested separately in net_tests.cpp here we only // try a few edge cases for port, service flags and time. static const std::vector<CAddress> fixture_addresses({ CAddress{ CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0 /* port */), NODE_NONE, NodeSeconds{0x4966bc61s}, /* Fri Jan 9 02:54:25 UTC 2009 */ }, CAddress{ CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0x00f1 /* port */), NODE_NETWORK, NodeSeconds{0x83766279s}, /* Tue Nov 22 11:22:33 UTC 2039 */ }, CAddress{ CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0xf1f2 /* port */), static_cast<ServiceFlags>(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED), NodeSeconds{0xffffffffs}, /* Sun Feb 7 06:28:15 UTC 2106 */ }, }); // fixture_addresses should equal to this when serialized in V1 format. // When this is unserialized from V1 format it should equal to fixture_addresses. static constexpr const char* stream_addrv1_hex = "03" // number of entries "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 "0000000000000000" // service flags, NODE_NONE "00000000000000000000000000000001" // address, fixed 16 bytes (IPv4 embedded in IPv6) "0000" // port "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 "0100000000000000" // service flags, NODE_NETWORK "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) "00f1" // port "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 "4804000000000000" // service flags, NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) "f1f2"; // port // fixture_addresses should equal to this when serialized in V2 format. // When this is unserialized from V2 format it should equal to fixture_addresses. static constexpr const char* stream_addrv2_hex = "03" // number of entries "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 "00" // service flags, COMPACTSIZE(NODE_NONE) "02" // network id, IPv6 "10" // address length, COMPACTSIZE(16) "00000000000000000000000000000001" // address "0000" // port "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 "01" // service flags, COMPACTSIZE(NODE_NETWORK) "02" // network id, IPv6 "10" // address length, COMPACTSIZE(16) "00000000000000000000000000000001" // address "00f1" // port "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 "fd4804" // service flags, COMPACTSIZE(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED) "02" // network id, IPv6 "10" // address length, COMPACTSIZE(16) "00000000000000000000000000000001" // address "f1f2"; // port BOOST_AUTO_TEST_CASE(caddress_serialize_v1) { DataStream s{}; s << CAddress::V1_NETWORK(fixture_addresses); BOOST_CHECK_EQUAL(HexStr(s), stream_addrv1_hex); } BOOST_AUTO_TEST_CASE(caddress_unserialize_v1) { DataStream s{ParseHex(stream_addrv1_hex)}; std::vector<CAddress> addresses_unserialized; s >> CAddress::V1_NETWORK(addresses_unserialized); BOOST_CHECK(fixture_addresses == addresses_unserialized); } BOOST_AUTO_TEST_CASE(caddress_serialize_v2) { DataStream s{}; s << CAddress::V2_NETWORK(fixture_addresses); BOOST_CHECK_EQUAL(HexStr(s), stream_addrv2_hex); } BOOST_AUTO_TEST_CASE(caddress_unserialize_v2) { DataStream s{ParseHex(stream_addrv2_hex)}; std::vector<CAddress> addresses_unserialized; s >> CAddress::V2_NETWORK(addresses_unserialized); BOOST_CHECK(fixture_addresses == addresses_unserialized); } BOOST_AUTO_TEST_CASE(isbadport) { BOOST_CHECK(IsBadPort(1)); BOOST_CHECK(IsBadPort(22)); BOOST_CHECK(IsBadPort(6000)); BOOST_CHECK(!IsBadPort(80)); BOOST_CHECK(!IsBadPort(443)); BOOST_CHECK(!IsBadPort(8333)); // Check all ports, there must be 80 bad ports in total. size_t total_bad_ports{0}; for (uint16_t port = std::numeric_limits<uint16_t>::max(); port > 0; --port) { if (IsBadPort(port)) { ++total_bad_ports; } } BOOST_CHECK_EQUAL(total_bad_ports, 80); } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src
bitcoin/src/test/key_io_tests.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/data/key_io_invalid.json.h> #include <test/data/key_io_valid.json.h> #include <key.h> #include <key_io.h> #include <script/script.h> #include <test/util/json.h> #include <test/util/setup_common.h> #include <util/chaintype.h> #include <util/strencodings.h> #include <boost/test/unit_test.hpp> #include <univalue.h> BOOST_FIXTURE_TEST_SUITE(key_io_tests, BasicTestingSetup) // Goal: check that parsed keys match test payload BOOST_AUTO_TEST_CASE(key_io_valid_parse) { UniValue tests = read_json(json_tests::key_io_valid); CKey privkey; CTxDestination destination; SelectParams(ChainType::MAIN); for (unsigned int idx = 0; idx < tests.size(); idx++) { const UniValue& test = tests[idx]; std::string strTest = test.write(); if (test.size() < 3) { // Allow for extra stuff (useful for comments) BOOST_ERROR("Bad test: " << strTest); continue; } std::string exp_base58string = test[0].get_str(); const std::vector<std::byte> exp_payload{ParseHex<std::byte>(test[1].get_str())}; const UniValue &metadata = test[2].get_obj(); bool isPrivkey = metadata.find_value("isPrivkey").get_bool(); SelectParams(ChainTypeFromString(metadata.find_value("chain").get_str()).value()); bool try_case_flip = metadata.find_value("tryCaseFlip").isNull() ? false : metadata.find_value("tryCaseFlip").get_bool(); if (isPrivkey) { bool isCompressed = metadata.find_value("isCompressed").get_bool(); // Must be valid private key privkey = DecodeSecret(exp_base58string); BOOST_CHECK_MESSAGE(privkey.IsValid(), "!IsValid:" + strTest); BOOST_CHECK_MESSAGE(privkey.IsCompressed() == isCompressed, "compressed mismatch:" + strTest); BOOST_CHECK_MESSAGE(Span{privkey} == Span{exp_payload}, "key mismatch:" + strTest); // Private key must be invalid public key destination = DecodeDestination(exp_base58string); BOOST_CHECK_MESSAGE(!IsValidDestination(destination), "IsValid privkey as pubkey:" + strTest); } else { // Must be valid public key destination = DecodeDestination(exp_base58string); CScript script = GetScriptForDestination(destination); BOOST_CHECK_MESSAGE(IsValidDestination(destination), "!IsValid:" + strTest); BOOST_CHECK_EQUAL(HexStr(script), HexStr(exp_payload)); // Try flipped case version for (char& c : exp_base58string) { if (c >= 'a' && c <= 'z') { c = (c - 'a') + 'A'; } else if (c >= 'A' && c <= 'Z') { c = (c - 'A') + 'a'; } } destination = DecodeDestination(exp_base58string); BOOST_CHECK_MESSAGE(IsValidDestination(destination) == try_case_flip, "!IsValid case flipped:" + strTest); if (IsValidDestination(destination)) { script = GetScriptForDestination(destination); BOOST_CHECK_EQUAL(HexStr(script), HexStr(exp_payload)); } // Public key must be invalid private key privkey = DecodeSecret(exp_base58string); BOOST_CHECK_MESSAGE(!privkey.IsValid(), "IsValid pubkey as privkey:" + strTest); } } } // Goal: check that generated keys match test vectors BOOST_AUTO_TEST_CASE(key_io_valid_gen) { UniValue tests = read_json(json_tests::key_io_valid); for (unsigned int idx = 0; idx < tests.size(); idx++) { const UniValue& test = tests[idx]; std::string strTest = test.write(); if (test.size() < 3) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } std::string exp_base58string = test[0].get_str(); std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str()); const UniValue &metadata = test[2].get_obj(); bool isPrivkey = metadata.find_value("isPrivkey").get_bool(); SelectParams(ChainTypeFromString(metadata.find_value("chain").get_str()).value()); if (isPrivkey) { bool isCompressed = metadata.find_value("isCompressed").get_bool(); CKey key; key.Set(exp_payload.begin(), exp_payload.end(), isCompressed); assert(key.IsValid()); BOOST_CHECK_MESSAGE(EncodeSecret(key) == exp_base58string, "result mismatch: " + strTest); } else { CTxDestination dest; CScript exp_script(exp_payload.begin(), exp_payload.end()); BOOST_CHECK(ExtractDestination(exp_script, dest)); std::string address = EncodeDestination(dest); BOOST_CHECK_EQUAL(address, exp_base58string); } } SelectParams(ChainType::MAIN); } // Goal: check that base58 parsing code is robust against a variety of corrupted data BOOST_AUTO_TEST_CASE(key_io_invalid) { UniValue tests = read_json(json_tests::key_io_invalid); // Negative testcases CKey privkey; CTxDestination destination; for (unsigned int idx = 0; idx < tests.size(); idx++) { const UniValue& test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } std::string exp_base58string = test[0].get_str(); // must be invalid as public and as private key for (const auto& chain : {ChainType::MAIN, ChainType::TESTNET, ChainType::SIGNET, ChainType::REGTEST}) { SelectParams(chain); destination = DecodeDestination(exp_base58string); BOOST_CHECK_MESSAGE(!IsValidDestination(destination), "IsValid pubkey in mainnet:" + strTest); privkey = DecodeSecret(exp_base58string); BOOST_CHECK_MESSAGE(!privkey.IsValid(), "IsValid privkey in mainnet:" + strTest); } } } BOOST_AUTO_TEST_SUITE_END()
0
bitcoin/src/test
bitcoin/src/test/util/transaction_utils.h
// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_TRANSACTION_UTILS_H #define BITCOIN_TEST_UTIL_TRANSACTION_UTILS_H #include <primitives/transaction.h> #include <array> class FillableSigningProvider; class CCoinsViewCache; // create crediting transaction // [1 coinbase input => 1 output with given scriptPubkey and value] CMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey, int nValue = 0); // create spending transaction // [1 input with referenced transaction outpoint, scriptSig, scriptWitness => // 1 output with empty scriptPubKey, full value of referenced transaction] CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CScriptWitness& scriptWitness, const CTransaction& txCredit); // Helper: create two dummy transactions, each with two outputs. // The first has nValues[0] and nValues[1] outputs paid to a TxoutType::PUBKEY, // the second nValues[2] and nValues[3] outputs paid to a TxoutType::PUBKEYHASH. std::vector<CMutableTransaction> SetupDummyInputs(FillableSigningProvider& keystoreRet, CCoinsViewCache& coinsRet, const std::array<CAmount,4>& nValues); #endif // BITCOIN_TEST_UTIL_TRANSACTION_UTILS_H
0
bitcoin/src/test
bitcoin/src/test/util/index.h
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_INDEX_H #define BITCOIN_TEST_UTIL_INDEX_H class BaseIndex; namespace util { class SignalInterrupt; } // namespace util /** Block until the index is synced to the current chain */ void IndexWaitSynced(const BaseIndex& index, const util::SignalInterrupt& interrupt); #endif // BITCOIN_TEST_UTIL_INDEX_H
0
bitcoin/src/test
bitcoin/src/test/util/mining.cpp
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/mining.h> #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <key_io.h> #include <node/context.h> #include <pow.h> #include <primitives/transaction.h> #include <test/util/script.h> #include <util/check.h> #include <validation.h> #include <validationinterface.h> #include <versionbits.h> using node::BlockAssembler; using node::NodeContext; COutPoint generatetoaddress(const NodeContext& node, const std::string& address) { const auto dest = DecodeDestination(address); assert(IsValidDestination(dest)); const auto coinbase_script = GetScriptForDestination(dest); return MineBlock(node, coinbase_script); } std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params) { std::vector<std::shared_ptr<CBlock>> ret{total_height}; auto time{params.GenesisBlock().nTime}; for (size_t height{0}; height < total_height; ++height) { CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())}; CMutableTransaction coinbase_tx; coinbase_tx.vin.resize(1); coinbase_tx.vin[0].prevout.SetNull(); coinbase_tx.vout.resize(1); coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE; coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus()); coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0; block.vtx = {MakeTransactionRef(std::move(coinbase_tx))}; block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION; block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash(); block.hashMerkleRoot = BlockMerkleRoot(block); block.nTime = ++time; block.nBits = params.GenesisBlock().nBits; block.nNonce = 0; while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) { ++block.nNonce; assert(block.nNonce); } } return ret; } COutPoint MineBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey) { auto block = PrepareBlock(node, coinbase_scriptPubKey); auto valid = MineBlock(node, block); assert(!valid.IsNull()); return valid; } struct BlockValidationStateCatcher : public CValidationInterface { const uint256 m_hash; std::optional<BlockValidationState> m_state; BlockValidationStateCatcher(const uint256& hash) : m_hash{hash}, m_state{} {} protected: void BlockChecked(const CBlock& block, const BlockValidationState& state) override { if (block.GetHash() != m_hash) return; m_state = state; } }; COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block) { while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) { ++block->nNonce; assert(block->nNonce); } auto& chainman{*Assert(node.chainman)}; const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()); bool new_block; BlockValidationStateCatcher bvsc{block->GetHash()}; RegisterValidationInterface(&bvsc); const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)}; const bool duplicate{!new_block && processed}; assert(!duplicate); UnregisterValidationInterface(&bvsc); SyncWithValidationInterfaceQueue(); const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()}; assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight())); if (was_valid) return {block->vtx[0]->GetHash(), 0}; return {}; } std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey, const BlockAssembler::Options& assembler_options) { auto block = std::make_shared<CBlock>( BlockAssembler{Assert(node.chainman)->ActiveChainstate(), Assert(node.mempool.get()), assembler_options} .CreateNewBlock(coinbase_scriptPubKey) ->block); LOCK(cs_main); block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1; block->hashMerkleRoot = BlockMerkleRoot(*block); return block; } std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey) { BlockAssembler::Options assembler_options; ApplyArgsManOptions(*node.args, assembler_options); return PrepareBlock(node, coinbase_scriptPubKey, assembler_options); }
0
bitcoin/src/test
bitcoin/src/test/util/validation.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/validation.h> #include <util/check.h> #include <util/time.h> #include <validation.h> #include <validationinterface.h> void TestChainstateManager::ResetIbd() { m_cached_finished_ibd = false; assert(IsInitialBlockDownload()); } void TestChainstateManager::JumpOutOfIbd() { Assert(IsInitialBlockDownload()); m_cached_finished_ibd = true; Assert(!IsInitialBlockDownload()); } void ValidationInterfaceTest::BlockConnected( ChainstateRole role, CValidationInterface& obj, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) { obj.BlockConnected(role, block, pindex); }
0
bitcoin/src/test
bitcoin/src/test/util/blockfilter.h
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_BLOCKFILTER_H #define BITCOIN_TEST_UTIL_BLOCKFILTER_H #include <blockfilter.h> class CBlockIndex; namespace node { class BlockManager; } bool ComputeFilter(BlockFilterType filter_type, const CBlockIndex& block_index, BlockFilter& filter, const node::BlockManager& blockman); #endif // BITCOIN_TEST_UTIL_BLOCKFILTER_H
0
bitcoin/src/test
bitcoin/src/test/util/script.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_SCRIPT_H #define BITCOIN_TEST_UTIL_SCRIPT_H #include <crypto/sha256.h> #include <script/script.h> static const std::vector<uint8_t> WITNESS_STACK_ELEM_OP_TRUE{uint8_t{OP_TRUE}}; static const CScript P2WSH_OP_TRUE{ CScript{} << OP_0 << ToByteVector([] { uint256 hash; CSHA256().Write(WITNESS_STACK_ELEM_OP_TRUE.data(), WITNESS_STACK_ELEM_OP_TRUE.size()).Finalize(hash.begin()); return hash; }())}; static const std::vector<uint8_t> EMPTY{}; static const CScript P2WSH_EMPTY{ CScript{} << OP_0 << ToByteVector([] { uint256 hash; CSHA256().Write(EMPTY.data(), EMPTY.size()).Finalize(hash.begin()); return hash; }())}; static const std::vector<std::vector<uint8_t>> P2WSH_EMPTY_TRUE_STACK{{static_cast<uint8_t>(OP_TRUE)}, {}}; static const std::vector<std::vector<uint8_t>> P2WSH_EMPTY_TWO_STACK{{static_cast<uint8_t>(OP_2)}, {}}; /** Flags that are not forbidden by an assert in script validation */ bool IsValidFlagCombination(unsigned flags); #endif // BITCOIN_TEST_UTIL_SCRIPT_H
0
bitcoin/src/test
bitcoin/src/test/util/coins.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/coins.h> #include <coins.h> #include <primitives/transaction.h> #include <script/script.h> #include <test/util/random.h> #include <uint256.h> #include <stdint.h> #include <utility> COutPoint AddTestCoin(CCoinsViewCache& coins_view) { Coin new_coin; COutPoint outpoint{Txid::FromUint256(InsecureRand256()), /*nIn=*/0}; new_coin.nHeight = 1; new_coin.out.nValue = InsecureRandMoneyAmount(); new_coin.out.scriptPubKey.assign(uint32_t{56}, 1); coins_view.AddCoin(outpoint, std::move(new_coin), /*possible_overwrite=*/false); return outpoint; };
0
bitcoin/src/test
bitcoin/src/test/util/net.h
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_NET_H #define BITCOIN_TEST_UTIL_NET_H #include <compat/compat.h> #include <net.h> #include <net_permissions.h> #include <net_processing.h> #include <netaddress.h> #include <node/connection_types.h> #include <node/eviction.h> #include <sync.h> #include <util/sock.h> #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <cstdint> #include <cstring> #include <memory> #include <string> #include <unordered_map> #include <vector> class FastRandomContext; template <typename C> class Span; struct ConnmanTestMsg : public CConnman { using CConnman::CConnman; void SetPeerConnectTimeout(std::chrono::seconds timeout) { m_peer_connect_timeout = timeout; } std::vector<CNode*> TestNodes() { LOCK(m_nodes_mutex); return m_nodes; } void AddTestNode(CNode& node) { LOCK(m_nodes_mutex); m_nodes.push_back(&node); if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()]; } void ClearTestNodes() { LOCK(m_nodes_mutex); for (CNode* node : m_nodes) { delete node; } m_nodes.clear(); } void Handshake(CNode& node, bool successfully_connected, ServiceFlags remote_services, ServiceFlags local_services, int32_t version, bool relay_txs) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex); bool ProcessMessagesOnce(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) { return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc); } void NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const; bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const; void FlushSendBuffer(CNode& node) const; bool AlreadyConnectedPublic(const CAddress& addr) { return AlreadyConnectedToAddress(addr); }; CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex); }; constexpr ServiceFlags ALL_SERVICE_FLAGS[]{ NODE_NONE, NODE_NETWORK, NODE_BLOOM, NODE_WITNESS, NODE_COMPACT_FILTERS, NODE_NETWORK_LIMITED, NODE_P2P_V2, }; constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]{ NetPermissionFlags::None, NetPermissionFlags::BloomFilter, NetPermissionFlags::Relay, NetPermissionFlags::ForceRelay, NetPermissionFlags::NoBan, NetPermissionFlags::Mempool, NetPermissionFlags::Addr, NetPermissionFlags::Download, NetPermissionFlags::Implicit, NetPermissionFlags::All, }; constexpr ConnectionType ALL_CONNECTION_TYPES[]{ ConnectionType::INBOUND, ConnectionType::OUTBOUND_FULL_RELAY, ConnectionType::MANUAL, ConnectionType::FEELER, ConnectionType::BLOCK_RELAY, ConnectionType::ADDR_FETCH, }; constexpr auto ALL_NETWORKS = std::array{ Network::NET_UNROUTABLE, Network::NET_IPV4, Network::NET_IPV6, Network::NET_ONION, Network::NET_I2P, Network::NET_CJDNS, Network::NET_INTERNAL, }; /** * A mocked Sock alternative that returns a statically contained data upon read and succeeds * and ignores all writes. The data to be returned is given to the constructor and when it is * exhausted an EOF is returned by further reads. */ class StaticContentsSock : public Sock { public: explicit StaticContentsSock(const std::string& contents) : Sock{INVALID_SOCKET}, m_contents{contents} { } ~StaticContentsSock() override { m_socket = INVALID_SOCKET; } StaticContentsSock& operator=(Sock&& other) override { assert(false && "Move of Sock into MockSock not allowed."); return *this; } ssize_t Send(const void*, size_t len, int) const override { return len; } ssize_t Recv(void* buf, size_t len, int flags) const override { const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)}; std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes); if ((flags & MSG_PEEK) == 0) { m_consumed += consume_bytes; } return consume_bytes; } int Connect(const sockaddr*, socklen_t) const override { return 0; } int Bind(const sockaddr*, socklen_t) const override { return 0; } int Listen(int) const override { return 0; } std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override { if (addr != nullptr) { // Pretend all connections come from 5.5.5.5:6789 memset(addr, 0x00, *addr_len); const socklen_t write_len = static_cast<socklen_t>(sizeof(sockaddr_in)); if (*addr_len >= write_len) { *addr_len = write_len; sockaddr_in* addr_in = reinterpret_cast<sockaddr_in*>(addr); addr_in->sin_family = AF_INET; memset(&addr_in->sin_addr, 0x05, sizeof(addr_in->sin_addr)); addr_in->sin_port = htons(6789); } } return std::make_unique<StaticContentsSock>(""); }; int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override { std::memset(opt_val, 0x0, *opt_len); return 0; } int SetSockOpt(int, int, const void*, socklen_t) const override { return 0; } int GetSockName(sockaddr* name, socklen_t* name_len) const override { std::memset(name, 0x0, *name_len); return 0; } bool SetNonBlocking() const override { return true; } bool IsSelectable() const override { return true; } bool Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred = nullptr) const override { if (occurred != nullptr) { *occurred = requested; } return true; } bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override { for (auto& [sock, events] : events_per_sock) { (void)sock; events.occurred = events.requested; } return true; } bool IsConnected(std::string&) const override { return true; } private: const std::string m_contents; mutable size_t m_consumed{0}; }; std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context); #endif // BITCOIN_TEST_UTIL_NET_H
0
bitcoin/src/test
bitcoin/src/test/util/logging.cpp
// Copyright (c) 2019-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/logging.h> #include <logging.h> #include <noui.h> #include <tinyformat.h> #include <stdexcept> DebugLogHelper::DebugLogHelper(std::string message, MatchFn match) : m_message{std::move(message)}, m_match(std::move(match)) { m_print_connection = LogInstance().PushBackCallback( [this](const std::string& s) { if (m_found) return; m_found = s.find(m_message) != std::string::npos && m_match(&s); }); noui_test_redirect(); } void DebugLogHelper::check_found() { noui_reconnect(); LogInstance().DeleteCallback(m_print_connection); if (!m_found && m_match(nullptr)) { throw std::runtime_error(strprintf("'%s' not found in debug log\n", m_message)); } }
0
bitcoin/src/test
bitcoin/src/test/util/mining.h
// Copyright (c) 2019-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_MINING_H #define BITCOIN_TEST_UTIL_MINING_H #include <node/miner.h> #include <memory> #include <string> #include <vector> class CBlock; class CChainParams; class COutPoint; class CScript; namespace node { struct NodeContext; } // namespace node /** Create a blockchain, starting from genesis */ std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params); /** Returns the generated coin */ COutPoint MineBlock(const node::NodeContext&, const CScript& coinbase_scriptPubKey); /** * Returns the generated coin (or Null if the block was invalid). * It is recommended to call RegenerateCommitments before mining the block to avoid merkle tree mismatches. **/ COutPoint MineBlock(const node::NodeContext&, std::shared_ptr<CBlock>& block); /** Prepare a block to be mined */ std::shared_ptr<CBlock> PrepareBlock(const node::NodeContext&, const CScript& coinbase_scriptPubKey); std::shared_ptr<CBlock> PrepareBlock(const node::NodeContext& node, const CScript& coinbase_scriptPubKey, const node::BlockAssembler::Options& assembler_options); /** RPC-like helper function, returns the generated coin */ COutPoint generatetoaddress(const node::NodeContext&, const std::string& address); #endif // BITCOIN_TEST_UTIL_MINING_H
0
bitcoin/src/test
bitcoin/src/test/util/script.cpp
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/interpreter.h> #include <test/util/script.h> bool IsValidFlagCombination(unsigned flags) { if (flags & SCRIPT_VERIFY_CLEANSTACK && ~flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) return false; if (flags & SCRIPT_VERIFY_WITNESS && ~flags & SCRIPT_VERIFY_P2SH) return false; return true; }
0
bitcoin/src/test
bitcoin/src/test/util/random.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/random.h> #include <logging.h> #include <random.h> #include <uint256.h> #include <cstdlib> #include <string> FastRandomContext g_insecure_rand_ctx; /** Return the unsigned from the environment var if available, otherwise 0 */ static uint256 GetUintFromEnv(const std::string& env_name) { const char* num = std::getenv(env_name.c_str()); if (!num) return {}; return uint256S(num); } void Seed(FastRandomContext& ctx) { // Should be enough to get the seed once for the process static uint256 seed{}; static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"}; if (seed.IsNull()) seed = GetUintFromEnv(RANDOM_CTX_SEED); if (seed.IsNull()) seed = GetRandHash(); LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex()); ctx = FastRandomContext(seed); }
0
bitcoin/src/test
bitcoin/src/test/util/poolresourcetester.h
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_POOLRESOURCETESTER_H #define BITCOIN_TEST_UTIL_POOLRESOURCETESTER_H #include <support/allocators/pool.h> #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <vector> /** * Helper to get access to private parts of PoolResource. Used in unit tests and in the fuzzer */ class PoolResourceTester { struct PtrAndBytes { uintptr_t ptr; std::size_t size; PtrAndBytes(const void* p, std::size_t s) : ptr(reinterpret_cast<uintptr_t>(p)), size(s) { } /** * defines a sort ordering by the pointer value */ friend bool operator<(PtrAndBytes const& a, PtrAndBytes const& b) { return a.ptr < b.ptr; } }; public: /** * Extracts the number of elements per freelist */ template <std::size_t MAX_BLOCK_SIZE_BYTES, std::size_t ALIGN_BYTES> static std::vector<std::size_t> FreeListSizes(const PoolResource<MAX_BLOCK_SIZE_BYTES, ALIGN_BYTES>& resource) { auto sizes = std::vector<std::size_t>(); for (const auto* ptr : resource.m_free_lists) { size_t size = 0; while (ptr != nullptr) { ++size; ptr = ptr->m_next; } sizes.push_back(size); } return sizes; } /** * How many bytes are still available from the last allocated chunk */ template <std::size_t MAX_BLOCK_SIZE_BYTES, std::size_t ALIGN_BYTES> static std::size_t AvailableMemoryFromChunk(const PoolResource<MAX_BLOCK_SIZE_BYTES, ALIGN_BYTES>& resource) { return resource.m_available_memory_end - resource.m_available_memory_it; } /** * Once all blocks are given back to the resource, tests that the freelists are consistent: * * * All data in the freelists must come from the chunks * * Memory doesn't overlap * * Each byte in the chunks can be accounted for in either the freelist or as available bytes. */ template <std::size_t MAX_BLOCK_SIZE_BYTES, std::size_t ALIGN_BYTES> static void CheckAllDataAccountedFor(const PoolResource<MAX_BLOCK_SIZE_BYTES, ALIGN_BYTES>& resource) { // collect all free blocks by iterating all freelists std::vector<PtrAndBytes> free_blocks; for (std::size_t freelist_idx = 0; freelist_idx < resource.m_free_lists.size(); ++freelist_idx) { std::size_t bytes = freelist_idx * resource.ELEM_ALIGN_BYTES; auto* ptr = resource.m_free_lists[freelist_idx]; while (ptr != nullptr) { free_blocks.emplace_back(ptr, bytes); ptr = ptr->m_next; } } // also add whatever has not yet been used for blocks auto num_available_bytes = resource.m_available_memory_end - resource.m_available_memory_it; if (num_available_bytes > 0) { free_blocks.emplace_back(resource.m_available_memory_it, num_available_bytes); } // collect all chunks std::vector<PtrAndBytes> chunks; for (const std::byte* ptr : resource.m_allocated_chunks) { chunks.emplace_back(ptr, resource.ChunkSizeBytes()); } // now we have all the data from all freelists on the one hand side, and all chunks on the other hand side. // To check if all of them match, sort by address and iterate. std::sort(free_blocks.begin(), free_blocks.end()); std::sort(chunks.begin(), chunks.end()); auto chunk_it = chunks.begin(); auto chunk_ptr_remaining = chunk_it->ptr; auto chunk_size_remaining = chunk_it->size; for (const auto& free_block : free_blocks) { if (chunk_size_remaining == 0) { assert(chunk_it != chunks.end()); ++chunk_it; assert(chunk_it != chunks.end()); chunk_ptr_remaining = chunk_it->ptr; chunk_size_remaining = chunk_it->size; } assert(free_block.ptr == chunk_ptr_remaining); // ensure addresses match assert(free_block.size <= chunk_size_remaining); // ensure no overflow assert((free_block.ptr & (resource.ELEM_ALIGN_BYTES - 1)) == 0); // ensure correct alignment chunk_ptr_remaining += free_block.size; chunk_size_remaining -= free_block.size; } // ensure we are at the end of the chunks assert(chunk_ptr_remaining == chunk_it->ptr + chunk_it->size); ++chunk_it; assert(chunk_it == chunks.end()); assert(chunk_size_remaining == 0); } }; #endif // BITCOIN_TEST_UTIL_POOLRESOURCETESTER_H
0
bitcoin/src/test
bitcoin/src/test/util/logging.h
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_LOGGING_H #define BITCOIN_TEST_UTIL_LOGGING_H #include <util/macros.h> #include <functional> #include <list> #include <string> class DebugLogHelper { const std::string m_message; bool m_found{false}; std::list<std::function<void(const std::string&)>>::iterator m_print_connection; //! Custom match checking function. //! //! Invoked with pointers to lines containing matching strings, and with //! null if check_found() is called without any successful match. //! //! Can return true to enable default DebugLogHelper behavior of: //! (1) ending search after first successful match, and //! (2) raising an error in check_found if no match was found //! Can return false to do the opposite in either case. using MatchFn = std::function<bool(const std::string* line)>; MatchFn m_match; void check_found(); public: explicit DebugLogHelper(std::string message, MatchFn match = [](const std::string*){ return true; }); ~DebugLogHelper() { check_found(); } }; #define ASSERT_DEBUG_LOG(message) DebugLogHelper UNIQUE_NAME(debugloghelper)(message) #endif // BITCOIN_TEST_UTIL_LOGGING_H
0
bitcoin/src/test
bitcoin/src/test/util/txmempool.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/txmempool.h> #include <chainparams.h> #include <node/context.h> #include <node/mempool_args.h> #include <txmempool.h> #include <util/check.h> #include <util/time.h> #include <util/translation.h> #include <validation.h> using node::NodeContext; CTxMemPool::Options MemPoolOptionsForTest(const NodeContext& node) { CTxMemPool::Options mempool_opts{ // Default to always checking mempool regardless of // chainparams.DefaultConsistencyChecks for tests .check_ratio = 1, }; const auto result{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)}; Assert(result); return mempool_opts; } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction& tx) const { return FromTx(MakeTransactionRef(tx)); } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx) const { return CTxMemPoolEntry{tx, nFee, TicksSinceEpoch<std::chrono::seconds>(time), nHeight, m_sequence, spendsCoinbase, sigOpCost, lp}; } std::optional<std::string> CheckPackageMempoolAcceptResult(const Package& txns, const PackageMempoolAcceptResult& result, bool expect_valid, const CTxMemPool* mempool) { if (expect_valid) { if (result.m_state.IsInvalid()) { return strprintf("Package validation unexpectedly failed: %s", result.m_state.ToString()); } } else { if (result.m_state.IsValid()) { return strprintf("Package validation unexpectedly succeeded. %s", result.m_state.ToString()); } } if (result.m_state.GetResult() != PackageValidationResult::PCKG_POLICY && txns.size() != result.m_tx_results.size()) { return strprintf("txns size %u does not match tx results size %u", txns.size(), result.m_tx_results.size()); } for (const auto& tx : txns) { const auto& wtxid = tx->GetWitnessHash(); if (result.m_tx_results.count(wtxid) == 0) { return strprintf("result not found for tx %s", wtxid.ToString()); } const auto& atmp_result = result.m_tx_results.at(wtxid); const bool valid{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID}; if (expect_valid && atmp_result.m_state.IsInvalid()) { return strprintf("tx %s unexpectedly failed: %s", wtxid.ToString(), atmp_result.m_state.ToString()); } //m_replaced_transactions should exist iff the result was VALID if (atmp_result.m_replaced_transactions.has_value() != valid) { return strprintf("tx %s result should %shave m_replaced_transactions", wtxid.ToString(), valid ? "" : "not "); } // m_vsize and m_base_fees should exist iff the result was VALID or MEMPOOL_ENTRY const bool mempool_entry{atmp_result.m_result_type == MempoolAcceptResult::ResultType::MEMPOOL_ENTRY}; if (atmp_result.m_base_fees.has_value() != (valid || mempool_entry)) { return strprintf("tx %s result should %shave m_base_fees", wtxid.ToString(), valid || mempool_entry ? "" : "not "); } if (atmp_result.m_vsize.has_value() != (valid || mempool_entry)) { return strprintf("tx %s result should %shave m_vsize", wtxid.ToString(), valid || mempool_entry ? "" : "not "); } // m_other_wtxid should exist iff the result was DIFFERENT_WITNESS const bool diff_witness{atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS}; if (atmp_result.m_other_wtxid.has_value() != diff_witness) { return strprintf("tx %s result should %shave m_other_wtxid", wtxid.ToString(), diff_witness ? "" : "not "); } // m_effective_feerate and m_wtxids_fee_calculations should exist iff the result was valid // or if the failure was TX_RECONSIDERABLE const bool valid_or_reconsiderable{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID || atmp_result.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE}; if (atmp_result.m_effective_feerate.has_value() != valid_or_reconsiderable) { return strprintf("tx %s result should %shave m_effective_feerate", wtxid.ToString(), valid ? "" : "not "); } if (atmp_result.m_wtxids_fee_calculations.has_value() != valid_or_reconsiderable) { return strprintf("tx %s result should %shave m_effective_feerate", wtxid.ToString(), valid ? "" : "not "); } if (mempool) { // The tx by txid should be in the mempool iff the result was not INVALID. const bool txid_in_mempool{atmp_result.m_result_type != MempoolAcceptResult::ResultType::INVALID}; if (mempool->exists(GenTxid::Txid(tx->GetHash())) != txid_in_mempool) { return strprintf("tx %s should %sbe in mempool", wtxid.ToString(), txid_in_mempool ? "" : "not "); } // Additionally, if the result was DIFFERENT_WITNESS, we shouldn't be able to find the tx in mempool by wtxid. if (tx->HasWitness() && atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS) { if (mempool->exists(GenTxid::Wtxid(wtxid))) { return strprintf("wtxid %s should not be in mempool", wtxid.ToString()); } } } } return std::nullopt; }
0
bitcoin/src/test
bitcoin/src/test/util/net.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/net.h> #include <net.h> #include <net_processing.h> #include <netaddress.h> #include <netmessagemaker.h> #include <node/connection_types.h> #include <node/eviction.h> #include <protocol.h> #include <random.h> #include <serialize.h> #include <span.h> #include <vector> void ConnmanTestMsg::Handshake(CNode& node, bool successfully_connected, ServiceFlags remote_services, ServiceFlags local_services, int32_t version, bool relay_txs) { auto& peerman{static_cast<PeerManager&>(*m_msgproc)}; auto& connman{*this}; peerman.InitializeNode(node, local_services); FlushSendBuffer(node); // Drop the version message added by InitializeNode. CSerializedNetMsg msg_version{ NetMsg::Make(NetMsgType::VERSION, version, // Using<CustomUintFormatter<8>>(remote_services), // int64_t{}, // dummy time int64_t{}, // ignored service bits CNetAddr::V1(CService{}), // dummy int64_t{}, // ignored service bits CNetAddr::V1(CService{}), // ignored uint64_t{1}, // dummy nonce std::string{}, // dummy subver int32_t{}, // dummy starting_height relay_txs), }; (void)connman.ReceiveMsgFrom(node, std::move(msg_version)); node.fPauseSend = false; connman.ProcessMessagesOnce(node); peerman.SendMessages(&node); FlushSendBuffer(node); // Drop the verack message added by SendMessages. if (node.fDisconnect) return; assert(node.nVersion == version); assert(node.GetCommonVersion() == std::min(version, PROTOCOL_VERSION)); CNodeStateStats statestats; assert(peerman.GetNodeStateStats(node.GetId(), statestats)); assert(statestats.m_relay_txs == (relay_txs && !node.IsBlockOnlyConn())); assert(statestats.their_services == remote_services); if (successfully_connected) { CSerializedNetMsg msg_verack{NetMsg::Make(NetMsgType::VERACK)}; (void)connman.ReceiveMsgFrom(node, std::move(msg_verack)); node.fPauseSend = false; connman.ProcessMessagesOnce(node); peerman.SendMessages(&node); assert(node.fSuccessfullyConnected == true); } } void ConnmanTestMsg::NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const { assert(node.ReceiveMsgBytes(msg_bytes, complete)); if (complete) { node.MarkReceivedMsgsForProcessing(); } } void ConnmanTestMsg::FlushSendBuffer(CNode& node) const { LOCK(node.cs_vSend); node.vSendMsg.clear(); node.m_send_memusage = 0; while (true) { const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false); if (to_send.empty()) break; node.m_transport->MarkBytesSent(to_send.size()); } } bool ConnmanTestMsg::ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const { bool queued = node.m_transport->SetMessageToSend(ser_msg); assert(queued); bool complete{false}; while (true) { const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false); if (to_send.empty()) break; NodeReceiveMsgBytes(node, to_send, complete); node.m_transport->MarkBytesSent(to_send.size()); } return complete; } CNode* ConnmanTestMsg::ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type) { CNode* node = ConnectNode(CAddress{}, pszDest, /*fCountFailure=*/false, conn_type, /*use_v2transport=*/true); if (!node) return nullptr; node->SetCommonVersion(PROTOCOL_VERSION); peerman.InitializeNode(*node, ServiceFlags(NODE_NETWORK | NODE_WITNESS)); node->fSuccessfullyConnected = true; AddTestNode(*node); return node; } std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context) { std::vector<NodeEvictionCandidate> candidates; candidates.reserve(n_candidates); for (int id = 0; id < n_candidates; ++id) { candidates.push_back({ /*id=*/id, /*m_connected=*/std::chrono::seconds{random_context.randrange(100)}, /*m_min_ping_time=*/std::chrono::microseconds{random_context.randrange(100)}, /*m_last_block_time=*/std::chrono::seconds{random_context.randrange(100)}, /*m_last_tx_time=*/std::chrono::seconds{random_context.randrange(100)}, /*fRelevantServices=*/random_context.randbool(), /*m_relay_txs=*/random_context.randbool(), /*fBloomFilter=*/random_context.randbool(), /*nKeyedNetGroup=*/random_context.randrange(100), /*prefer_evict=*/random_context.randbool(), /*m_is_local=*/random_context.randbool(), /*m_network=*/ALL_NETWORKS[random_context.randrange(ALL_NETWORKS.size())], /*m_noban=*/false, /*m_conn_type=*/ConnectionType::INBOUND, }); } return candidates; }
0
bitcoin/src/test
bitcoin/src/test/util/README.md
# Test library This contains files for the test library, which is used by the test binaries (unit tests, benchmarks, fuzzers, gui tests). Generally, the files in this folder should be well-separated modules. New code should be added to existing modules or (when in doubt) a new module should be created. The utilities in here are compiled into a library, which does not hold any state. However, the main file `setup_common` defines the common test setup for all test binaries. The test binaries will handle the global state when they instantiate the `BasicTestingSetup` (or one of its derived classes).
0
bitcoin/src/test
bitcoin/src/test/util/chainstate.h
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #ifndef BITCOIN_TEST_UTIL_CHAINSTATE_H #define BITCOIN_TEST_UTIL_CHAINSTATE_H #include <clientversion.h> #include <logging.h> #include <node/context.h> #include <node/utxo_snapshot.h> #include <rpc/blockchain.h> #include <test/util/setup_common.h> #include <util/fs.h> #include <validation.h> #include <univalue.h> const auto NoMalleation = [](AutoFile& file, node::SnapshotMetadata& meta){}; /** * Create and activate a UTXO snapshot, optionally providing a function to * malleate the snapshot. * * If `reset_chainstate` is true, reset the original chainstate back to the genesis * block. This allows us to simulate more realistic conditions in which a snapshot is * loaded into an otherwise mostly-uninitialized datadir. It also allows us to test * conditions that would otherwise cause shutdowns based on the IBD chainstate going * past the snapshot it generated. */ template<typename F = decltype(NoMalleation)> static bool CreateAndActivateUTXOSnapshot( TestingSetup* fixture, F malleation = NoMalleation, bool reset_chainstate = false, bool in_memory_chainstate = false) { node::NodeContext& node = fixture->m_node; fs::path root = fixture->m_path_root; // Write out a snapshot to the test's tempdir. // int height; WITH_LOCK(::cs_main, height = node.chainman->ActiveHeight()); fs::path snapshot_path = root / fs::u8path(tfm::format("test_snapshot.%d.dat", height)); FILE* outfile{fsbridge::fopen(snapshot_path, "wb")}; AutoFile auto_outfile{outfile}; UniValue result = CreateUTXOSnapshot( node, node.chainman->ActiveChainstate(), auto_outfile, snapshot_path, snapshot_path); LogPrintf( "Wrote UTXO snapshot to %s: %s\n", fs::PathToString(snapshot_path.make_preferred()), result.write()); // Read the written snapshot in and then activate it. // FILE* infile{fsbridge::fopen(snapshot_path, "rb")}; AutoFile auto_infile{infile}; node::SnapshotMetadata metadata; auto_infile >> metadata; malleation(auto_infile, metadata); if (reset_chainstate) { { // What follows is code to selectively reset chainstate data without // disturbing the existing BlockManager instance, which is needed to // recognize the headers chain previously generated by the chainstate we're // removing. Without those headers, we can't activate the snapshot below. // // This is a stripped-down version of node::LoadChainstate which // preserves the block index. LOCK(::cs_main); CBlockIndex *orig_tip = node.chainman->ActiveChainstate().m_chain.Tip(); uint256 gen_hash = node.chainman->ActiveChainstate().m_chain[0]->GetBlockHash(); node.chainman->ResetChainstates(); node.chainman->InitializeChainstate(node.mempool.get()); Chainstate& chain = node.chainman->ActiveChainstate(); Assert(chain.LoadGenesisBlock()); // These cache values will be corrected shortly in `MaybeRebalanceCaches`. chain.InitCoinsDB(1 << 20, true, false, ""); chain.InitCoinsCache(1 << 20); chain.CoinsTip().SetBestBlock(gen_hash); chain.setBlockIndexCandidates.insert(node.chainman->m_blockman.LookupBlockIndex(gen_hash)); chain.LoadChainTip(); node.chainman->MaybeRebalanceCaches(); // Reset the HAVE_DATA flags below the snapshot height, simulating // never-having-downloaded them in the first place. // TODO: perhaps we could improve this by using pruning to delete // these blocks instead CBlockIndex *pindex = orig_tip; while (pindex && pindex != chain.m_chain.Tip()) { pindex->nStatus &= ~BLOCK_HAVE_DATA; pindex->nStatus &= ~BLOCK_HAVE_UNDO; // We have to set the ASSUMED_VALID flag, because otherwise it // would not be possible to have a block index entry without HAVE_DATA // and with nTx > 0 (since we aren't setting the pruned flag); // see CheckBlockIndex(). pindex->nStatus |= BLOCK_ASSUMED_VALID; pindex = pindex->pprev; } } BlockValidationState state; if (!node.chainman->ActiveChainstate().ActivateBestChain(state)) { throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString())); } Assert( 0 == WITH_LOCK(node.chainman->GetMutex(), return node.chainman->ActiveHeight())); } auto& new_active = node.chainman->ActiveChainstate(); auto* tip = new_active.m_chain.Tip(); // Disconnect a block so that the snapshot chainstate will be ahead, otherwise // it will refuse to activate. // // TODO this is a unittest-specific hack, and we should probably rethink how to // better generate/activate snapshots in unittests. if (tip->pprev) { new_active.m_chain.SetTip(*(tip->pprev)); } bool res = node.chainman->ActivateSnapshot(auto_infile, metadata, in_memory_chainstate); // Restore the old tip. new_active.m_chain.SetTip(*tip); return res; } #endif // BITCOIN_TEST_UTIL_CHAINSTATE_H
0
bitcoin/src/test
bitcoin/src/test/util/json.h
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_JSON_H #define BITCOIN_TEST_UTIL_JSON_H #include <string> #include <univalue.h> UniValue read_json(const std::string& jsondata); #endif // BITCOIN_TEST_UTIL_JSON_H
0
bitcoin/src/test
bitcoin/src/test/util/coins.h
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_COINS_H #define BITCOIN_TEST_UTIL_COINS_H #include <primitives/transaction.h> class CCoinsViewCache; /** * Create a Coin with DynamicMemoryUsage of 80 bytes and add it to the given view. * @param[in,out] coins_view The coins view cache to add the new coin to. * @returns the COutPoint of the created coin. */ COutPoint AddTestCoin(CCoinsViewCache& coins_view); #endif // BITCOIN_TEST_UTIL_COINS_H
0
bitcoin/src/test
bitcoin/src/test/util/blockfilter.cpp
// Copyright (c) 2019-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/blockfilter.h> #include <chainparams.h> #include <node/blockstorage.h> #include <primitives/block.h> #include <undo.h> #include <validation.h> using node::BlockManager; bool ComputeFilter(BlockFilterType filter_type, const CBlockIndex& block_index, BlockFilter& filter, const BlockManager& blockman) { LOCK(::cs_main); CBlock block; if (!blockman.ReadBlockFromDisk(block, block_index.GetBlockPos())) { return false; } CBlockUndo block_undo; if (block_index.nHeight > 0 && !blockman.UndoReadFromDisk(block_undo, block_index)) { return false; } filter = BlockFilter(filter_type, block, block_undo); return true; }
0
bitcoin/src/test
bitcoin/src/test/util/validation.h
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_VALIDATION_H #define BITCOIN_TEST_UTIL_VALIDATION_H #include <validation.h> class CValidationInterface; struct TestChainstateManager : public ChainstateManager { /** Reset the ibd cache to its initial state */ void ResetIbd(); /** Toggle IsInitialBlockDownload from true to false */ void JumpOutOfIbd(); }; class ValidationInterfaceTest { public: static void BlockConnected( ChainstateRole role, CValidationInterface& obj, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex); }; #endif // BITCOIN_TEST_UTIL_VALIDATION_H
0
bitcoin/src/test
bitcoin/src/test/util/str.h
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_STR_H #define BITCOIN_TEST_UTIL_STR_H #include <string> bool CaseInsensitiveEqual(const std::string& s1, const std::string& s2); /** * Increment a string. Useful to enumerate all fixed length strings with * characters in [min_char, max_char]. */ template <typename CharType, size_t StringLength> bool NextString(CharType (&string)[StringLength], CharType min_char, CharType max_char) { for (CharType& elem : string) { bool has_next = elem != max_char; elem = elem < min_char || elem >= max_char ? min_char : CharType(elem + 1); if (has_next) return true; } return false; } /** * Iterate over string values and call function for each string without * successive duplicate characters. */ template <typename CharType, size_t StringLength, typename Fn> void ForEachNoDup(CharType (&string)[StringLength], CharType min_char, CharType max_char, Fn&& fn) { for (bool has_next = true; has_next; has_next = NextString(string, min_char, max_char)) { int prev = -1; bool skip_string = false; for (CharType c : string) { if (c == prev) skip_string = true; if (skip_string || c < min_char || c > max_char) break; prev = c; } if (!skip_string) fn(); } } #endif // BITCOIN_TEST_UTIL_STR_H
0
bitcoin/src/test
bitcoin/src/test/util/setup_common.h
// Copyright (c) 2015-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_SETUP_COMMON_H #define BITCOIN_TEST_UTIL_SETUP_COMMON_H #include <common/args.h> // IWYU pragma: export #include <key.h> #include <node/caches.h> #include <node/context.h> // IWYU pragma: export #include <primitives/transaction.h> #include <pubkey.h> #include <stdexcept> #include <util/chaintype.h> // IWYU pragma: export #include <util/check.h> #include <util/fs.h> #include <util/string.h> #include <util/vector.h> #include <functional> #include <type_traits> #include <vector> class CFeeRate; class Chainstate; class FastRandomContext; /** This is connected to the logger. Can be used to redirect logs to any other log */ extern const std::function<void(const std::string&)> G_TEST_LOG_FUN; /** Retrieve the command line arguments. */ extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS; // Enable BOOST_CHECK_EQUAL for enum class types namespace std { template <typename T> std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) { return stream << static_cast<typename std::underlying_type<T>::type>(e); } } // namespace std static constexpr CAmount CENT{1000000}; /** Basic testing setup. * This just configures logging, data dir and chain parameters. */ struct BasicTestingSetup { util::SignalInterrupt m_interrupt; node::NodeContext m_node; // keep as first member to be destructed last explicit BasicTestingSetup(const ChainType chainType = ChainType::MAIN, const std::vector<const char*>& extra_args = {}); ~BasicTestingSetup(); const fs::path m_path_root; ArgsManager m_args; }; /** Testing setup that performs all steps up until right before * ChainstateManager gets initialized. Meant for testing ChainstateManager * initialization behaviour. */ struct ChainTestingSetup : public BasicTestingSetup { node::CacheSizes m_cache_sizes{}; bool m_coins_db_in_memory{true}; bool m_block_tree_db_in_memory{true}; explicit ChainTestingSetup(const ChainType chainType = ChainType::MAIN, const std::vector<const char*>& extra_args = {}); ~ChainTestingSetup(); // Supplies a chainstate, if one is needed void LoadVerifyActivateChainstate(); }; /** Testing setup that configures a complete environment. */ struct TestingSetup : public ChainTestingSetup { explicit TestingSetup( const ChainType chainType = ChainType::MAIN, const std::vector<const char*>& extra_args = {}, const bool coins_db_in_memory = true, const bool block_tree_db_in_memory = true); }; /** Identical to TestingSetup, but chain set to regtest */ struct RegTestingSetup : public TestingSetup { RegTestingSetup() : TestingSetup{ChainType::REGTEST} {} }; class CBlock; struct CMutableTransaction; class CScript; /** * Testing fixture that pre-creates a 100-block REGTEST-mode block chain */ struct TestChain100Setup : public TestingSetup { TestChain100Setup( const ChainType chain_type = ChainType::REGTEST, const std::vector<const char*>& extra_args = {}, const bool coins_db_in_memory = true, const bool block_tree_db_in_memory = true); /** * Create a new block with just given transactions, coinbase paying to * scriptPubKey, and try to add it to the current chain. * If no chainstate is specified, default to the active. */ CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey, Chainstate* chainstate = nullptr); /** * Create a new block with just given transactions, coinbase paying to * scriptPubKey. */ CBlock CreateBlock( const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey, Chainstate& chainstate); //! Mine a series of new blocks on the active chain. void mineBlocks(int num_blocks); /** * Create a transaction, optionally setting the fee based on the feerate. * Note: The feerate may not be met exactly depending on whether the signatures can have different sizes. * * @param input_transactions The transactions to spend * @param inputs Outpoints with which to construct transaction vin. * @param input_height The height of the block that included the input transactions. * @param input_signing_keys The keys to spend the input transactions. * @param outputs Transaction vout. * @param feerate The feerate the transaction should pay. * @param fee_output The index of the output to take the fee from. * @return The transaction and the fee it pays */ std::pair<CMutableTransaction, CAmount> CreateValidTransaction(const std::vector<CTransactionRef>& input_transactions, const std::vector<COutPoint>& inputs, int input_height, const std::vector<CKey>& input_signing_keys, const std::vector<CTxOut>& outputs, const std::optional<CFeeRate>& feerate, const std::optional<uint32_t>& fee_output); /** * Create a transaction and, optionally, submit to the mempool. * * @param input_transactions The transactions to spend * @param inputs Outpoints with which to construct transaction vin. * @param input_height The height of the block that included the input transaction(s). * @param input_signing_keys The keys to spend inputs. * @param outputs Transaction vout. * @param submit Whether or not to submit to mempool */ CMutableTransaction CreateValidMempoolTransaction(const std::vector<CTransactionRef>& input_transactions, const std::vector<COutPoint>& inputs, int input_height, const std::vector<CKey>& input_signing_keys, const std::vector<CTxOut>& outputs, bool submit = true); /** * Create a 1-in-1-out transaction and, optionally, submit to the mempool. * * @param input_transaction The transaction to spend * @param input_vout The vout to spend from the input_transaction * @param input_height The height of the block that included the input_transaction * @param input_signing_key The key to spend the input_transaction * @param output_destination Where to send the output * @param output_amount How much to send * @param submit Whether or not to submit to mempool */ CMutableTransaction CreateValidMempoolTransaction(CTransactionRef input_transaction, uint32_t input_vout, int input_height, CKey input_signing_key, CScript output_destination, CAmount output_amount = CAmount(1 * COIN), bool submit = true); /** Create transactions spending from m_coinbase_txns. These transactions will only spend coins * that exist in the current chain, but may be premature coinbase spends, have missing * signatures, or violate some other consensus rules. They should only be used for testing * mempool consistency. All transactions will have some random number of inputs and outputs * (between 1 and 24). Transactions may or may not be dependent upon each other; if dependencies * exit, every parent will always be somewhere in the list before the child so each transaction * can be submitted in the same order they appear in the list. * @param[in] submit When true, submit transactions to the mempool. * When false, return them but don't submit them. * @returns A vector of transactions that can be submitted to the mempool. */ std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit); /** Mock the mempool minimum feerate by adding a transaction and calling TrimToSize(0), * simulating the mempool "reaching capacity" and evicting by descendant feerate. Note that * this clears the mempool, and the new minimum feerate will depend on the maximum feerate of * transactions removed, so this must be called while the mempool is empty. * * @param target_feerate The new mempool minimum feerate after this function returns. * Must be above max(incremental feerate, min relay feerate), * or 1sat/vB with default settings. */ void MockMempoolMinFee(const CFeeRate& target_feerate); std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions CKey coinbaseKey; // private/public key needed to spend coinbase transactions }; /** * Make a test setup that has disk access to the debug.log file disabled. Can * be used in "hot loops", for example fuzzing or benchmarking. */ template <class T = const BasicTestingSetup> std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType::REGTEST, const std::vector<const char*>& extra_args = {}) { const std::vector<const char*> arguments = Cat( { "-nodebuglogfile", "-nodebug", }, extra_args); return std::make_unique<T>(chain_type, arguments); } CBlock getBlock13b8a(); // define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_* std::ostream& operator<<(std::ostream& os, const uint256& num); /** * BOOST_CHECK_EXCEPTION predicates to check the specific validation error. * Use as * BOOST_CHECK_EXCEPTION(code that throws, exception type, HasReason("foo")); */ class HasReason { public: explicit HasReason(const std::string& reason) : m_reason(reason) {} bool operator()(const std::exception& e) const { return std::string(e.what()).find(m_reason) != std::string::npos; }; private: const std::string m_reason; }; #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H
0
bitcoin/src/test
bitcoin/src/test/util/xoroshiro128plusplus.h
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_XOROSHIRO128PLUSPLUS_H #define BITCOIN_TEST_UTIL_XOROSHIRO128PLUSPLUS_H #include <cstdint> #include <limits> /** xoroshiro128++ PRNG. Extremely fast, not appropriate for cryptographic purposes. * * Memory footprint is 128bit, period is 2^128 - 1. * This class is not thread-safe. * * Reference implementation available at https://prng.di.unimi.it/xoroshiro128plusplus.c * See https://prng.di.unimi.it/ */ class XoRoShiRo128PlusPlus { uint64_t m_s0; uint64_t m_s1; [[nodiscard]] constexpr static uint64_t rotl(uint64_t x, int n) { return (x << n) | (x >> (64 - n)); } [[nodiscard]] constexpr static uint64_t SplitMix64(uint64_t& seedval) noexcept { uint64_t z = (seedval += UINT64_C(0x9e3779b97f4a7c15)); z = (z ^ (z >> 30U)) * UINT64_C(0xbf58476d1ce4e5b9); z = (z ^ (z >> 27U)) * UINT64_C(0x94d049bb133111eb); return z ^ (z >> 31U); } public: using result_type = uint64_t; constexpr explicit XoRoShiRo128PlusPlus(uint64_t seedval) noexcept : m_s0(SplitMix64(seedval)), m_s1(SplitMix64(seedval)) { } // no copy - that is dangerous, we don't want accidentally copy the RNG and then have two streams // with exactly the same results. If you need a copy, call copy(). XoRoShiRo128PlusPlus(const XoRoShiRo128PlusPlus&) = delete; XoRoShiRo128PlusPlus& operator=(const XoRoShiRo128PlusPlus&) = delete; // allow moves XoRoShiRo128PlusPlus(XoRoShiRo128PlusPlus&&) = default; XoRoShiRo128PlusPlus& operator=(XoRoShiRo128PlusPlus&&) = default; ~XoRoShiRo128PlusPlus() = default; constexpr result_type operator()() noexcept { uint64_t s0 = m_s0, s1 = m_s1; const uint64_t result = rotl(s0 + s1, 17) + s0; s1 ^= s0; m_s0 = rotl(s0, 49) ^ s1 ^ (s1 << 21); m_s1 = rotl(s1, 28); return result; } static constexpr result_type min() noexcept { return std::numeric_limits<result_type>::min(); } static constexpr result_type max() noexcept { return std::numeric_limits<result_type>::max(); } static constexpr double entropy() noexcept { return 0.0; } }; #endif // BITCOIN_TEST_UTIL_XOROSHIRO128PLUSPLUS_H
0
bitcoin/src/test
bitcoin/src/test/util/setup_common.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/setup_common.h> #include <kernel/validation_cache_sizes.h> #include <addrman.h> #include <banman.h> #include <chainparams.h> #include <common/system.h> #include <common/url.h> #include <consensus/consensus.h> #include <consensus/params.h> #include <consensus/validation.h> #include <crypto/sha256.h> #include <init.h> #include <init/common.h> #include <interfaces/chain.h> #include <kernel/mempool_entry.h> #include <logging.h> #include <net.h> #include <net_processing.h> #include <node/blockstorage.h> #include <node/chainstate.h> #include <node/context.h> #include <node/kernel_notifications.h> #include <node/mempool_args.h> #include <node/miner.h> #include <node/peerman_args.h> #include <node/validation_cache_args.h> #include <noui.h> #include <policy/fees.h> #include <policy/fees_args.h> #include <pow.h> #include <random.h> #include <rpc/blockchain.h> #include <rpc/register.h> #include <rpc/server.h> #include <scheduler.h> #include <script/sigcache.h> #include <streams.h> #include <test/util/net.h> #include <test/util/random.h> #include <test/util/txmempool.h> #include <timedata.h> #include <txdb.h> #include <txmempool.h> #include <util/chaintype.h> #include <util/check.h> #include <util/rbf.h> #include <util/strencodings.h> #include <util/string.h> #include <util/thread.h> #include <util/threadnames.h> #include <util/time.h> #include <util/translation.h> #include <util/vector.h> #include <validation.h> #include <validationinterface.h> #include <walletinitinterface.h> #include <algorithm> #include <functional> #include <stdexcept> using kernel::BlockTreeDB; using kernel::ValidationCacheSizes; using node::ApplyArgsManOptions; using node::BlockAssembler; using node::BlockManager; using node::CalculateCacheSizes; using node::KernelNotifications; using node::LoadChainstate; using node::RegenerateCommitments; using node::VerifyLoadedChainstate; const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; UrlDecodeFn* const URL_DECODE = nullptr; /** Random context to get unique temp data dirs. Separate from g_insecure_rand_ctx, which can be seeded from a const env var */ static FastRandomContext g_insecure_rand_ctx_temp_path; std::ostream& operator<<(std::ostream& os, const uint256& num) { os << num.ToString(); return os; } struct NetworkSetup { NetworkSetup() { Assert(SetupNetworking()); } }; static NetworkSetup g_networksetup_instance; BasicTestingSetup::BasicTestingSetup(const ChainType chainType, const std::vector<const char*>& extra_args) : m_path_root{fs::temp_directory_path() / "test_common_" PACKAGE_NAME / g_insecure_rand_ctx_temp_path.rand256().ToString()}, m_args{} { m_node.shutdown = &m_interrupt; m_node.args = &gArgs; std::vector<const char*> arguments = Cat( { "dummy", "-printtoconsole=0", "-logsourcelocations", "-logtimemicros", "-logthreadnames", "-loglevel=trace", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", }, extra_args); if (G_TEST_COMMAND_LINE_ARGUMENTS) { arguments = Cat(arguments, G_TEST_COMMAND_LINE_ARGUMENTS()); } util::ThreadRename("test"); fs::create_directories(m_path_root); m_args.ForceSetArg("-datadir", fs::PathToString(m_path_root)); gArgs.ForceSetArg("-datadir", fs::PathToString(m_path_root)); gArgs.ClearPathCache(); { SetupServerArgs(*m_node.args); std::string error; if (!m_node.args->ParseParameters(arguments.size(), arguments.data(), error)) { m_node.args->ClearArgs(); throw std::runtime_error{error}; } } SelectParams(chainType); SeedInsecureRand(); if (G_TEST_LOG_FUN) LogInstance().PushBackCallback(G_TEST_LOG_FUN); InitLogging(*m_node.args); AppInitParameterInteraction(*m_node.args); LogInstance().StartLogging(); m_node.kernel = std::make_unique<kernel::Context>(); SetupEnvironment(); ValidationCacheSizes validation_cache_sizes{}; ApplyArgsManOptions(*m_node.args, validation_cache_sizes); Assert(InitSignatureCache(validation_cache_sizes.signature_cache_bytes)); Assert(InitScriptExecutionCache(validation_cache_sizes.script_execution_cache_bytes)); m_node.chain = interfaces::MakeChain(m_node); static bool noui_connected = false; if (!noui_connected) { noui_connect(); noui_connected = true; } } BasicTestingSetup::~BasicTestingSetup() { m_node.kernel.reset(); SetMockTime(0s); // Reset mocktime for following tests LogInstance().DisconnectTestLogger(); fs::remove_all(m_path_root); gArgs.ClearArgs(); } ChainTestingSetup::ChainTestingSetup(const ChainType chainType, const std::vector<const char*>& extra_args) : BasicTestingSetup(chainType, extra_args) { const CChainParams& chainparams = Params(); // We have to run a scheduler thread to prevent ActivateBestChain // from blocking due to queue overrun. m_node.scheduler = std::make_unique<CScheduler>(); m_node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { m_node.scheduler->serviceQueue(); }); GetMainSignals().RegisterBackgroundSignalScheduler(*m_node.scheduler); m_node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(FeeestPath(*m_node.args), DEFAULT_ACCEPT_STALE_FEE_ESTIMATES); m_node.mempool = std::make_unique<CTxMemPool>(MemPoolOptionsForTest(m_node)); m_cache_sizes = CalculateCacheSizes(m_args); m_node.notifications = std::make_unique<KernelNotifications>(*Assert(m_node.shutdown), m_node.exit_status); const ChainstateManager::Options chainman_opts{ .chainparams = chainparams, .datadir = m_args.GetDataDirNet(), .adjusted_time_callback = GetAdjustedTime, .check_block_index = true, .notifications = *m_node.notifications, .worker_threads_num = 2, }; const BlockManager::Options blockman_opts{ .chainparams = chainman_opts.chainparams, .blocks_dir = m_args.GetBlocksDirPath(), .notifications = chainman_opts.notifications, }; m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown), chainman_opts, blockman_opts); m_node.chainman->m_blockman.m_block_tree_db = std::make_unique<BlockTreeDB>(DBParams{ .path = m_args.GetDataDirNet() / "blocks" / "index", .cache_bytes = static_cast<size_t>(m_cache_sizes.block_tree_db), .memory_only = true}); } ChainTestingSetup::~ChainTestingSetup() { if (m_node.scheduler) m_node.scheduler->stop(); GetMainSignals().FlushBackgroundCallbacks(); GetMainSignals().UnregisterBackgroundSignalScheduler(); m_node.connman.reset(); m_node.banman.reset(); m_node.addrman.reset(); m_node.netgroupman.reset(); m_node.args = nullptr; m_node.mempool.reset(); m_node.fee_estimator.reset(); m_node.chainman.reset(); m_node.scheduler.reset(); } void ChainTestingSetup::LoadVerifyActivateChainstate() { auto& chainman{*Assert(m_node.chainman)}; node::ChainstateLoadOptions options; options.mempool = Assert(m_node.mempool.get()); options.block_tree_db_in_memory = m_block_tree_db_in_memory; options.coins_db_in_memory = m_coins_db_in_memory; options.reindex = node::fReindex; options.reindex_chainstate = m_args.GetBoolArg("-reindex-chainstate", false); options.prune = chainman.m_blockman.IsPruneMode(); options.check_blocks = m_args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS); options.check_level = m_args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL); options.require_full_verification = m_args.IsArgSet("-checkblocks") || m_args.IsArgSet("-checklevel"); auto [status, error] = LoadChainstate(chainman, m_cache_sizes, options); assert(status == node::ChainstateLoadStatus::SUCCESS); std::tie(status, error) = VerifyLoadedChainstate(chainman, options); assert(status == node::ChainstateLoadStatus::SUCCESS); BlockValidationState state; if (!chainman.ActiveChainstate().ActivateBestChain(state)) { throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString())); } } TestingSetup::TestingSetup( const ChainType chainType, const std::vector<const char*>& extra_args, const bool coins_db_in_memory, const bool block_tree_db_in_memory) : ChainTestingSetup(chainType, extra_args) { m_coins_db_in_memory = coins_db_in_memory; m_block_tree_db_in_memory = block_tree_db_in_memory; // Ideally we'd move all the RPC tests to the functional testing framework // instead of unit tests, but for now we need these here. RegisterAllCoreRPCCommands(tableRPC); LoadVerifyActivateChainstate(); m_node.netgroupman = std::make_unique<NetGroupManager>(/*asmap=*/std::vector<bool>()); m_node.addrman = std::make_unique<AddrMan>(*m_node.netgroupman, /*deterministic=*/false, m_node.args->GetIntArg("-checkaddrman", 0)); m_node.banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME); m_node.connman = std::make_unique<ConnmanTestMsg>(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman, Params()); // Deterministic randomness for tests. PeerManager::Options peerman_opts; ApplyArgsManOptions(*m_node.args, peerman_opts); peerman_opts.deterministic_rng = true; m_node.peerman = PeerManager::make(*m_node.connman, *m_node.addrman, m_node.banman.get(), *m_node.chainman, *m_node.mempool, peerman_opts); { CConnman::Options options; options.m_msgproc = m_node.peerman.get(); m_node.connman->Init(options); } } TestChain100Setup::TestChain100Setup( const ChainType chain_type, const std::vector<const char*>& extra_args, const bool coins_db_in_memory, const bool block_tree_db_in_memory) : TestingSetup{ChainType::REGTEST, extra_args, coins_db_in_memory, block_tree_db_in_memory} { SetMockTime(1598887952); constexpr std::array<unsigned char, 32> vchKey = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; coinbaseKey.Set(vchKey.begin(), vchKey.end(), true); // Generate a 100-block chain: this->mineBlocks(COINBASE_MATURITY); { LOCK(::cs_main); assert( m_node.chainman->ActiveChain().Tip()->GetBlockHash().ToString() == "571d80a9967ae599cec0448b0b0ba1cfb606f584d8069bd7166b86854ba7a191"); } } void TestChain100Setup::mineBlocks(int num_blocks) { CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; for (int i = 0; i < num_blocks; i++) { std::vector<CMutableTransaction> noTxns; CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey); SetMockTime(GetTime() + 1); m_coinbase_txns.push_back(b.vtx[0]); } } CBlock TestChain100Setup::CreateBlock( const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey, Chainstate& chainstate) { CBlock block = BlockAssembler{chainstate, nullptr}.CreateNewBlock(scriptPubKey)->block; Assert(block.vtx.size() == 1); for (const CMutableTransaction& tx : txns) { block.vtx.push_back(MakeTransactionRef(tx)); } RegenerateCommitments(block, *Assert(m_node.chainman)); while (!CheckProofOfWork(block.GetHash(), block.nBits, m_node.chainman->GetConsensus())) ++block.nNonce; return block; } CBlock TestChain100Setup::CreateAndProcessBlock( const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey, Chainstate* chainstate) { if (!chainstate) { chainstate = &Assert(m_node.chainman)->ActiveChainstate(); } CBlock block = this->CreateBlock(txns, scriptPubKey, *chainstate); std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block); Assert(m_node.chainman)->ProcessNewBlock(shared_pblock, true, true, nullptr); return block; } std::pair<CMutableTransaction, CAmount> TestChain100Setup::CreateValidTransaction(const std::vector<CTransactionRef>& input_transactions, const std::vector<COutPoint>& inputs, int input_height, const std::vector<CKey>& input_signing_keys, const std::vector<CTxOut>& outputs, const std::optional<CFeeRate>& feerate, const std::optional<uint32_t>& fee_output) { CMutableTransaction mempool_txn; mempool_txn.vin.reserve(inputs.size()); mempool_txn.vout.reserve(outputs.size()); for (const auto& outpoint : inputs) { mempool_txn.vin.emplace_back(outpoint, CScript(), MAX_BIP125_RBF_SEQUENCE); } mempool_txn.vout = outputs; // - Add the signing key to a keystore FillableSigningProvider keystore; for (const auto& input_signing_key : input_signing_keys) { keystore.AddKey(input_signing_key); } // - Populate a CoinsViewCache with the unspent output CCoinsView coins_view; CCoinsViewCache coins_cache(&coins_view); for (const auto& input_transaction : input_transactions) { AddCoins(coins_cache, *input_transaction.get(), input_height); } // Build Outpoint to Coin map for SignTransaction std::map<COutPoint, Coin> input_coins; CAmount inputs_amount{0}; for (const auto& outpoint_to_spend : inputs) { // - Use GetCoin to properly populate utxo_to_spend, Coin utxo_to_spend; assert(coins_cache.GetCoin(outpoint_to_spend, utxo_to_spend)); input_coins.insert({outpoint_to_spend, utxo_to_spend}); inputs_amount += utxo_to_spend.out.nValue; } // - Default signature hashing type int nHashType = SIGHASH_ALL; std::map<int, bilingual_str> input_errors; assert(SignTransaction(mempool_txn, &keystore, input_coins, nHashType, input_errors)); CAmount current_fee = inputs_amount - std::accumulate(outputs.begin(), outputs.end(), CAmount(0), [](const CAmount& acc, const CTxOut& out) { return acc + out.nValue; }); // Deduct fees from fee_output to meet feerate if set if (feerate.has_value()) { assert(fee_output.has_value()); assert(fee_output.value() < mempool_txn.vout.size()); CAmount target_fee = feerate.value().GetFee(GetVirtualTransactionSize(CTransaction{mempool_txn})); CAmount deduction = target_fee - current_fee; if (deduction > 0) { // Only deduct fee if there's anything to deduct. If the caller has put more fees than // the target feerate, don't change the fee. mempool_txn.vout[fee_output.value()].nValue -= deduction; // Re-sign since an output has changed input_errors.clear(); assert(SignTransaction(mempool_txn, &keystore, input_coins, nHashType, input_errors)); current_fee = target_fee; } } return {mempool_txn, current_fee}; } CMutableTransaction TestChain100Setup::CreateValidMempoolTransaction(const std::vector<CTransactionRef>& input_transactions, const std::vector<COutPoint>& inputs, int input_height, const std::vector<CKey>& input_signing_keys, const std::vector<CTxOut>& outputs, bool submit) { CMutableTransaction mempool_txn = CreateValidTransaction(input_transactions, inputs, input_height, input_signing_keys, outputs, std::nullopt, std::nullopt).first; // If submit=true, add transaction to the mempool. if (submit) { LOCK(cs_main); const MempoolAcceptResult result = m_node.chainman->ProcessTransaction(MakeTransactionRef(mempool_txn)); assert(result.m_result_type == MempoolAcceptResult::ResultType::VALID); } return mempool_txn; } CMutableTransaction TestChain100Setup::CreateValidMempoolTransaction(CTransactionRef input_transaction, uint32_t input_vout, int input_height, CKey input_signing_key, CScript output_destination, CAmount output_amount, bool submit) { COutPoint input{input_transaction->GetHash(), input_vout}; CTxOut output{output_amount, output_destination}; return CreateValidMempoolTransaction(/*input_transactions=*/{input_transaction}, /*inputs=*/{input}, /*input_height=*/input_height, /*input_signing_keys=*/{input_signing_key}, /*outputs=*/{output}, /*submit=*/submit); } std::vector<CTransactionRef> TestChain100Setup::PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit) { std::vector<CTransactionRef> mempool_transactions; std::deque<std::pair<COutPoint, CAmount>> unspent_prevouts; std::transform(m_coinbase_txns.begin(), m_coinbase_txns.end(), std::back_inserter(unspent_prevouts), [](const auto& tx){ return std::make_pair(COutPoint(tx->GetHash(), 0), tx->vout[0].nValue); }); while (num_transactions > 0 && !unspent_prevouts.empty()) { // The number of inputs and outputs are random, between 1 and 24. CMutableTransaction mtx = CMutableTransaction(); const size_t num_inputs = det_rand.randrange(24) + 1; CAmount total_in{0}; for (size_t n{0}; n < num_inputs; ++n) { if (unspent_prevouts.empty()) break; const auto& [prevout, amount] = unspent_prevouts.front(); mtx.vin.emplace_back(prevout, CScript()); total_in += amount; unspent_prevouts.pop_front(); } const size_t num_outputs = det_rand.randrange(24) + 1; const CAmount fee = 100 * det_rand.randrange(30); const CAmount amount_per_output = (total_in - fee) / num_outputs; for (size_t n{0}; n < num_outputs; ++n) { CScript spk = CScript() << CScriptNum(num_transactions + n); mtx.vout.emplace_back(amount_per_output, spk); } CTransactionRef ptx = MakeTransactionRef(mtx); mempool_transactions.push_back(ptx); if (amount_per_output > 3000) { // If the value is high enough to fund another transaction + fees, keep track of it so // it can be used to build a more complex transaction graph. Insert randomly into // unspent_prevouts for extra randomness in the resulting structures. for (size_t n{0}; n < num_outputs; ++n) { unspent_prevouts.emplace_back(COutPoint(ptx->GetHash(), n), amount_per_output); std::swap(unspent_prevouts.back(), unspent_prevouts[det_rand.randrange(unspent_prevouts.size())]); } } if (submit) { LOCK2(cs_main, m_node.mempool->cs); LockPoints lp; m_node.mempool->addUnchecked(CTxMemPoolEntry(ptx, /*fee=*/(total_in - num_outputs * amount_per_output), /*time=*/0, /*entry_height=*/1, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/4, lp)); } --num_transactions; } return mempool_transactions; } void TestChain100Setup::MockMempoolMinFee(const CFeeRate& target_feerate) { LOCK2(cs_main, m_node.mempool->cs); // Transactions in the mempool will affect the new minimum feerate. assert(m_node.mempool->size() == 0); // The target feerate cannot be too low... // ...otherwise the transaction's feerate will need to be negative. assert(target_feerate > m_node.mempool->m_incremental_relay_feerate); // ...otherwise this is not meaningful. The feerate policy uses the maximum of both feerates. assert(target_feerate > m_node.mempool->m_min_relay_feerate); // Manually create an invalid transaction. Manually set the fee in the CTxMemPoolEntry to // achieve the exact target feerate. CMutableTransaction mtx = CMutableTransaction(); mtx.vin.emplace_back(COutPoint{Txid::FromUint256(g_insecure_rand_ctx.rand256()), 0}); mtx.vout.emplace_back(1 * COIN, GetScriptForDestination(WitnessV0ScriptHash(CScript() << OP_TRUE))); const auto tx{MakeTransactionRef(mtx)}; LockPoints lp; // The new mempool min feerate is equal to the removed package's feerate + incremental feerate. const auto tx_fee = target_feerate.GetFee(GetVirtualTransactionSize(*tx)) - m_node.mempool->m_incremental_relay_feerate.GetFee(GetVirtualTransactionSize(*tx)); m_node.mempool->addUnchecked(CTxMemPoolEntry(tx, /*fee=*/tx_fee, /*time=*/0, /*entry_height=*/1, /*entry_sequence=*/0, /*spends_coinbase=*/true, /*sigops_cost=*/1, lp)); m_node.mempool->TrimToSize(0); assert(m_node.mempool->GetMinFee() == target_feerate); } /** * @returns a real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af) * with 9 txs. */ CBlock getBlock13b8a() { CBlock block; DataStream stream{ ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), }; stream >> TX_WITH_WITNESS(block); return block; }
0
bitcoin/src/test
bitcoin/src/test/util/json.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/json.h> #include <string> #include <util/check.h> #include <univalue.h> UniValue read_json(const std::string& jsondata) { UniValue v; Assert(v.read(jsondata) && v.isArray()); return v.get_array(); }
0
bitcoin/src/test
bitcoin/src/test/util/txmempool.h
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_TXMEMPOOL_H #define BITCOIN_TEST_UTIL_TXMEMPOOL_H #include <policy/packages.h> #include <txmempool.h> #include <util/time.h> namespace node { struct NodeContext; } struct PackageMempoolAcceptResult; CTxMemPool::Options MemPoolOptionsForTest(const node::NodeContext& node); struct TestMemPoolEntryHelper { // Default values CAmount nFee{0}; NodeSeconds time{}; unsigned int nHeight{1}; uint64_t m_sequence{0}; bool spendsCoinbase{false}; unsigned int sigOpCost{4}; LockPoints lp; CTxMemPoolEntry FromTx(const CMutableTransaction& tx) const; CTxMemPoolEntry FromTx(const CTransactionRef& tx) const; // Change the default value TestMemPoolEntryHelper& Fee(CAmount _fee) { nFee = _fee; return *this; } TestMemPoolEntryHelper& Time(NodeSeconds tp) { time = tp; return *this; } TestMemPoolEntryHelper& Height(unsigned int _height) { nHeight = _height; return *this; } TestMemPoolEntryHelper& Sequence(uint64_t _seq) { m_sequence = _seq; return *this; } TestMemPoolEntryHelper& SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; } TestMemPoolEntryHelper& SigOpsCost(unsigned int _sigopsCost) { sigOpCost = _sigopsCost; return *this; } }; /** Check expected properties for every PackageMempoolAcceptResult, regardless of value. Returns * a string if an error occurs with error populated, nullopt otherwise. If mempool is provided, * checks that the expected transactions are in mempool (this should be set to nullptr for a test_accept). */ std::optional<std::string> CheckPackageMempoolAcceptResult(const Package& txns, const PackageMempoolAcceptResult& result, bool expect_valid, const CTxMemPool* mempool); #endif // BITCOIN_TEST_UTIL_TXMEMPOOL_H
0
bitcoin/src/test
bitcoin/src/test/util/str.cpp
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/str.h> #include <cstdint> #include <string> bool CaseInsensitiveEqual(const std::string& s1, const std::string& s2) { if (s1.size() != s2.size()) return false; for (size_t i = 0; i < s1.size(); ++i) { char c1 = s1[i]; if (c1 >= 'A' && c1 <= 'Z') c1 -= ('A' - 'a'); char c2 = s2[i]; if (c2 >= 'A' && c2 <= 'Z') c2 -= ('A' - 'a'); if (c1 != c2) return false; } return true; }
0
bitcoin/src/test
bitcoin/src/test/util/random.h
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_RANDOM_H #define BITCOIN_TEST_UTIL_RANDOM_H #include <consensus/amount.h> #include <random.h> #include <uint256.h> #include <cstdint> /** * This global and the helpers that use it are not thread-safe. * * If thread-safety is needed, the global could be made thread_local (given * that thread_local is supported on all architectures we support) or a * per-thread instance could be used in the multi-threaded test. */ extern FastRandomContext g_insecure_rand_ctx; /** * Flag to make GetRand in random.h return the same number */ extern bool g_mock_deterministic_tests; enum class SeedRand { ZEROS, //!< Seed with a compile time constant of zeros SEED, //!< Call the Seed() helper }; /** Seed the given random ctx or use the seed passed in via an environment var */ void Seed(FastRandomContext& ctx); static inline void SeedInsecureRand(SeedRand seed = SeedRand::SEED) { if (seed == SeedRand::ZEROS) { g_insecure_rand_ctx = FastRandomContext(/*fDeterministic=*/true); } else { Seed(g_insecure_rand_ctx); } } static inline uint32_t InsecureRand32() { return g_insecure_rand_ctx.rand32(); } static inline uint256 InsecureRand256() { return g_insecure_rand_ctx.rand256(); } static inline uint64_t InsecureRandBits(int bits) { return g_insecure_rand_ctx.randbits(bits); } static inline uint64_t InsecureRandRange(uint64_t range) { return g_insecure_rand_ctx.randrange(range); } static inline bool InsecureRandBool() { return g_insecure_rand_ctx.randbool(); } static inline CAmount InsecureRandMoneyAmount() { return static_cast<CAmount>(InsecureRandRange(MAX_MONEY + 1)); } #endif // BITCOIN_TEST_UTIL_RANDOM_H
0
bitcoin/src/test
bitcoin/src/test/util/index.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/index.h> #include <index/base.h> #include <util/check.h> #include <util/signalinterrupt.h> #include <util/time.h> void IndexWaitSynced(const BaseIndex& index, const util::SignalInterrupt& interrupt) { while (!index.BlockUntilSyncedToCurrentChain()) { // Assert shutdown was not requested to abort the test, instead of looping forever, in case // there was an unexpected error in the index that caused it to stop syncing and request a shutdown. Assert(!interrupt); UninterruptibleSleep(100ms); } assert(index.GetSummary().synced); }
0
bitcoin/src/test
bitcoin/src/test/util/transaction_utils.cpp
// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <coins.h> #include <script/signingprovider.h> #include <test/util/transaction_utils.h> CMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey, int nValue) { CMutableTransaction txCredit; txCredit.nVersion = 1; txCredit.nLockTime = 0; txCredit.vin.resize(1); txCredit.vout.resize(1); txCredit.vin[0].prevout.SetNull(); txCredit.vin[0].scriptSig = CScript() << CScriptNum(0) << CScriptNum(0); txCredit.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txCredit.vout[0].scriptPubKey = scriptPubKey; txCredit.vout[0].nValue = nValue; return txCredit; } CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CScriptWitness& scriptWitness, const CTransaction& txCredit) { CMutableTransaction txSpend; txSpend.nVersion = 1; txSpend.nLockTime = 0; txSpend.vin.resize(1); txSpend.vout.resize(1); txSpend.vin[0].scriptWitness = scriptWitness; txSpend.vin[0].prevout.hash = txCredit.GetHash(); txSpend.vin[0].prevout.n = 0; txSpend.vin[0].scriptSig = scriptSig; txSpend.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txSpend.vout[0].scriptPubKey = CScript(); txSpend.vout[0].nValue = txCredit.vout[0].nValue; return txSpend; } std::vector<CMutableTransaction> SetupDummyInputs(FillableSigningProvider& keystoreRet, CCoinsViewCache& coinsRet, const std::array<CAmount,4>& nValues) { std::vector<CMutableTransaction> dummyTransactions; dummyTransactions.resize(2); // Add some keys to the keystore: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } // Create some dummy input transactions dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = nValues[0]; dummyTransactions[0].vout[0].scriptPubKey << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = nValues[1]; dummyTransactions[0].vout[1].scriptPubKey << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG; AddCoins(coinsRet, CTransaction(dummyTransactions[0]), 0); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = nValues[2]; dummyTransactions[1].vout[0].scriptPubKey = GetScriptForDestination(PKHash(key[2].GetPubKey())); dummyTransactions[1].vout[1].nValue = nValues[3]; dummyTransactions[1].vout[1].scriptPubKey = GetScriptForDestination(PKHash(key[3].GetPubKey())); AddCoins(coinsRet, CTransaction(dummyTransactions[1]), 0); return dummyTransactions; }
0
bitcoin/src/test
bitcoin/src/test/fuzz/psbt.cpp
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <node/psbt.h> #include <psbt.h> #include <pubkey.h> #include <script/script.h> #include <streams.h> #include <util/check.h> #include <cstdint> #include <optional> #include <string> #include <vector> using node::AnalyzePSBT; using node::PSBTAnalysis; using node::PSBTInputAnalysis; FUZZ_TARGET(psbt) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; PartiallySignedTransaction psbt_mut; std::string error; auto str = fuzzed_data_provider.ConsumeRandomLengthString(); if (!DecodeRawPSBT(psbt_mut, MakeByteSpan(str), error)) { return; } const PartiallySignedTransaction psbt = psbt_mut; const PSBTAnalysis analysis = AnalyzePSBT(psbt); (void)PSBTRoleName(analysis.next); for (const PSBTInputAnalysis& input_analysis : analysis.inputs) { (void)PSBTRoleName(input_analysis.next); } (void)psbt.IsNull(); std::optional<CMutableTransaction> tx = psbt.tx; if (tx) { const CMutableTransaction& mtx = *tx; const PartiallySignedTransaction psbt_from_tx{mtx}; } for (const PSBTInput& input : psbt.inputs) { (void)PSBTInputSigned(input); (void)input.IsNull(); } (void)CountPSBTUnsignedInputs(psbt); for (const PSBTOutput& output : psbt.outputs) { (void)output.IsNull(); } for (size_t i = 0; i < psbt.tx->vin.size(); ++i) { CTxOut tx_out; if (psbt.GetInputUTXO(tx_out, i)) { (void)tx_out.IsNull(); (void)tx_out.ToString(); } } psbt_mut = psbt; (void)FinalizePSBT(psbt_mut); psbt_mut = psbt; CMutableTransaction result; if (FinalizeAndExtractPSBT(psbt_mut, result)) { const PartiallySignedTransaction psbt_from_tx{result}; } PartiallySignedTransaction psbt_merge; str = fuzzed_data_provider.ConsumeRandomLengthString(); if (!DecodeRawPSBT(psbt_merge, MakeByteSpan(str), error)) { psbt_merge = psbt; } psbt_mut = psbt; (void)psbt_mut.Merge(psbt_merge); psbt_mut = psbt; (void)CombinePSBTs(psbt_mut, {psbt_mut, psbt_merge}); psbt_mut = psbt; for (unsigned int i = 0; i < psbt_merge.tx->vin.size(); ++i) { (void)psbt_mut.AddInput(psbt_merge.tx->vin[i], psbt_merge.inputs[i]); } for (unsigned int i = 0; i < psbt_merge.tx->vout.size(); ++i) { Assert(psbt_mut.AddOutput(psbt_merge.tx->vout[i], psbt_merge.outputs[i])); } psbt_mut.unknown.insert(psbt_merge.unknown.begin(), psbt_merge.unknown.end()); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/fee_rate.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <policy/feerate.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <limits> #include <string> #include <vector> FUZZ_TARGET(fee_rate) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CAmount satoshis_per_k = ConsumeMoney(fuzzed_data_provider); const CFeeRate fee_rate{satoshis_per_k}; (void)fee_rate.GetFeePerK(); const auto bytes = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); if (!MultiplicationOverflow(int64_t{bytes}, satoshis_per_k)) { (void)fee_rate.GetFee(bytes); } (void)fee_rate.ToString(); const CAmount another_satoshis_per_k = ConsumeMoney(fuzzed_data_provider); CFeeRate larger_fee_rate{another_satoshis_per_k}; larger_fee_rate += fee_rate; if (satoshis_per_k != 0 && another_satoshis_per_k != 0) { assert(fee_rate < larger_fee_rate); assert(!(fee_rate > larger_fee_rate)); assert(!(fee_rate == larger_fee_rate)); assert(fee_rate <= larger_fee_rate); assert(!(fee_rate >= larger_fee_rate)); assert(fee_rate != larger_fee_rate); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/rpc.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <base58.h> #include <key.h> #include <key_io.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <psbt.h> #include <rpc/client.h> #include <rpc/request.h> #include <rpc/server.h> #include <span.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <tinyformat.h> #include <uint256.h> #include <univalue.h> #include <util/strencodings.h> #include <util/string.h> #include <util/time.h> #include <algorithm> #include <cassert> #include <cstdint> #include <cstdlib> #include <exception> #include <iostream> #include <memory> #include <optional> #include <stdexcept> #include <vector> enum class ChainType; namespace { struct RPCFuzzTestingSetup : public TestingSetup { RPCFuzzTestingSetup(const ChainType chain_type, const std::vector<const char*>& extra_args) : TestingSetup{chain_type, extra_args} { } void CallRPC(const std::string& rpc_method, const std::vector<std::string>& arguments) { JSONRPCRequest request; request.context = &m_node; request.strMethod = rpc_method; try { request.params = RPCConvertValues(rpc_method, arguments); } catch (const std::runtime_error&) { return; } tableRPC.execute(request); } std::vector<std::string> GetRPCCommands() const { return tableRPC.listCommands(); } }; RPCFuzzTestingSetup* rpc_testing_setup = nullptr; std::string g_limit_to_rpc_command; // RPC commands which are not appropriate for fuzzing: such as RPC commands // reading or writing to a filename passed as an RPC parameter, RPC commands // resulting in network activity, etc. const std::vector<std::string> RPC_COMMANDS_NOT_SAFE_FOR_FUZZING{ "addconnection", // avoid DNS lookups "addnode", // avoid DNS lookups "addpeeraddress", // avoid DNS lookups "dumptxoutset", // avoid writing to disk "dumpwallet", // avoid writing to disk "enumeratesigners", "echoipc", // avoid assertion failure (Assertion `"EnsureAnyNodeContext(request.context).init" && check' failed.) "generatetoaddress", // avoid prohibitively slow execution (when `num_blocks` is large) "generatetodescriptor", // avoid prohibitively slow execution (when `nblocks` is large) "gettxoutproof", // avoid prohibitively slow execution "importmempool", // avoid reading from disk "importwallet", // avoid reading from disk "loadtxoutset", // avoid reading from disk "loadwallet", // avoid reading from disk "savemempool", // disabled as a precautionary measure: may take a file path argument in the future "setban", // avoid DNS lookups "stop", // avoid shutdown state }; // RPC commands which are safe for fuzzing. const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{ "analyzepsbt", "clearbanned", "combinepsbt", "combinerawtransaction", "converttopsbt", "createmultisig", "createpsbt", "createrawtransaction", "decodepsbt", "decoderawtransaction", "decodescript", "deriveaddresses", "descriptorprocesspsbt", "disconnectnode", "echo", "echojson", "estimaterawfee", "estimatesmartfee", "finalizepsbt", "generate", "generateblock", "getaddednodeinfo", "getaddrmaninfo", "getbestblockhash", "getblock", "getblockchaininfo", "getblockcount", "getblockfilter", "getblockfrompeer", // when no peers are connected, no p2p message is sent "getblockhash", "getblockheader", "getblockstats", "getblocktemplate", "getchaintips", "getchainstates", "getchaintxstats", "getconnectioncount", "getdeploymentinfo", "getdescriptorinfo", "getdifficulty", "getindexinfo", "getmemoryinfo", "getmempoolancestors", "getmempooldescendants", "getmempoolentry", "getmempoolinfo", "getmininginfo", "getnettotals", "getnetworkhashps", "getnetworkinfo", "getnodeaddresses", "getpeerinfo", "getprioritisedtransactions", "getrawaddrman", "getrawmempool", "getrawtransaction", "getrpcinfo", "gettxout", "gettxoutsetinfo", "gettxspendingprevout", "help", "invalidateblock", "joinpsbts", "listbanned", "logging", "mockscheduler", "ping", "preciousblock", "prioritisetransaction", "pruneblockchain", "reconsiderblock", "scanblocks", "scantxoutset", "sendmsgtopeer", // when no peers are connected, no p2p message is sent "sendrawtransaction", "setmocktime", "setnetworkactive", "signmessagewithprivkey", "signrawtransactionwithkey", "submitblock", "submitheader", "submitpackage", "syncwithvalidationinterfacequeue", "testmempoolaccept", "uptime", "utxoupdatepsbt", "validateaddress", "verifychain", "verifymessage", "verifytxoutproof", "waitforblock", "waitforblockheight", "waitfornewblock", }; std::string ConsumeScalarRPCArgument(FuzzedDataProvider& fuzzed_data_provider, bool& good_data) { const size_t max_string_length = 4096; const size_t max_base58_bytes_length{64}; std::string r; CallOneOf( fuzzed_data_provider, [&] { // string argument r = fuzzed_data_provider.ConsumeRandomLengthString(max_string_length); }, [&] { // base64 argument r = EncodeBase64(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)); }, [&] { // hex argument r = HexStr(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)); }, [&] { // bool argument r = fuzzed_data_provider.ConsumeBool() ? "true" : "false"; }, [&] { // range argument r = "[" + ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>()) + "," + ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>()) + "]"; }, [&] { // integral argument (int64_t) r = ToString(fuzzed_data_provider.ConsumeIntegral<int64_t>()); }, [&] { // integral argument (uint64_t) r = ToString(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); }, [&] { // floating point argument r = strprintf("%f", fuzzed_data_provider.ConsumeFloatingPoint<double>()); }, [&] { // tx destination argument r = EncodeDestination(ConsumeTxDestination(fuzzed_data_provider)); }, [&] { // uint160 argument r = ConsumeUInt160(fuzzed_data_provider).ToString(); }, [&] { // uint256 argument r = ConsumeUInt256(fuzzed_data_provider).ToString(); }, [&] { // base32 argument r = EncodeBase32(fuzzed_data_provider.ConsumeRandomLengthString(max_string_length)); }, [&] { // base58 argument r = EncodeBase58(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_base58_bytes_length))); }, [&] { // base58 argument with checksum r = EncodeBase58Check(MakeUCharSpan(fuzzed_data_provider.ConsumeRandomLengthString(max_base58_bytes_length))); }, [&] { // hex encoded block std::optional<CBlock> opt_block = ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS); if (!opt_block) { good_data = false; return; } DataStream data_stream{}; data_stream << TX_WITH_WITNESS(*opt_block); r = HexStr(data_stream); }, [&] { // hex encoded block header std::optional<CBlockHeader> opt_block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider); if (!opt_block_header) { good_data = false; return; } DataStream data_stream{}; data_stream << *opt_block_header; r = HexStr(data_stream); }, [&] { // hex encoded tx std::optional<CMutableTransaction> opt_tx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!opt_tx) { good_data = false; return; } DataStream data_stream; auto allow_witness = (fuzzed_data_provider.ConsumeBool() ? TX_WITH_WITNESS : TX_NO_WITNESS); data_stream << allow_witness(*opt_tx); r = HexStr(data_stream); }, [&] { // base64 encoded psbt std::optional<PartiallySignedTransaction> opt_psbt = ConsumeDeserializable<PartiallySignedTransaction>(fuzzed_data_provider); if (!opt_psbt) { good_data = false; return; } DataStream data_stream{}; data_stream << *opt_psbt; r = EncodeBase64(data_stream); }, [&] { // base58 encoded key CKey key = ConsumePrivateKey(fuzzed_data_provider); if (!key.IsValid()) { good_data = false; return; } r = EncodeSecret(key); }, [&] { // hex encoded pubkey CKey key = ConsumePrivateKey(fuzzed_data_provider); if (!key.IsValid()) { good_data = false; return; } r = HexStr(key.GetPubKey()); }); return r; } std::string ConsumeArrayRPCArgument(FuzzedDataProvider& fuzzed_data_provider, bool& good_data) { std::vector<std::string> scalar_arguments; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 100) { scalar_arguments.push_back(ConsumeScalarRPCArgument(fuzzed_data_provider, good_data)); } return "[\"" + Join(scalar_arguments, "\",\"") + "\"]"; } std::string ConsumeRPCArgument(FuzzedDataProvider& fuzzed_data_provider, bool& good_data) { return fuzzed_data_provider.ConsumeBool() ? ConsumeScalarRPCArgument(fuzzed_data_provider, good_data) : ConsumeArrayRPCArgument(fuzzed_data_provider, good_data); } RPCFuzzTestingSetup* InitializeRPCFuzzTestingSetup() { static const auto setup = MakeNoLogFileContext<RPCFuzzTestingSetup>(); SetRPCWarmupFinished(); return setup.get(); } }; // namespace void initialize_rpc() { rpc_testing_setup = InitializeRPCFuzzTestingSetup(); const std::vector<std::string> supported_rpc_commands = rpc_testing_setup->GetRPCCommands(); for (const std::string& rpc_command : supported_rpc_commands) { const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end(); const bool not_safe_for_fuzzing = std::find(RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_NOT_SAFE_FOR_FUZZING.end(); if (!(safe_for_fuzzing || not_safe_for_fuzzing)) { std::cerr << "Error: RPC command \"" << rpc_command << "\" not found in RPC_COMMANDS_SAFE_FOR_FUZZING or RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n"; std::terminate(); } if (safe_for_fuzzing && not_safe_for_fuzzing) { std::cerr << "Error: RPC command \"" << rpc_command << "\" found in *both* RPC_COMMANDS_SAFE_FOR_FUZZING and RPC_COMMANDS_NOT_SAFE_FOR_FUZZING. Please update " << __FILE__ << ".\n"; std::terminate(); } } const char* limit_to_rpc_command_env = std::getenv("LIMIT_TO_RPC_COMMAND"); if (limit_to_rpc_command_env != nullptr) { g_limit_to_rpc_command = std::string{limit_to_rpc_command_env}; } } FUZZ_TARGET(rpc, .init = initialize_rpc) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; bool good_data{true}; SetMockTime(ConsumeTime(fuzzed_data_provider)); const std::string rpc_command = fuzzed_data_provider.ConsumeRandomLengthString(64); if (!g_limit_to_rpc_command.empty() && rpc_command != g_limit_to_rpc_command) { return; } const bool safe_for_fuzzing = std::find(RPC_COMMANDS_SAFE_FOR_FUZZING.begin(), RPC_COMMANDS_SAFE_FOR_FUZZING.end(), rpc_command) != RPC_COMMANDS_SAFE_FOR_FUZZING.end(); if (!safe_for_fuzzing) { return; } std::vector<std::string> arguments; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 100) { arguments.push_back(ConsumeRPCArgument(fuzzed_data_provider, good_data)); } try { rpc_testing_setup->CallRPC(rpc_command, arguments); } catch (const UniValue& json_rpc_error) { const std::string error_msg{json_rpc_error.find_value("message").get_str()}; if (error_msg.starts_with("Internal bug detected")) { // Only allow the intentional internal bug assert(error_msg.find("trigger_internal_bug") != std::string::npos); } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/txorphan.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <consensus/validation.h> #include <net_processing.h> #include <node/eviction.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <script/script.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <txorphanage.h> #include <uint256.h> #include <util/check.h> #include <util/time.h> #include <cstdint> #include <memory> #include <set> #include <utility> #include <vector> void initialize_orphanage() { static const auto testing_setup = MakeNoLogFileContext(); } FUZZ_TARGET(txorphan, .init = initialize_orphanage) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FastRandomContext limit_orphans_rng{/*fDeterministic=*/true}; SetMockTime(ConsumeTime(fuzzed_data_provider)); TxOrphanage orphanage; std::vector<COutPoint> outpoints; // initial outpoints used to construct transactions later for (uint8_t i = 0; i < 4; i++) { outpoints.emplace_back(Txid::FromUint256(uint256{i}), 0); } // if true, allow duplicate input when constructing tx const bool duplicate_input = fuzzed_data_provider.ConsumeBool(); LIMITED_WHILE(outpoints.size() < 200'000 && fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS) { // construct transaction const CTransactionRef tx = [&] { CMutableTransaction tx_mut; const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size()); const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size()); // pick unique outpoints from outpoints as input for (uint32_t i = 0; i < num_in; i++) { auto& prevout = PickValue(fuzzed_data_provider, outpoints); tx_mut.vin.emplace_back(prevout); // pop the picked outpoint if duplicate input is not allowed if (!duplicate_input) { std::swap(prevout, outpoints.back()); outpoints.pop_back(); } } // output amount will not affect txorphanage for (uint32_t i = 0; i < num_out; i++) { tx_mut.vout.emplace_back(CAmount{0}, CScript{}); } // restore previously popped outpoints for (auto& in : tx_mut.vin) { outpoints.push_back(in.prevout); } auto new_tx = MakeTransactionRef(tx_mut); // add newly constructed transaction to outpoints for (uint32_t i = 0; i < num_out; i++) { outpoints.emplace_back(new_tx->GetHash(), i); } return new_tx; }(); // trigger orphanage functions LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS) { NodeId peer_id = fuzzed_data_provider.ConsumeIntegral<NodeId>(); CallOneOf( fuzzed_data_provider, [&] { orphanage.AddChildrenToWorkSet(*tx); }, [&] { { CTransactionRef ref = orphanage.GetTxToReconsider(peer_id); if (ref) { bool have_tx = orphanage.HaveTx(GenTxid::Txid(ref->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(ref->GetWitnessHash())); Assert(have_tx); } } }, [&] { bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetWitnessHash())); // AddTx should return false if tx is too big or already have it // tx weight is unknown, we only check when tx is already in orphanage { bool add_tx = orphanage.AddTx(tx, peer_id); // have_tx == true -> add_tx == false Assert(!have_tx || !add_tx); } have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetWitnessHash())); { bool add_tx = orphanage.AddTx(tx, peer_id); // if have_tx is still false, it must be too big Assert(!have_tx == (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT)); Assert(!have_tx || !add_tx); } }, [&] { bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetWitnessHash())); // EraseTx should return 0 if m_orphans doesn't have the tx { Assert(have_tx == orphanage.EraseTx(tx->GetHash())); } have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetWitnessHash())); // have_tx should be false and EraseTx should fail { Assert(!have_tx && !orphanage.EraseTx(tx->GetHash())); } }, [&] { orphanage.EraseForPeer(peer_id); }, [&] { // test mocktime and expiry SetMockTime(ConsumeTime(fuzzed_data_provider)); auto limit = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); orphanage.LimitOrphans(limit, limit_orphans_rng); Assert(orphanage.Size() <= limit); }); } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/flatfile.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <flatfile.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cassert> #include <cstdint> #include <optional> #include <string> #include <vector> FUZZ_TARGET(flatfile) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); std::optional<FlatFilePos> flat_file_pos = ConsumeDeserializable<FlatFilePos>(fuzzed_data_provider); if (!flat_file_pos) { return; } std::optional<FlatFilePos> another_flat_file_pos = ConsumeDeserializable<FlatFilePos>(fuzzed_data_provider); if (another_flat_file_pos) { assert((*flat_file_pos == *another_flat_file_pos) != (*flat_file_pos != *another_flat_file_pos)); } (void)flat_file_pos->ToString(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/prevector.cpp
// Copyright (c) 2015-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <prevector.h> #include <vector> #include <reverse_iterator.h> #include <serialize.h> #include <streams.h> namespace { template <unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; public: void test() const { const pretype& const_pre_vector = pre_vector; assert(real_vector.size() == pre_vector.size()); assert(real_vector.empty() == pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { assert(real_vector[s] == pre_vector[s]); assert(&(pre_vector[s]) == &(pre_vector.begin()[s])); assert(&(pre_vector[s]) == &*(pre_vector.begin() + s)); assert(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // assert(realtype(pre_vector) == real_vector); assert(pretype(real_vector.begin(), real_vector.end()) == pre_vector); assert(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; for (const T& v : pre_vector) { assert(v == real_vector[pos]); ++pos; } for (const T& v : reverse_iterate(pre_vector)) { --pos; assert(v == real_vector[pos]); } for (const T& v : const_pre_vector) { assert(v == real_vector[pos]); ++pos; } for (const T& v : reverse_iterate(const_pre_vector)) { --pos; assert(v == real_vector[pos]); } DataStream ss1{}; DataStream ss2{}; ss1 << real_vector; ss2 << pre_vector; assert(ss1.size() == ss2.size()); for (Size s = 0; s < ss1.size(); s++) { assert(ss1[s] == ss2[s]); } } void resize(Size s) { real_vector.resize(s); assert(real_vector.size() == s); pre_vector.resize(s); assert(pre_vector.size() == s); } void reserve(Size s) { real_vector.reserve(s); assert(real_vector.capacity() >= s); pre_vector.reserve(s); assert(pre_vector.capacity() >= s); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); } template <typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() const { return real_vector.size(); } Size capacity() const { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); } void swap() noexcept { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); } void move() { real_vector = std::move(real_vector_alt); real_vector_alt.clear(); pre_vector = std::move(pre_vector_alt); pre_vector_alt.clear(); } void copy() { real_vector = real_vector_alt; pre_vector = pre_vector_alt; } void resize_uninitialized(realtype values) { size_t r = values.size(); size_t s = real_vector.size() / 2; if (real_vector.capacity() < s + r) { real_vector.reserve(s + r); } real_vector.resize(s); pre_vector.resize_uninitialized(s); for (auto v : values) { real_vector.push_back(v); } auto p = pre_vector.size(); pre_vector.resize_uninitialized(p + r); for (auto v : values) { pre_vector[p] = v; ++p; } } }; } // namespace FUZZ_TARGET(prevector) { FuzzedDataProvider prov(buffer.data(), buffer.size()); prevector_tester<8, int> test; LIMITED_WHILE(prov.remaining_bytes(), 3000) { switch (prov.ConsumeIntegralInRange<int>(0, 13 + 3 * (test.size() > 0))) { case 0: test.insert(prov.ConsumeIntegralInRange<size_t>(0, test.size()), prov.ConsumeIntegral<int>()); break; case 1: test.resize(std::max(0, std::min(30, (int)test.size() + prov.ConsumeIntegralInRange<int>(0, 4) - 2))); break; case 2: test.insert(prov.ConsumeIntegralInRange<size_t>(0, test.size()), 1 + prov.ConsumeBool(), prov.ConsumeIntegral<int>()); break; case 3: { int del = prov.ConsumeIntegralInRange<int>(0, test.size()); int beg = prov.ConsumeIntegralInRange<int>(0, test.size() - del); test.erase(beg, beg + del); break; } case 4: test.push_back(prov.ConsumeIntegral<int>()); break; case 5: { int values[4]; int num = 1 + prov.ConsumeIntegralInRange<int>(0, 3); for (int k = 0; k < num; ++k) { values[k] = prov.ConsumeIntegral<int>(); } test.insert_range(prov.ConsumeIntegralInRange<size_t>(0, test.size()), values, values + num); break; } case 6: { int num = 1 + prov.ConsumeIntegralInRange<int>(0, 15); std::vector<int> values(num); for (auto& v : values) { v = prov.ConsumeIntegral<int>(); } test.resize_uninitialized(values); break; } case 7: test.reserve(prov.ConsumeIntegralInRange<size_t>(0, 32767)); break; case 8: test.shrink_to_fit(); break; case 9: test.clear(); break; case 10: test.assign(prov.ConsumeIntegralInRange<size_t>(0, 32767), prov.ConsumeIntegral<int>()); break; case 11: test.swap(); break; case 12: test.copy(); break; case 13: test.move(); break; case 14: test.update(prov.ConsumeIntegralInRange<size_t>(0, test.size() - 1), prov.ConsumeIntegral<int>()); break; case 15: test.erase(prov.ConsumeIntegralInRange<size_t>(0, test.size() - 1)); break; case 16: test.pop_back(); break; } } test.test(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_descriptor_cache.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <pubkey.h> #include <script/descriptor.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <optional> #include <string> #include <vector> FUZZ_TARGET(script_descriptor_cache) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); DescriptorCache descriptor_cache; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const std::vector<uint8_t> code = fuzzed_data_provider.ConsumeBytes<uint8_t>(BIP32_EXTKEY_SIZE); if (code.size() == BIP32_EXTKEY_SIZE) { CExtPubKey xpub; xpub.Decode(code.data()); const uint32_t key_exp_pos = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); CExtPubKey xpub_fetched; if (fuzzed_data_provider.ConsumeBool()) { (void)descriptor_cache.GetCachedParentExtPubKey(key_exp_pos, xpub_fetched); descriptor_cache.CacheParentExtPubKey(key_exp_pos, xpub); assert(descriptor_cache.GetCachedParentExtPubKey(key_exp_pos, xpub_fetched)); } else { const uint32_t der_index = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); (void)descriptor_cache.GetCachedDerivedExtPubKey(key_exp_pos, der_index, xpub_fetched); descriptor_cache.CacheDerivedExtPubKey(key_exp_pos, der_index, xpub); assert(descriptor_cache.GetCachedDerivedExtPubKey(key_exp_pos, der_index, xpub_fetched)); } assert(xpub == xpub_fetched); } (void)descriptor_cache.GetCachedParentExtPubKeys(); (void)descriptor_cache.GetCachedDerivedExtPubKeys(); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/timedata.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <timedata.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(timedata) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const unsigned int max_size = fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(0, 1000); // A max_size of 0 implies no limit, so cap the max number of insertions to avoid timeouts auto max_to_insert = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 4000); // Divide by 2 to avoid signed integer overflow in .median() const int64_t initial_value = fuzzed_data_provider.ConsumeIntegral<int64_t>() / 2; CMedianFilter<int64_t> median_filter{max_size, initial_value}; while (fuzzed_data_provider.remaining_bytes() > 0 && --max_to_insert >= 0) { (void)median_filter.median(); assert(median_filter.size() > 0); assert(static_cast<size_t>(median_filter.size()) == median_filter.sorted().size()); assert(static_cast<unsigned int>(median_filter.size()) <= max_size || max_size == 0); // Divide by 2 to avoid signed integer overflow in .median() median_filter.input(fuzzed_data_provider.ConsumeIntegral<int64_t>() / 2); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_sigcache.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <key.h> #include <pubkey.h> #include <script/sigcache.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <cstdint> #include <optional> #include <string> #include <vector> namespace { const BasicTestingSetup* g_setup; } // namespace void initialize_script_sigcache() { static const auto testing_setup = MakeNoLogFileContext<>(); g_setup = testing_setup.get(); } FUZZ_TARGET(script_sigcache, .init = initialize_script_sigcache) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::optional<CMutableTransaction> mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); const CTransaction tx{mutable_transaction ? *mutable_transaction : CMutableTransaction{}}; const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const CAmount amount = ConsumeMoney(fuzzed_data_provider); const bool store = fuzzed_data_provider.ConsumeBool(); PrecomputedTransactionData tx_data; CachingTransactionSignatureChecker caching_transaction_signature_checker{mutable_transaction ? &tx : nullptr, n_in, amount, store, tx_data}; if (fuzzed_data_provider.ConsumeBool()) { const auto random_bytes = fuzzed_data_provider.ConsumeBytes<unsigned char>(64); const XOnlyPubKey pub_key(ConsumeUInt256(fuzzed_data_provider)); if (random_bytes.size() == 64) { (void)caching_transaction_signature_checker.VerifySchnorrSignature(random_bytes, pub_key, ConsumeUInt256(fuzzed_data_provider)); } } else { const auto random_bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider); const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider); if (pub_key) { if (!random_bytes.empty()) { (void)caching_transaction_signature_checker.VerifyECDSASignature(random_bytes, *pub_key, ConsumeUInt256(fuzzed_data_provider)); } } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_ops.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/script.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(script_ops) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); CScript script_mut = ConsumeScript(fuzzed_data_provider); LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 1000000) { CallOneOf( fuzzed_data_provider, [&] { CScript s = ConsumeScript(fuzzed_data_provider); script_mut = std::move(s); }, [&] { const CScript& s = ConsumeScript(fuzzed_data_provider); script_mut = s; }, [&] { script_mut << fuzzed_data_provider.ConsumeIntegral<int64_t>(); }, [&] { script_mut << ConsumeOpcodeType(fuzzed_data_provider); }, [&] { script_mut << ConsumeScriptNum(fuzzed_data_provider); }, [&] { script_mut << ConsumeRandomLengthByteVector(fuzzed_data_provider); }, [&] { script_mut.clear(); }); } const CScript& script = script_mut; (void)script.GetSigOpCount(false); (void)script.GetSigOpCount(true); (void)script.GetSigOpCount(script); (void)script.HasValidOps(); (void)script.IsPayToScriptHash(); (void)script.IsPayToWitnessScriptHash(); (void)script.IsPushOnly(); (void)script.IsUnspendable(); { CScript::const_iterator pc = script.begin(); opcodetype opcode; (void)script.GetOp(pc, opcode); std::vector<uint8_t> data; (void)script.GetOp(pc, opcode, data); (void)script.IsPushOnly(pc); } { int version; std::vector<uint8_t> program; (void)script.IsWitnessProgram(version, program); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/validation_load_mempool.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <kernel/mempool_persist.h> #include <node/mempool_args.h> #include <node/mempool_persist_args.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/mempool.h> #include <test/util/setup_common.h> #include <test/util/txmempool.h> #include <txmempool.h> #include <util/time.h> #include <validation.h> #include <cstdint> #include <vector> using kernel::DumpMempool; using kernel::LoadMempool; using node::MempoolPath; namespace { const TestingSetup* g_setup; } // namespace void initialize_validation_load_mempool() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } FUZZ_TARGET(validation_load_mempool, .init = initialize_validation_load_mempool) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; SetMockTime(ConsumeTime(fuzzed_data_provider)); FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider}; CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node)}; auto& chainstate{static_cast<DummyChainState&>(g_setup->m_node.chainman->ActiveChainstate())}; chainstate.SetMempool(&pool); auto fuzzed_fopen = [&](const fs::path&, const char*) { return fuzzed_file_provider.open(); }; (void)LoadMempool(pool, MempoolPath(g_setup->m_args), chainstate, { .mockable_fopen_function = fuzzed_fopen, }); pool.SetLoadTried(true); (void)DumpMempool(pool, MempoolPath(g_setup->m_args), fuzzed_fopen, true); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/crypto_chacha20.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/chacha20.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/xoroshiro128plusplus.h> #include <array> #include <cstddef> #include <cstdint> #include <vector> FUZZ_TARGET(crypto_chacha20) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const auto key = ConsumeFixedLengthByteVector<std::byte>(fuzzed_data_provider, ChaCha20::KEYLEN); ChaCha20 chacha20{key}; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { CallOneOf( fuzzed_data_provider, [&] { auto key = ConsumeFixedLengthByteVector<std::byte>(fuzzed_data_provider, ChaCha20::KEYLEN); chacha20.SetKey(key); }, [&] { chacha20.Seek( { fuzzed_data_provider.ConsumeIntegral<uint32_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>() }, fuzzed_data_provider.ConsumeIntegral<uint32_t>()); }, [&] { std::vector<uint8_t> output(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)); chacha20.Keystream(MakeWritableByteSpan(output)); }, [&] { std::vector<std::byte> output(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)); const auto input = ConsumeFixedLengthByteVector<std::byte>(fuzzed_data_provider, output.size()); chacha20.Crypt(input, output); }); } } namespace { /** Fuzzer that invokes ChaCha20::Crypt() or ChaCha20::Keystream multiple times: once for a large block at once, and then the same data in chunks, comparing the outcome. If UseCrypt, seeded Xoroshiro128++ output is used as input to Crypt(). If not, Keystream() is used directly, or sequences of 0x00 are encrypted. */ template<bool UseCrypt> void ChaCha20SplitFuzz(FuzzedDataProvider& provider) { // Determine key, iv, start position, length. auto key_bytes = ConsumeFixedLengthByteVector<std::byte>(provider, ChaCha20::KEYLEN); uint64_t iv = provider.ConsumeIntegral<uint64_t>(); uint32_t iv_prefix = provider.ConsumeIntegral<uint32_t>(); uint64_t total_bytes = provider.ConsumeIntegralInRange<uint64_t>(0, 1000000); /* ~x = 2^BITS - 1 - x, so ~(total_bytes >> 6) is the maximal seek position. */ uint32_t seek = provider.ConsumeIntegralInRange<uint32_t>(0, ~(uint32_t)(total_bytes >> 6)); // Initialize two ChaCha20 ciphers, with the same key/iv/position. ChaCha20 crypt1(key_bytes); ChaCha20 crypt2(key_bytes); crypt1.Seek({iv_prefix, iv}, seek); crypt2.Seek({iv_prefix, iv}, seek); // Construct vectors with data. std::vector<std::byte> data1, data2; data1.resize(total_bytes); data2.resize(total_bytes); // If using Crypt(), initialize data1 and data2 with the same Xoroshiro128++ based // stream. if constexpr (UseCrypt) { uint64_t seed = provider.ConsumeIntegral<uint64_t>(); XoRoShiRo128PlusPlus rng(seed); uint64_t bytes = 0; while (bytes < (total_bytes & ~uint64_t{7})) { uint64_t val = rng(); WriteLE64(UCharCast(data1.data() + bytes), val); WriteLE64(UCharCast(data2.data() + bytes), val); bytes += 8; } if (bytes < total_bytes) { std::byte valbytes[8]; uint64_t val = rng(); WriteLE64(UCharCast(valbytes), val); std::copy(valbytes, valbytes + (total_bytes - bytes), data1.data() + bytes); std::copy(valbytes, valbytes + (total_bytes - bytes), data2.data() + bytes); } } // Whether UseCrypt is used or not, the two byte arrays must match. assert(data1 == data2); // Encrypt data1, the whole array at once. if constexpr (UseCrypt) { crypt1.Crypt(data1, data1); } else { crypt1.Keystream(data1); } // Encrypt data2, in at most 256 chunks. uint64_t bytes2 = 0; int iter = 0; while (true) { bool is_last = (iter == 255) || (bytes2 == total_bytes) || provider.ConsumeBool(); ++iter; // Determine how many bytes to encrypt in this chunk: a fuzzer-determined // amount for all but the last chunk (which processes all remaining bytes). uint64_t now = is_last ? total_bytes - bytes2 : provider.ConsumeIntegralInRange<uint64_t>(0, total_bytes - bytes2); // For each chunk, consider using Crypt() even when UseCrypt is false. // This tests that Keystream() has the same behavior as Crypt() applied // to 0x00 input bytes. if (UseCrypt || provider.ConsumeBool()) { crypt2.Crypt(Span{data2}.subspan(bytes2, now), Span{data2}.subspan(bytes2, now)); } else { crypt2.Keystream(Span{data2}.subspan(bytes2, now)); } bytes2 += now; if (is_last) break; } // We should have processed everything now. assert(bytes2 == total_bytes); // And the result should match. assert(data1 == data2); } } // namespace FUZZ_TARGET(chacha20_split_crypt) { FuzzedDataProvider provider{buffer.data(), buffer.size()}; ChaCha20SplitFuzz<true>(provider); } FUZZ_TARGET(chacha20_split_keystream) { FuzzedDataProvider provider{buffer.data(), buffer.size()}; ChaCha20SplitFuzz<false>(provider); } FUZZ_TARGET(crypto_fschacha20) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; auto key = fuzzed_data_provider.ConsumeBytes<std::byte>(FSChaCha20::KEYLEN); key.resize(FSChaCha20::KEYLEN); auto fsc20 = FSChaCha20{key, fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, 1024)}; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { auto input = fuzzed_data_provider.ConsumeBytes<std::byte>(fuzzed_data_provider.ConsumeIntegralInRange(0, 4096)); std::vector<std::byte> output; output.resize(input.size()); fsc20.Crypt(input, output); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/minisketch.cpp
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <minisketch.h> #include <node/minisketchwrapper.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/check.h> #include <map> #include <numeric> namespace { Minisketch MakeFuzzMinisketch32(size_t capacity, uint32_t impl) { return Assert(Minisketch(32, impl, capacity)); } } // namespace FUZZ_TARGET(minisketch) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const auto capacity{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 200)}; const uint32_t impl{fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, Minisketch::MaxImplementation())}; if (!Minisketch::ImplementationSupported(32, impl)) return; Minisketch sketch_a{MakeFuzzMinisketch32(capacity, impl)}; Minisketch sketch_b{MakeFuzzMinisketch32(capacity, impl)}; sketch_a.SetSeed(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); sketch_b.SetSeed(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); // Fill two sets and keep the difference in a map std::map<uint32_t, bool> diff; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const auto entry{fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, std::numeric_limits<uint32_t>::max() - 1)}; const auto KeepDiff{[&] { bool& mut{diff[entry]}; mut = !mut; }}; CallOneOf( fuzzed_data_provider, [&] { sketch_a.Add(entry); KeepDiff(); }, [&] { sketch_b.Add(entry); KeepDiff(); }, [&] { sketch_a.Add(entry); sketch_b.Add(entry); }); } const auto num_diff{std::accumulate(diff.begin(), diff.end(), size_t{0}, [](auto n, const auto& e) { return n + e.second; })}; Minisketch sketch_ar{MakeFuzzMinisketch32(capacity, impl)}; Minisketch sketch_br{MakeFuzzMinisketch32(capacity, impl)}; sketch_ar.SetSeed(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); sketch_br.SetSeed(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); sketch_ar.Deserialize(sketch_a.Serialize()); sketch_br.Deserialize(sketch_b.Serialize()); Minisketch sketch_diff{std::move(fuzzed_data_provider.ConsumeBool() ? sketch_a : sketch_ar)}; sketch_diff.Merge(fuzzed_data_provider.ConsumeBool() ? sketch_b : sketch_br); if (capacity >= num_diff) { const auto max_elements{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(num_diff, capacity)}; const auto dec{*Assert(sketch_diff.Decode(max_elements))}; Assert(dec.size() == num_diff); for (auto d : dec) { Assert(diff.at(d)); } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/util.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <pubkey.h> #include <test/fuzz/util.h> #include <test/util/script.h> #include <util/check.h> #include <util/overflow.h> #include <util/rbf.h> #include <util/time.h> #include <memory> std::vector<uint8_t> ConstructPubKeyBytes(FuzzedDataProvider& fuzzed_data_provider, Span<const uint8_t> byte_data, const bool compressed) noexcept { uint8_t pk_type; if (compressed) { pk_type = fuzzed_data_provider.PickValueInArray({0x02, 0x03}); } else { pk_type = fuzzed_data_provider.PickValueInArray({0x04, 0x06, 0x07}); } std::vector<uint8_t> pk_data{byte_data.begin(), byte_data.begin() + (compressed ? CPubKey::COMPRESSED_SIZE : CPubKey::SIZE)}; pk_data[0] = pk_type; return pk_data; } CAmount ConsumeMoney(FuzzedDataProvider& fuzzed_data_provider, const std::optional<CAmount>& max) noexcept { return fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, max.value_or(MAX_MONEY)); } int64_t ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min, const std::optional<int64_t>& max) noexcept { // Avoid t=0 (1970-01-01T00:00:00Z) since SetMockTime(0) disables mocktime. static const int64_t time_min{946684801}; // 2000-01-01T00:00:01Z static const int64_t time_max{4133980799}; // 2100-12-31T23:59:59Z return fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(min.value_or(time_min), max.value_or(time_max)); } CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<Txid>>& prevout_txids, const int max_num_in, const int max_num_out) noexcept { CMutableTransaction tx_mut; const auto p2wsh_op_true = fuzzed_data_provider.ConsumeBool(); tx_mut.nVersion = fuzzed_data_provider.ConsumeBool() ? CTransaction::CURRENT_VERSION : fuzzed_data_provider.ConsumeIntegral<int32_t>(); tx_mut.nLockTime = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_in); const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_out); for (int i = 0; i < num_in; ++i) { const auto& txid_prev = prevout_txids ? PickValue(fuzzed_data_provider, *prevout_txids) : Txid::FromUint256(ConsumeUInt256(fuzzed_data_provider)); const auto index_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, max_num_out); const auto sequence = ConsumeSequence(fuzzed_data_provider); const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider); CScriptWitness script_wit; if (p2wsh_op_true) { script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE}; } else { script_wit = ConsumeScriptWitness(fuzzed_data_provider); } CTxIn in; in.prevout = COutPoint{txid_prev, index_out}; in.nSequence = sequence; in.scriptSig = script_sig; in.scriptWitness = script_wit; tx_mut.vin.push_back(in); } for (int i = 0; i < num_out; ++i) { const auto amount = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-10, 50 * COIN + 10); const auto script_pk = p2wsh_op_true ? P2WSH_OP_TRUE : ConsumeScript(fuzzed_data_provider, /*maybe_p2wsh=*/true); tx_mut.vout.emplace_back(amount, script_pk); } return tx_mut; } CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, const size_t max_stack_elem_size) noexcept { CScriptWitness ret; const auto n_elements = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, max_stack_elem_size); for (size_t i = 0; i < n_elements; ++i) { ret.stack.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider)); } return ret; } CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, const bool maybe_p2wsh) noexcept { CScript r_script{}; { // Keep a buffer of bytes to allow the fuzz engine to produce smaller // inputs to generate CScripts with repeated data. static constexpr unsigned MAX_BUFFER_SZ{128}; std::vector<uint8_t> buffer(MAX_BUFFER_SZ, uint8_t{'a'}); while (fuzzed_data_provider.ConsumeBool()) { CallOneOf( fuzzed_data_provider, [&] { // Insert byte vector directly to allow malformed or unparsable scripts r_script.insert(r_script.end(), buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ)); }, [&] { // Push a byte vector from the buffer r_script << std::vector<uint8_t>{buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ)}; }, [&] { // Push multisig // There is a special case for this to aid the fuzz engine // navigate the highly structured multisig format. r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22); int num_data{fuzzed_data_provider.ConsumeIntegralInRange(1, 22)}; while (num_data--) { auto pubkey_bytes{ConstructPubKeyBytes(fuzzed_data_provider, buffer, fuzzed_data_provider.ConsumeBool())}; if (fuzzed_data_provider.ConsumeBool()) { pubkey_bytes.back() = num_data; // Make each pubkey different } r_script << pubkey_bytes; } r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22); }, [&] { // Mutate the buffer const auto vec{ConsumeRandomLengthByteVector(fuzzed_data_provider, /*max_length=*/MAX_BUFFER_SZ)}; std::copy(vec.begin(), vec.end(), buffer.begin()); }, [&] { // Push an integral r_script << fuzzed_data_provider.ConsumeIntegral<int64_t>(); }, [&] { // Push an opcode r_script << ConsumeOpcodeType(fuzzed_data_provider); }, [&] { // Push a scriptnum r_script << ConsumeScriptNum(fuzzed_data_provider); }); } } if (maybe_p2wsh && fuzzed_data_provider.ConsumeBool()) { uint256 script_hash; CSHA256().Write(r_script.data(), r_script.size()).Finalize(script_hash.begin()); r_script.clear(); r_script << OP_0 << ToByteVector(script_hash); } return r_script; } uint32_t ConsumeSequence(FuzzedDataProvider& fuzzed_data_provider) noexcept { return fuzzed_data_provider.ConsumeBool() ? fuzzed_data_provider.PickValueInArray({ CTxIn::SEQUENCE_FINAL, CTxIn::MAX_SEQUENCE_NONFINAL, MAX_BIP125_RBF_SEQUENCE, }) : fuzzed_data_provider.ConsumeIntegral<uint32_t>(); } std::map<COutPoint, Coin> ConsumeCoins(FuzzedDataProvider& fuzzed_data_provider) noexcept { std::map<COutPoint, Coin> coins; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const std::optional<COutPoint> outpoint{ConsumeDeserializable<COutPoint>(fuzzed_data_provider)}; if (!outpoint) { break; } const std::optional<Coin> coin{ConsumeDeserializable<Coin>(fuzzed_data_provider)}; if (!coin) { break; } coins[*outpoint] = *coin; } return coins; } CTxDestination ConsumeTxDestination(FuzzedDataProvider& fuzzed_data_provider) noexcept { CTxDestination tx_destination; const size_t call_size{CallOneOf( fuzzed_data_provider, [&] { tx_destination = CNoDestination{}; }, [&] { bool compressed = fuzzed_data_provider.ConsumeBool(); CPubKey pk{ConstructPubKeyBytes( fuzzed_data_provider, ConsumeFixedLengthByteVector(fuzzed_data_provider, (compressed ? CPubKey::COMPRESSED_SIZE : CPubKey::SIZE)), compressed )}; tx_destination = PubKeyDestination{pk}; }, [&] { tx_destination = PKHash{ConsumeUInt160(fuzzed_data_provider)}; }, [&] { tx_destination = ScriptHash{ConsumeUInt160(fuzzed_data_provider)}; }, [&] { tx_destination = WitnessV0ScriptHash{ConsumeUInt256(fuzzed_data_provider)}; }, [&] { tx_destination = WitnessV0KeyHash{ConsumeUInt160(fuzzed_data_provider)}; }, [&] { tx_destination = WitnessV1Taproot{XOnlyPubKey{ConsumeUInt256(fuzzed_data_provider)}}; }, [&] { std::vector<unsigned char> program{ConsumeRandomLengthByteVector(fuzzed_data_provider, /*max_length=*/40)}; if (program.size() < 2) { program = {0, 0}; } tx_destination = WitnessUnknown{fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(2, 16), program}; })}; Assert(call_size == std::variant_size_v<CTxDestination>); return tx_destination; } CKey ConsumePrivateKey(FuzzedDataProvider& fuzzed_data_provider, std::optional<bool> compressed) noexcept { auto key_data = fuzzed_data_provider.ConsumeBytes<uint8_t>(32); key_data.resize(32); CKey key; bool compressed_value = compressed ? *compressed : fuzzed_data_provider.ConsumeBool(); key.Set(key_data.begin(), key_data.end(), compressed_value); return key; } bool ContainsSpentInput(const CTransaction& tx, const CCoinsViewCache& inputs) noexcept { for (const CTxIn& tx_in : tx.vin) { const Coin& coin = inputs.AccessCoin(tx_in.prevout); if (coin.IsSpent()) { return true; } } return false; } FILE* FuzzedFileProvider::open() { SetFuzzedErrNo(m_fuzzed_data_provider); if (m_fuzzed_data_provider.ConsumeBool()) { return nullptr; } std::string mode; CallOneOf( m_fuzzed_data_provider, [&] { mode = "r"; }, [&] { mode = "r+"; }, [&] { mode = "w"; }, [&] { mode = "w+"; }, [&] { mode = "a"; }, [&] { mode = "a+"; }); #if defined _GNU_SOURCE && !defined __ANDROID__ const cookie_io_functions_t io_hooks = { FuzzedFileProvider::read, FuzzedFileProvider::write, FuzzedFileProvider::seek, FuzzedFileProvider::close, }; return fopencookie(this, mode.c_str(), io_hooks); #else (void)mode; return nullptr; #endif } ssize_t FuzzedFileProvider::read(void* cookie, char* buf, size_t size) { FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie; SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider); if (buf == nullptr || size == 0 || fuzzed_file->m_fuzzed_data_provider.ConsumeBool()) { return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1; } const std::vector<uint8_t> random_bytes = fuzzed_file->m_fuzzed_data_provider.ConsumeBytes<uint8_t>(size); if (random_bytes.empty()) { return 0; } std::memcpy(buf, random_bytes.data(), random_bytes.size()); if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)random_bytes.size())) { return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1; } fuzzed_file->m_offset += random_bytes.size(); return random_bytes.size(); } ssize_t FuzzedFileProvider::write(void* cookie, const char* buf, size_t size) { FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie; SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider); const ssize_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<ssize_t>(0, size); if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)n)) { return 0; } fuzzed_file->m_offset += n; return n; } int FuzzedFileProvider::seek(void* cookie, int64_t* offset, int whence) { assert(whence == SEEK_SET || whence == SEEK_CUR || whence == SEEK_END); FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie; SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider); int64_t new_offset = 0; if (whence == SEEK_SET) { new_offset = *offset; } else if (whence == SEEK_CUR) { if (AdditionOverflow(fuzzed_file->m_offset, *offset)) { return -1; } new_offset = fuzzed_file->m_offset + *offset; } else if (whence == SEEK_END) { const int64_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 4096); if (AdditionOverflow(n, *offset)) { return -1; } new_offset = n + *offset; } if (new_offset < 0) { return -1; } fuzzed_file->m_offset = new_offset; *offset = new_offset; return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0); } int FuzzedFileProvider::close(void* cookie) { FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie; SetFuzzedErrNo(fuzzed_file->m_fuzzed_data_provider); return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/crypto_diff_fuzz_chacha20.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/chacha20.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <vector> /* From https://cr.yp.to/chacha.html chacha-merged.c version 20080118 D. J. Bernstein Public domain. */ typedef unsigned int u32; typedef unsigned char u8; #define U8C(v) (v##U) #define U32C(v) (v##U) #define U8V(v) ((u8)(v)&U8C(0xFF)) #define U32V(v) ((u32)(v)&U32C(0xFFFFFFFF)) #define ROTL32(v, n) (U32V((v) << (n)) | ((v) >> (32 - (n)))) #define U8TO32_LITTLE(p) \ (((u32)((p)[0])) | ((u32)((p)[1]) << 8) | ((u32)((p)[2]) << 16) | \ ((u32)((p)[3]) << 24)) #define U32TO8_LITTLE(p, v) \ do { \ (p)[0] = U8V((v)); \ (p)[1] = U8V((v) >> 8); \ (p)[2] = U8V((v) >> 16); \ (p)[3] = U8V((v) >> 24); \ } while (0) /* ------------------------------------------------------------------------- */ /* Data structures */ typedef struct { u32 input[16]; } ECRYPT_ctx; /* ------------------------------------------------------------------------- */ /* Mandatory functions */ void ECRYPT_keysetup( ECRYPT_ctx* ctx, const u8* key, u32 keysize, /* Key size in bits. */ u32 ivsize); /* IV size in bits. */ void ECRYPT_ivsetup( ECRYPT_ctx* ctx, const u8* iv); void ECRYPT_encrypt_bytes( ECRYPT_ctx* ctx, const u8* plaintext, u8* ciphertext, u32 msglen); /* Message length in bytes. */ /* ------------------------------------------------------------------------- */ /* Optional features */ void ECRYPT_keystream_bytes( ECRYPT_ctx* ctx, u8* keystream, u32 length); /* Length of keystream in bytes. */ /* ------------------------------------------------------------------------- */ #define ROTATE(v, c) (ROTL32(v, c)) #define XOR(v, w) ((v) ^ (w)) #define PLUS(v, w) (U32V((v) + (w))) #define PLUSONE(v) (PLUS((v), 1)) #define QUARTERROUND(a, b, c, d) \ a = PLUS(a, b); d = ROTATE(XOR(d, a), 16); \ c = PLUS(c, d); b = ROTATE(XOR(b, c), 12); \ a = PLUS(a, b); d = ROTATE(XOR(d, a), 8); \ c = PLUS(c, d); b = ROTATE(XOR(b, c), 7); static const char sigma[] = "expand 32-byte k"; static const char tau[] = "expand 16-byte k"; void ECRYPT_keysetup(ECRYPT_ctx* x, const u8* k, u32 kbits, u32 ivbits) { const char* constants; x->input[4] = U8TO32_LITTLE(k + 0); x->input[5] = U8TO32_LITTLE(k + 4); x->input[6] = U8TO32_LITTLE(k + 8); x->input[7] = U8TO32_LITTLE(k + 12); if (kbits == 256) { /* recommended */ k += 16; constants = sigma; } else { /* kbits == 128 */ constants = tau; } x->input[8] = U8TO32_LITTLE(k + 0); x->input[9] = U8TO32_LITTLE(k + 4); x->input[10] = U8TO32_LITTLE(k + 8); x->input[11] = U8TO32_LITTLE(k + 12); x->input[0] = U8TO32_LITTLE(constants + 0); x->input[1] = U8TO32_LITTLE(constants + 4); x->input[2] = U8TO32_LITTLE(constants + 8); x->input[3] = U8TO32_LITTLE(constants + 12); } void ECRYPT_ivsetup(ECRYPT_ctx* x, const u8* iv) { x->input[12] = 0; x->input[13] = 0; x->input[14] = U8TO32_LITTLE(iv + 0); x->input[15] = U8TO32_LITTLE(iv + 4); } void ECRYPT_encrypt_bytes(ECRYPT_ctx* x, const u8* m, u8* c, u32 bytes) { u32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; u32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15; u8* ctarget = nullptr; u8 tmp[64]; uint32_t i; if (!bytes) return; j0 = x->input[0]; j1 = x->input[1]; j2 = x->input[2]; j3 = x->input[3]; j4 = x->input[4]; j5 = x->input[5]; j6 = x->input[6]; j7 = x->input[7]; j8 = x->input[8]; j9 = x->input[9]; j10 = x->input[10]; j11 = x->input[11]; j12 = x->input[12]; j13 = x->input[13]; j14 = x->input[14]; j15 = x->input[15]; for (;;) { if (bytes < 64) { for (i = 0; i < bytes; ++i) tmp[i] = m[i]; m = tmp; ctarget = c; c = tmp; } x0 = j0; x1 = j1; x2 = j2; x3 = j3; x4 = j4; x5 = j5; x6 = j6; x7 = j7; x8 = j8; x9 = j9; x10 = j10; x11 = j11; x12 = j12; x13 = j13; x14 = j14; x15 = j15; for (i = 20; i > 0; i -= 2) { QUARTERROUND(x0, x4, x8, x12) QUARTERROUND(x1, x5, x9, x13) QUARTERROUND(x2, x6, x10, x14) QUARTERROUND(x3, x7, x11, x15) QUARTERROUND(x0, x5, x10, x15) QUARTERROUND(x1, x6, x11, x12) QUARTERROUND(x2, x7, x8, x13) QUARTERROUND(x3, x4, x9, x14) } x0 = PLUS(x0, j0); x1 = PLUS(x1, j1); x2 = PLUS(x2, j2); x3 = PLUS(x3, j3); x4 = PLUS(x4, j4); x5 = PLUS(x5, j5); x6 = PLUS(x6, j6); x7 = PLUS(x7, j7); x8 = PLUS(x8, j8); x9 = PLUS(x9, j9); x10 = PLUS(x10, j10); x11 = PLUS(x11, j11); x12 = PLUS(x12, j12); x13 = PLUS(x13, j13); x14 = PLUS(x14, j14); x15 = PLUS(x15, j15); x0 = XOR(x0, U8TO32_LITTLE(m + 0)); x1 = XOR(x1, U8TO32_LITTLE(m + 4)); x2 = XOR(x2, U8TO32_LITTLE(m + 8)); x3 = XOR(x3, U8TO32_LITTLE(m + 12)); x4 = XOR(x4, U8TO32_LITTLE(m + 16)); x5 = XOR(x5, U8TO32_LITTLE(m + 20)); x6 = XOR(x6, U8TO32_LITTLE(m + 24)); x7 = XOR(x7, U8TO32_LITTLE(m + 28)); x8 = XOR(x8, U8TO32_LITTLE(m + 32)); x9 = XOR(x9, U8TO32_LITTLE(m + 36)); x10 = XOR(x10, U8TO32_LITTLE(m + 40)); x11 = XOR(x11, U8TO32_LITTLE(m + 44)); x12 = XOR(x12, U8TO32_LITTLE(m + 48)); x13 = XOR(x13, U8TO32_LITTLE(m + 52)); x14 = XOR(x14, U8TO32_LITTLE(m + 56)); x15 = XOR(x15, U8TO32_LITTLE(m + 60)); j12 = PLUSONE(j12); if (!j12) { j13 = PLUSONE(j13); /* stopping at 2^70 bytes per nonce is user's responsibility */ } U32TO8_LITTLE(c + 0, x0); U32TO8_LITTLE(c + 4, x1); U32TO8_LITTLE(c + 8, x2); U32TO8_LITTLE(c + 12, x3); U32TO8_LITTLE(c + 16, x4); U32TO8_LITTLE(c + 20, x5); U32TO8_LITTLE(c + 24, x6); U32TO8_LITTLE(c + 28, x7); U32TO8_LITTLE(c + 32, x8); U32TO8_LITTLE(c + 36, x9); U32TO8_LITTLE(c + 40, x10); U32TO8_LITTLE(c + 44, x11); U32TO8_LITTLE(c + 48, x12); U32TO8_LITTLE(c + 52, x13); U32TO8_LITTLE(c + 56, x14); U32TO8_LITTLE(c + 60, x15); if (bytes <= 64) { if (bytes < 64) { for (i = 0; i < bytes; ++i) ctarget[i] = c[i]; } x->input[12] = j12; x->input[13] = j13; return; } bytes -= 64; c += 64; m += 64; } } void ECRYPT_keystream_bytes(ECRYPT_ctx* x, u8* stream, u32 bytes) { u32 i; for (i = 0; i < bytes; ++i) stream[i] = 0; ECRYPT_encrypt_bytes(x, stream, stream, bytes); } FUZZ_TARGET(crypto_diff_fuzz_chacha20) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; ECRYPT_ctx ctx; const std::vector<unsigned char> key = ConsumeFixedLengthByteVector(fuzzed_data_provider, 32); ChaCha20 chacha20{MakeByteSpan(key)}; ECRYPT_keysetup(&ctx, key.data(), key.size() * 8, 0); // ECRYPT_keysetup() doesn't set the counter and nonce to 0 while SetKey() does static const uint8_t iv[8] = {0, 0, 0, 0, 0, 0, 0, 0}; ChaCha20::Nonce96 nonce{0, 0}; uint32_t counter{0}; ECRYPT_ivsetup(&ctx, iv); LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 3000) { CallOneOf( fuzzed_data_provider, [&] { const std::vector<unsigned char> key = ConsumeFixedLengthByteVector(fuzzed_data_provider, 32); chacha20.SetKey(MakeByteSpan(key)); nonce = {0, 0}; counter = 0; ECRYPT_keysetup(&ctx, key.data(), key.size() * 8, 0); // ECRYPT_keysetup() doesn't set the counter and nonce to 0 while SetKey() does uint8_t iv[8] = {0, 0, 0, 0, 0, 0, 0, 0}; ECRYPT_ivsetup(&ctx, iv); }, [&] { uint32_t iv_prefix = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); uint64_t iv = fuzzed_data_provider.ConsumeIntegral<uint64_t>(); nonce = {iv_prefix, iv}; counter = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); chacha20.Seek(nonce, counter); ctx.input[12] = counter; ctx.input[13] = iv_prefix; ctx.input[14] = iv; ctx.input[15] = iv >> 32; }, [&] { uint32_t integralInRange = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096); std::vector<uint8_t> output(integralInRange); chacha20.Keystream(MakeWritableByteSpan(output)); std::vector<uint8_t> djb_output(integralInRange); ECRYPT_keystream_bytes(&ctx, djb_output.data(), djb_output.size()); assert(output == djb_output); // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. uint32_t old_counter = counter; counter += (integralInRange + 63) >> 6; if (counter < old_counter) ++nonce.first; if (integralInRange & 63) { chacha20.Seek(nonce, counter); } assert(counter == ctx.input[12]); }, [&] { uint32_t integralInRange = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096); std::vector<uint8_t> output(integralInRange); const std::vector<uint8_t> input = ConsumeFixedLengthByteVector(fuzzed_data_provider, output.size()); chacha20.Crypt(MakeByteSpan(input), MakeWritableByteSpan(output)); std::vector<uint8_t> djb_output(integralInRange); ECRYPT_encrypt_bytes(&ctx, input.data(), djb_output.data(), input.size()); assert(output == djb_output); // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. uint32_t old_counter = counter; counter += (integralInRange + 63) >> 6; if (counter < old_counter) ++nonce.first; if (integralInRange & 63) { chacha20.Seek(nonce, counter); } assert(counter == ctx.input[12]); }); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/signature_checker.cpp
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <pubkey.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/script.h> #include <cstdint> #include <limits> #include <string> #include <vector> namespace { class FuzzedSignatureChecker : public BaseSignatureChecker { FuzzedDataProvider& m_fuzzed_data_provider; public: explicit FuzzedSignatureChecker(FuzzedDataProvider& fuzzed_data_provider) : m_fuzzed_data_provider(fuzzed_data_provider) { } bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return m_fuzzed_data_provider.ConsumeBool(); } bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror = nullptr) const override { return m_fuzzed_data_provider.ConsumeBool(); } bool CheckLockTime(const CScriptNum& nLockTime) const override { return m_fuzzed_data_provider.ConsumeBool(); } bool CheckSequence(const CScriptNum& nSequence) const override { return m_fuzzed_data_provider.ConsumeBool(); } virtual ~FuzzedSignatureChecker() = default; }; } // namespace FUZZ_TARGET(signature_checker) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const unsigned int flags = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const SigVersion sig_version = fuzzed_data_provider.PickValueInArray({SigVersion::BASE, SigVersion::WITNESS_V0}); const auto script_1{ConsumeScript(fuzzed_data_provider)}; const auto script_2{ConsumeScript(fuzzed_data_provider)}; std::vector<std::vector<unsigned char>> stack; (void)EvalScript(stack, script_1, flags, FuzzedSignatureChecker(fuzzed_data_provider), sig_version, nullptr); if (!IsValidFlagCombination(flags)) { return; } (void)VerifyScript(script_1, script_2, nullptr, flags, FuzzedSignatureChecker(fuzzed_data_provider), nullptr); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/crypto_poly1305.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/poly1305.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <vector> FUZZ_TARGET(crypto_poly1305) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const auto key = ConsumeFixedLengthByteVector<std::byte>(fuzzed_data_provider, Poly1305::KEYLEN); const auto in = ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider); std::vector<std::byte> tag_out(Poly1305::TAGLEN); Poly1305{key}.Update(in).Finalize(tag_out); } FUZZ_TARGET(crypto_poly1305_split) { FuzzedDataProvider provider{buffer.data(), buffer.size()}; // Read key and instantiate two Poly1305 objects with it. auto key = provider.ConsumeBytes<std::byte>(Poly1305::KEYLEN); key.resize(Poly1305::KEYLEN); Poly1305 poly_full{key}, poly_split{key}; // Vector that holds all bytes processed so far. std::vector<std::byte> total_input; // Process input in pieces. LIMITED_WHILE(provider.remaining_bytes(), 100) { auto in = ConsumeRandomLengthByteVector<std::byte>(provider); poly_split.Update(in); // Update total_input to match what was processed. total_input.insert(total_input.end(), in.begin(), in.end()); } // Process entire input at once. poly_full.Update(total_input); // Verify both agree. std::array<std::byte, Poly1305::TAGLEN> tag_split, tag_full; poly_split.Finalize(tag_split); poly_full.Finalize(tag_full); assert(tag_full == tag_split); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/spanparsing.cpp
// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <util/spanparsing.h> FUZZ_TARGET(spanparsing) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const size_t query_size = fuzzed_data_provider.ConsumeIntegral<size_t>(); const std::string query = fuzzed_data_provider.ConsumeBytesAsString(std::min<size_t>(query_size, 1024 * 1024)); const std::string span_str = fuzzed_data_provider.ConsumeRemainingBytesAsString(); const Span<const char> const_span{span_str}; Span<const char> mut_span = const_span; (void)spanparsing::Const(query, mut_span); mut_span = const_span; (void)spanparsing::Func(query, mut_span); mut_span = const_span; (void)spanparsing::Expr(mut_span); if (!query.empty()) { mut_span = const_span; (void)spanparsing::Split(mut_span, query.front()); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/key_io.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <key_io.h> #include <test/fuzz/fuzz.h> #include <util/chaintype.h> #include <cassert> #include <cstdint> #include <string> #include <vector> void initialize_key_io() { ECC_Start(); SelectParams(ChainType::MAIN); } FUZZ_TARGET(key_io, .init = initialize_key_io) { const std::string random_string(buffer.begin(), buffer.end()); const CKey key = DecodeSecret(random_string); if (key.IsValid()) { assert(key == DecodeSecret(EncodeSecret(key))); } const CExtKey ext_key = DecodeExtKey(random_string); if (ext_key.key.size() == 32) { assert(ext_key == DecodeExtKey(EncodeExtKey(ext_key))); } const CExtPubKey ext_pub_key = DecodeExtPubKey(random_string); if (ext_pub_key.pubkey.size() == CPubKey::COMPRESSED_SIZE) { assert(ext_pub_key == DecodeExtPubKey(EncodeExtPubKey(ext_pub_key))); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/golomb_rice.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <blockfilter.h> #include <serialize.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/bytevectorhash.h> #include <util/golombrice.h> #include <algorithm> #include <cassert> #include <cstdint> #include <iosfwd> #include <unordered_set> #include <vector> namespace { uint64_t HashToRange(const std::vector<uint8_t>& element, const uint64_t f) { const uint64_t hash = CSipHasher(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL) .Write(element) .Finalize(); return FastRange64(hash, f); } std::vector<uint64_t> BuildHashedSet(const std::unordered_set<std::vector<uint8_t>, ByteVectorHash>& elements, const uint64_t f) { std::vector<uint64_t> hashed_elements; hashed_elements.reserve(elements.size()); for (const std::vector<uint8_t>& element : elements) { hashed_elements.push_back(HashToRange(element, f)); } std::sort(hashed_elements.begin(), hashed_elements.end()); return hashed_elements; } } // namespace FUZZ_TARGET(golomb_rice) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); std::vector<uint8_t> golomb_rice_data; std::vector<uint64_t> encoded_deltas; { std::unordered_set<std::vector<uint8_t>, ByteVectorHash> elements; const int n = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 512); for (int i = 0; i < n; ++i) { elements.insert(ConsumeRandomLengthByteVector(fuzzed_data_provider, 16)); } VectorWriter stream{golomb_rice_data, 0}; WriteCompactSize(stream, static_cast<uint32_t>(elements.size())); BitStreamWriter bitwriter{stream}; if (!elements.empty()) { uint64_t last_value = 0; for (const uint64_t value : BuildHashedSet(elements, static_cast<uint64_t>(elements.size()) * static_cast<uint64_t>(BASIC_FILTER_M))) { const uint64_t delta = value - last_value; encoded_deltas.push_back(delta); GolombRiceEncode(bitwriter, BASIC_FILTER_P, delta); last_value = value; } } bitwriter.Flush(); } std::vector<uint64_t> decoded_deltas; { SpanReader stream{golomb_rice_data}; BitStreamReader bitreader{stream}; const uint32_t n = static_cast<uint32_t>(ReadCompactSize(stream)); for (uint32_t i = 0; i < n; ++i) { decoded_deltas.push_back(GolombRiceDecode(bitreader, BASIC_FILTER_P)); } } assert(encoded_deltas == decoded_deltas); { const std::vector<uint8_t> random_bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider, 1024); SpanReader stream{random_bytes}; uint32_t n; try { n = static_cast<uint32_t>(ReadCompactSize(stream)); } catch (const std::ios_base::failure&) { return; } BitStreamReader bitreader{stream}; for (uint32_t i = 0; i < std::min<uint32_t>(n, 1024); ++i) { try { (void)GolombRiceDecode(bitreader, BASIC_FILTER_P); } catch (const std::ios_base::failure&) { } } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/crypto_hkdf_hmac_sha256_l32.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/hkdf_sha256_32.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(crypto_hkdf_hmac_sha256_l32) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const std::vector<uint8_t> initial_key_material = ConsumeRandomLengthByteVector(fuzzed_data_provider); CHKDF_HMAC_SHA256_L32 hkdf_hmac_sha256_l32(initial_key_material.data(), initial_key_material.size(), fuzzed_data_provider.ConsumeRandomLengthString(1024)); LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { std::vector<uint8_t> out(32); hkdf_hmac_sha256_l32.Expand32(fuzzed_data_provider.ConsumeRandomLengthString(128), out.data()); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/rolling_bloom_filter.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <common/bloom.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <uint256.h> #include <cassert> #include <cstdint> #include <optional> #include <string> #include <vector> FUZZ_TARGET(rolling_bloom_filter) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); CRollingBloomFilter rolling_bloom_filter{ fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(1, 1000), 0.999 / fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(1, std::numeric_limits<unsigned int>::max())}; LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 3000) { CallOneOf( fuzzed_data_provider, [&] { const std::vector<unsigned char> b = ConsumeRandomLengthByteVector(fuzzed_data_provider); (void)rolling_bloom_filter.contains(b); rolling_bloom_filter.insert(b); const bool present = rolling_bloom_filter.contains(b); assert(present); }, [&] { const uint256 u256{ConsumeUInt256(fuzzed_data_provider)}; (void)rolling_bloom_filter.contains(u256); rolling_bloom_filter.insert(u256); const bool present = rolling_bloom_filter.contains(u256); assert(present); }, [&] { rolling_bloom_filter.reset(); }); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/locale.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <tinyformat.h> #include <util/strencodings.h> #include <util/string.h> #include <cassert> #include <clocale> #include <cstdint> #include <locale> #include <string> #include <vector> namespace { const std::string locale_identifiers[] = { "C", "C.UTF-8", "aa_DJ", "aa_DJ.ISO-8859-1", "aa_DJ.UTF-8", "aa_ER", "aa_ER.UTF-8", "aa_ET", "aa_ET.UTF-8", "af_ZA", "af_ZA.ISO-8859-1", "af_ZA.UTF-8", "agr_PE", "agr_PE.UTF-8", "ak_GH", "ak_GH.UTF-8", "am_ET", "am_ET.UTF-8", "an_ES", "an_ES.ISO-8859-15", "an_ES.UTF-8", "anp_IN", "anp_IN.UTF-8", "ar_AE", "ar_AE.ISO-8859-6", "ar_AE.UTF-8", "ar_BH", "ar_BH.ISO-8859-6", "ar_BH.UTF-8", "ar_DZ", "ar_DZ.ISO-8859-6", "ar_DZ.UTF-8", "ar_EG", "ar_EG.ISO-8859-6", "ar_EG.UTF-8", "ar_IN", "ar_IN.UTF-8", "ar_IQ", "ar_IQ.ISO-8859-6", "ar_IQ.UTF-8", "ar_JO", "ar_JO.ISO-8859-6", "ar_JO.UTF-8", "ar_KW", "ar_KW.ISO-8859-6", "ar_KW.UTF-8", "ar_LB", "ar_LB.ISO-8859-6", "ar_LB.UTF-8", "ar_LY", "ar_LY.ISO-8859-6", "ar_LY.UTF-8", "ar_MA", "ar_MA.ISO-8859-6", "ar_MA.UTF-8", "ar_OM", "ar_OM.ISO-8859-6", "ar_OM.UTF-8", "ar_QA", "ar_QA.ISO-8859-6", "ar_QA.UTF-8", "ar_SA", "ar_SA.ISO-8859-6", "ar_SA.UTF-8", "ar_SD", "ar_SD.ISO-8859-6", "ar_SD.UTF-8", "ar_SS", "ar_SS.UTF-8", "ar_SY", "ar_SY.ISO-8859-6", "ar_SY.UTF-8", "ar_TN", "ar_TN.ISO-8859-6", "ar_TN.UTF-8", "ar_YE", "ar_YE.ISO-8859-6", "ar_YE.UTF-8", "as_IN", "as_IN.UTF-8", "ast_ES", "ast_ES.ISO-8859-15", "ast_ES.UTF-8", "ayc_PE", "ayc_PE.UTF-8", "az_AZ", "az_AZ.UTF-8", "az_IR", "az_IR.UTF-8", "be_BY", "be_BY.CP1251", "be_BY.UTF-8", "bem_ZM", "bem_ZM.UTF-8", "ber_DZ", "ber_DZ.UTF-8", "ber_MA", "ber_MA.UTF-8", "bg_BG", "bg_BG.CP1251", "bg_BG.UTF-8", "bho_IN", "bho_IN.UTF-8", "bho_NP", "bho_NP.UTF-8", "bi_VU", "bi_VU.UTF-8", "bn_BD", "bn_BD.UTF-8", "bn_IN", "bn_IN.UTF-8", "bo_CN", "bo_CN.UTF-8", "bo_IN", "bo_IN.UTF-8", "br_FR", "br_FR.ISO-8859-1", "br_FR.UTF-8", "brx_IN", "brx_IN.UTF-8", "bs_BA", "bs_BA.ISO-8859-2", "bs_BA.UTF-8", "byn_ER", "byn_ER.UTF-8", "ca_AD", "ca_AD.ISO-8859-15", "ca_AD.UTF-8", "ca_ES", "ca_ES.ISO-8859-1", "ca_ES.UTF-8", "ca_FR", "ca_FR.ISO-8859-15", "ca_FR.UTF-8", "ca_IT", "ca_IT.ISO-8859-15", "ca_IT.UTF-8", "ce_RU", "ce_RU.UTF-8", "chr_US", "chr_US.UTF-8", "ckb_IQ", "ckb_IQ.UTF-8", "cmn_TW", "cmn_TW.UTF-8", "crh_UA", "crh_UA.UTF-8", "csb_PL", "csb_PL.UTF-8", "cs_CZ", "cs_CZ.ISO-8859-2", "cs_CZ.UTF-8", "cv_RU", "cv_RU.UTF-8", "cy_GB", "cy_GB.ISO-8859-14", "cy_GB.UTF-8", "da_DK", "da_DK.ISO-8859-1", "da_DK.UTF-8", "de_AT", "de_AT.ISO-8859-1", "de_AT.UTF-8", "de_BE", "de_BE.ISO-8859-1", "de_BE.UTF-8", "de_CH", "de_CH.ISO-8859-1", "de_CH.UTF-8", "de_DE", "de_DE.ISO-8859-1", "de_DE.UTF-8", "de_IT", "de_IT.ISO-8859-1", "de_IT.UTF-8", "de_LU", "de_LU.ISO-8859-1", "de_LU.UTF-8", "doi_IN", "doi_IN.UTF-8", "dv_MV", "dv_MV.UTF-8", "dz_BT", "dz_BT.UTF-8", "el_CY", "el_CY.ISO-8859-7", "el_CY.UTF-8", "el_GR", "el_GR.ISO-8859-7", "el_GR.UTF-8", "en_AG", "en_AG.UTF-8", "en_AU", "en_AU.ISO-8859-1", "en_AU.UTF-8", "en_BW", "en_BW.ISO-8859-1", "en_BW.UTF-8", "en_CA", "en_CA.ISO-8859-1", "en_CA.UTF-8", "en_DK", "en_DK.ISO-8859-1", "en_DK.ISO-8859-15", "en_DK.UTF-8", "en_GB", "en_GB.ISO-8859-1", "en_GB.ISO-8859-15", "en_GB.UTF-8", "en_HK", "en_HK.ISO-8859-1", "en_HK.UTF-8", "en_IE", "en_IE.ISO-8859-1", "en_IE.UTF-8", "en_IL", "en_IL.UTF-8", "en_IN", "en_IN.UTF-8", "en_NG", "en_NG.UTF-8", "en_NZ", "en_NZ.ISO-8859-1", "en_NZ.UTF-8", "en_PH", "en_PH.ISO-8859-1", "en_PH.UTF-8", "en_SG", "en_SG.ISO-8859-1", "en_SG.UTF-8", "en_US", "en_US.ISO-8859-1", "en_US.ISO-8859-15", "en_US.UTF-8", "en_ZA", "en_ZA.ISO-8859-1", "en_ZA.UTF-8", "en_ZM", "en_ZM.UTF-8", "en_ZW", "en_ZW.ISO-8859-1", "en_ZW.UTF-8", "es_AR", "es_AR.ISO-8859-1", "es_AR.UTF-8", "es_BO", "es_BO.ISO-8859-1", "es_BO.UTF-8", "es_CL", "es_CL.ISO-8859-1", "es_CL.UTF-8", "es_CO", "es_CO.ISO-8859-1", "es_CO.UTF-8", "es_CR", "es_CR.ISO-8859-1", "es_CR.UTF-8", "es_CU", "es_CU.UTF-8", "es_DO", "es_DO.ISO-8859-1", "es_DO.UTF-8", "es_EC", "es_EC.ISO-8859-1", "es_EC.UTF-8", "es_ES", "es_ES.ISO-8859-1", "es_ES.UTF-8", "es_GT", "es_GT.ISO-8859-1", "es_GT.UTF-8", "es_HN", "es_HN.ISO-8859-1", "es_HN.UTF-8", "es_MX", "es_MX.ISO-8859-1", "es_MX.UTF-8", "es_NI", "es_NI.ISO-8859-1", "es_NI.UTF-8", "es_PA", "es_PA.ISO-8859-1", "es_PA.UTF-8", "es_PE", "es_PE.ISO-8859-1", "es_PE.UTF-8", "es_PR", "es_PR.ISO-8859-1", "es_PR.UTF-8", "es_PY", "es_PY.ISO-8859-1", "es_PY.UTF-8", "es_SV", "es_SV.ISO-8859-1", "es_SV.UTF-8", "es_US", "es_US.ISO-8859-1", "es_US.UTF-8", "es_UY", "es_UY.ISO-8859-1", "es_UY.UTF-8", "es_VE", "es_VE.ISO-8859-1", "es_VE.UTF-8", "et_EE", "et_EE.ISO-8859-1", "et_EE.ISO-8859-15", "et_EE.UTF-8", "eu_ES", "eu_ES.ISO-8859-1", "eu_ES.UTF-8", "eu_FR", "eu_FR.ISO-8859-1", "eu_FR.UTF-8", "fa_IR", "fa_IR.UTF-8", "ff_SN", "ff_SN.UTF-8", "fi_FI", "fi_FI.ISO-8859-1", "fi_FI.UTF-8", "fil_PH", "fil_PH.UTF-8", "fo_FO", "fo_FO.ISO-8859-1", "fo_FO.UTF-8", "fr_BE", "fr_BE.ISO-8859-1", "fr_BE.UTF-8", "fr_CA", "fr_CA.ISO-8859-1", "fr_CA.UTF-8", "fr_CH", "fr_CH.ISO-8859-1", "fr_CH.UTF-8", "fr_FR", "fr_FR.ISO-8859-1", "fr_FR.UTF-8", "fr_LU", "fr_LU.ISO-8859-1", "fr_LU.UTF-8", "fur_IT", "fur_IT.UTF-8", "fy_DE", "fy_DE.UTF-8", "fy_NL", "fy_NL.UTF-8", "ga_IE", "ga_IE.ISO-8859-1", "ga_IE.UTF-8", "gd_GB", "gd_GB.ISO-8859-15", "gd_GB.UTF-8", "gez_ER", "gez_ER.UTF-8", "gez_ET", "gez_ET.UTF-8", "gl_ES", "gl_ES.ISO-8859-1", "gl_ES.UTF-8", "gu_IN", "gu_IN.UTF-8", "gv_GB", "gv_GB.ISO-8859-1", "gv_GB.UTF-8", "hak_TW", "hak_TW.UTF-8", "ha_NG", "ha_NG.UTF-8", "he_IL", "he_IL.ISO-8859-8", "he_IL.UTF-8", "hif_FJ", "hif_FJ.UTF-8", "hi_IN", "hi_IN.UTF-8", "hne_IN", "hne_IN.UTF-8", "hr_HR", "hr_HR.ISO-8859-2", "hr_HR.UTF-8", "hsb_DE", "hsb_DE.ISO-8859-2", "hsb_DE.UTF-8", "ht_HT", "ht_HT.UTF-8", "hu_HU", "hu_HU.ISO-8859-2", "hu_HU.UTF-8", "hy_AM", "hy_AM.ARMSCII-8", "hy_AM.UTF-8", "ia_FR", "ia_FR.UTF-8", "id_ID", "id_ID.ISO-8859-1", "id_ID.UTF-8", "ig_NG", "ig_NG.UTF-8", "ik_CA", "ik_CA.UTF-8", "is_IS", "is_IS.ISO-8859-1", "is_IS.UTF-8", "it_CH", "it_CH.ISO-8859-1", "it_CH.UTF-8", "it_IT", "it_IT.ISO-8859-1", "it_IT.UTF-8", "iu_CA", "iu_CA.UTF-8", "kab_DZ", "kab_DZ.UTF-8", "ka_GE", "ka_GE.GEORGIAN-PS", "ka_GE.UTF-8", "kk_KZ", "kk_KZ.PT154", "kk_KZ.RK1048", "kk_KZ.UTF-8", "kl_GL", "kl_GL.ISO-8859-1", "kl_GL.UTF-8", "km_KH", "km_KH.UTF-8", "kn_IN", "kn_IN.UTF-8", "kok_IN", "kok_IN.UTF-8", "ks_IN", "ks_IN.UTF-8", "ku_TR", "ku_TR.ISO-8859-9", "ku_TR.UTF-8", "kw_GB", "kw_GB.ISO-8859-1", "kw_GB.UTF-8", "ky_KG", "ky_KG.UTF-8", "lb_LU", "lb_LU.UTF-8", "lg_UG", "lg_UG.ISO-8859-10", "lg_UG.UTF-8", "li_BE", "li_BE.UTF-8", "lij_IT", "lij_IT.UTF-8", "li_NL", "li_NL.UTF-8", "ln_CD", "ln_CD.UTF-8", "lo_LA", "lo_LA.UTF-8", "lt_LT", "lt_LT.ISO-8859-13", "lt_LT.UTF-8", "lv_LV", "lv_LV.ISO-8859-13", "lv_LV.UTF-8", "lzh_TW", "lzh_TW.UTF-8", "mag_IN", "mag_IN.UTF-8", "mai_IN", "mai_IN.UTF-8", "mai_NP", "mai_NP.UTF-8", "mfe_MU", "mfe_MU.UTF-8", "mg_MG", "mg_MG.ISO-8859-15", "mg_MG.UTF-8", "mhr_RU", "mhr_RU.UTF-8", "mi_NZ", "mi_NZ.ISO-8859-13", "mi_NZ.UTF-8", "miq_NI", "miq_NI.UTF-8", "mjw_IN", "mjw_IN.UTF-8", "mk_MK", "mk_MK.ISO-8859-5", "mk_MK.UTF-8", "ml_IN", "ml_IN.UTF-8", "mni_IN", "mni_IN.UTF-8", "mn_MN", "mn_MN.UTF-8", "mr_IN", "mr_IN.UTF-8", "ms_MY", "ms_MY.ISO-8859-1", "ms_MY.UTF-8", "mt_MT", "mt_MT.ISO-8859-3", "mt_MT.UTF-8", "my_MM", "my_MM.UTF-8", "nan_TW", "nan_TW.UTF-8", "nb_NO", "nb_NO.ISO-8859-1", "nb_NO.UTF-8", "nds_DE", "nds_DE.UTF-8", "nds_NL", "nds_NL.UTF-8", "ne_NP", "ne_NP.UTF-8", "nhn_MX", "nhn_MX.UTF-8", "niu_NU", "niu_NU.UTF-8", "niu_NZ", "niu_NZ.UTF-8", "nl_AW", "nl_AW.UTF-8", "nl_BE", "nl_BE.ISO-8859-1", "nl_BE.UTF-8", "nl_NL", "nl_NL.ISO-8859-1", "nl_NL.UTF-8", "nn_NO", "nn_NO.ISO-8859-1", "nn_NO.UTF-8", "nr_ZA", "nr_ZA.UTF-8", "nso_ZA", "nso_ZA.UTF-8", "oc_FR", "oc_FR.ISO-8859-1", "oc_FR.UTF-8", "om_ET", "om_ET.UTF-8", "om_KE", "om_KE.ISO-8859-1", "om_KE.UTF-8", "or_IN", "or_IN.UTF-8", "os_RU", "os_RU.UTF-8", "pa_IN", "pa_IN.UTF-8", "pap_AW", "pap_AW.UTF-8", "pap_CW", "pap_CW.UTF-8", "pa_PK", "pa_PK.UTF-8", "pl_PL", "pl_PL.ISO-8859-2", "pl_PL.UTF-8", "ps_AF", "ps_AF.UTF-8", "pt_BR", "pt_BR.ISO-8859-1", "pt_BR.UTF-8", "pt_PT", "pt_PT.ISO-8859-1", "pt_PT.UTF-8", "quz_PE", "quz_PE.UTF-8", "raj_IN", "raj_IN.UTF-8", "ro_RO", "ro_RO.ISO-8859-2", "ro_RO.UTF-8", "ru_RU", "ru_RU.CP1251", "ru_RU.ISO-8859-5", "ru_RU.KOI8-R", "ru_RU.UTF-8", "ru_UA", "ru_UA.KOI8-U", "ru_UA.UTF-8", "rw_RW", "rw_RW.UTF-8", "sa_IN", "sa_IN.UTF-8", "sat_IN", "sat_IN.UTF-8", "sc_IT", "sc_IT.UTF-8", "sd_IN", "sd_IN.UTF-8", "sd_PK", "sd_PK.UTF-8", "se_NO", "se_NO.UTF-8", "sgs_LT", "sgs_LT.UTF-8", "shn_MM", "shn_MM.UTF-8", "shs_CA", "shs_CA.UTF-8", "sid_ET", "sid_ET.UTF-8", "si_LK", "si_LK.UTF-8", "sk_SK", "sk_SK.ISO-8859-2", "sk_SK.UTF-8", "sl_SI", "sl_SI.ISO-8859-2", "sl_SI.UTF-8", "sm_WS", "sm_WS.UTF-8", "so_DJ", "so_DJ.ISO-8859-1", "so_DJ.UTF-8", "so_ET", "so_ET.UTF-8", "so_KE", "so_KE.ISO-8859-1", "so_KE.UTF-8", "so_SO", "so_SO.ISO-8859-1", "so_SO.UTF-8", "sq_AL", "sq_AL.ISO-8859-1", "sq_AL.UTF-8", "sq_MK", "sq_MK.UTF-8", "sr_ME", "sr_ME.UTF-8", "sr_RS", "sr_RS.UTF-8", "ss_ZA", "ss_ZA.UTF-8", "st_ZA", "st_ZA.ISO-8859-1", "st_ZA.UTF-8", "sv_FI", "sv_FI.ISO-8859-1", "sv_FI.UTF-8", "sv_SE", "sv_SE.ISO-8859-1", "sv_SE.ISO-8859-15", "sv_SE.UTF-8", "sw_KE", "sw_KE.UTF-8", "sw_TZ", "sw_TZ.UTF-8", "szl_PL", "szl_PL.UTF-8", "ta_IN", "ta_IN.UTF-8", "ta_LK", "ta_LK.UTF-8", "te_IN", "te_IN.UTF-8", "tg_TJ", "tg_TJ.KOI8-T", "tg_TJ.UTF-8", "the_NP", "the_NP.UTF-8", "th_TH", "th_TH.TIS-620", "th_TH.UTF-8", "ti_ER", "ti_ER.UTF-8", "ti_ET", "ti_ET.UTF-8", "tig_ER", "tig_ER.UTF-8", "tk_TM", "tk_TM.UTF-8", "tl_PH", "tl_PH.ISO-8859-1", "tl_PH.UTF-8", "tn_ZA", "tn_ZA.UTF-8", "to_TO", "to_TO.UTF-8", "tpi_PG", "tpi_PG.UTF-8", "tr_CY", "tr_CY.ISO-8859-9", "tr_CY.UTF-8", "tr_TR", "tr_TR.ISO-8859-9", "tr_TR.UTF-8", "ts_ZA", "ts_ZA.UTF-8", "tt_RU", "tt_RU.UTF-8", "ug_CN", "ug_CN.UTF-8", "uk_UA", "uk_UA.KOI8-U", "uk_UA.UTF-8", "unm_US", "unm_US.UTF-8", "ur_IN", "ur_IN.UTF-8", "ur_PK", "ur_PK.UTF-8", "uz_UZ", "uz_UZ.ISO-8859-1", "uz_UZ.UTF-8", "ve_ZA", "ve_ZA.UTF-8", "vi_VN", "vi_VN.UTF-8", "wa_BE", "wa_BE.ISO-8859-1", "wa_BE.UTF-8", "wae_CH", "wae_CH.UTF-8", "wal_ET", "wal_ET.UTF-8", "wo_SN", "wo_SN.UTF-8", "xh_ZA", "xh_ZA.ISO-8859-1", "xh_ZA.UTF-8", "yi_US", "yi_US.CP1255", "yi_US.UTF-8", "yo_NG", "yo_NG.UTF-8", "yue_HK", "yue_HK.UTF-8", "yuw_PG", "yuw_PG.UTF-8", "zh_CN", "zh_CN.GB18030", "zh_CN.GB2312", "zh_CN.GBK", "zh_CN.UTF-8", "zh_HK", "zh_HK.BIG5-HKSCS", "zh_HK.UTF-8", "zh_SG", "zh_SG.GB2312", "zh_SG.GBK", "zh_SG.UTF-8", "zh_TW", "zh_TW.BIG5", "zh_TW.EUC-TW", "zh_TW.UTF-8", "zu_ZA", "zu_ZA.ISO-8859-1", "zu_ZA.UTF-8"}; std::string ConsumeLocaleIdentifier(FuzzedDataProvider& fuzzed_data_provider) { return fuzzed_data_provider.PickValueInArray<std::string>(locale_identifiers); } bool IsAvailableLocale(const std::string& locale_identifier) { try { (void)std::locale(locale_identifier); } catch (const std::runtime_error&) { return false; } return true; } } // namespace FUZZ_TARGET(locale) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::string locale_identifier = ConsumeLocaleIdentifier(fuzzed_data_provider); if (!IsAvailableLocale(locale_identifier)) { return; } const char* c_locale = std::setlocale(LC_ALL, "C"); assert(c_locale != nullptr); const std::string random_string = fuzzed_data_provider.ConsumeRandomLengthString(5); int32_t parseint32_out_without_locale; const bool parseint32_without_locale = ParseInt32(random_string, &parseint32_out_without_locale); int64_t parseint64_out_without_locale; const bool parseint64_without_locale = ParseInt64(random_string, &parseint64_out_without_locale); const int64_t random_int64 = fuzzed_data_provider.ConsumeIntegral<int64_t>(); const std::string tostring_without_locale = ToString(random_int64); // The variable `random_int32` is no longer used, but the harness still needs to // consume the same data that it did previously to not invalidate existing seeds. const int32_t random_int32 = fuzzed_data_provider.ConsumeIntegral<int32_t>(); (void)random_int32; const std::string strprintf_int_without_locale = strprintf("%d", random_int64); const double random_double = fuzzed_data_provider.ConsumeFloatingPoint<double>(); const std::string strprintf_double_without_locale = strprintf("%f", random_double); const char* new_locale = std::setlocale(LC_ALL, locale_identifier.c_str()); assert(new_locale != nullptr); int32_t parseint32_out_with_locale; const bool parseint32_with_locale = ParseInt32(random_string, &parseint32_out_with_locale); assert(parseint32_without_locale == parseint32_with_locale); if (parseint32_without_locale) { assert(parseint32_out_without_locale == parseint32_out_with_locale); } int64_t parseint64_out_with_locale; const bool parseint64_with_locale = ParseInt64(random_string, &parseint64_out_with_locale); assert(parseint64_without_locale == parseint64_with_locale); if (parseint64_without_locale) { assert(parseint64_out_without_locale == parseint64_out_with_locale); } const std::string tostring_with_locale = ToString(random_int64); assert(tostring_without_locale == tostring_with_locale); const std::string strprintf_int_with_locale = strprintf("%d", random_int64); assert(strprintf_int_without_locale == strprintf_int_with_locale); const std::string strprintf_double_with_locale = strprintf("%f", random_double); assert(strprintf_double_without_locale == strprintf_double_with_locale); const std::locale current_cpp_locale; assert(current_cpp_locale == std::locale::classic()); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/message.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <key_io.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/chaintype.h> #include <util/message.h> #include <util/strencodings.h> #include <cassert> #include <cstdint> #include <iostream> #include <string> #include <vector> void initialize_message() { ECC_Start(); SelectParams(ChainType::REGTEST); } FUZZ_TARGET(message, .init = initialize_message) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::string random_message = fuzzed_data_provider.ConsumeRandomLengthString(1024); { CKey private_key = ConsumePrivateKey(fuzzed_data_provider); std::string signature; const bool message_signed = MessageSign(private_key, random_message, signature); if (private_key.IsValid()) { assert(message_signed); const MessageVerificationResult verification_result = MessageVerify(EncodeDestination(PKHash(private_key.GetPubKey().GetID())), signature, random_message); assert(verification_result == MessageVerificationResult::OK); } } { (void)MessageHash(random_message); (void)MessageVerify(fuzzed_data_provider.ConsumeRandomLengthString(1024), fuzzed_data_provider.ConsumeRandomLengthString(1024), random_message); (void)SigningResultString(fuzzed_data_provider.PickValueInArray({SigningResult::OK, SigningResult::PRIVATE_KEY_NOT_AVAILABLE, SigningResult::SIGNING_FAILED})); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/miniscript.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <hash.h> #include <key.h> #include <script/miniscript.h> #include <script/script.h> #include <script/signingprovider.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/strencodings.h> namespace { using Fragment = miniscript::Fragment; using NodeRef = miniscript::NodeRef<CPubKey>; using Node = miniscript::Node<CPubKey>; using Type = miniscript::Type; using MsCtx = miniscript::MiniscriptContext; using miniscript::operator"" _mst; //! Some pre-computed data for more efficient string roundtrips and to simulate challenges. struct TestData { typedef CPubKey Key; // Precomputed public keys, and a dummy signature for each of them. std::vector<Key> dummy_keys; std::map<Key, int> dummy_key_idx_map; std::map<CKeyID, Key> dummy_keys_map; std::map<Key, std::pair<std::vector<unsigned char>, bool>> dummy_sigs; std::map<XOnlyPubKey, std::pair<std::vector<unsigned char>, bool>> schnorr_sigs; // Precomputed hashes of each kind. std::vector<std::vector<unsigned char>> sha256; std::vector<std::vector<unsigned char>> ripemd160; std::vector<std::vector<unsigned char>> hash256; std::vector<std::vector<unsigned char>> hash160; std::map<std::vector<unsigned char>, std::vector<unsigned char>> sha256_preimages; std::map<std::vector<unsigned char>, std::vector<unsigned char>> ripemd160_preimages; std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash256_preimages; std::map<std::vector<unsigned char>, std::vector<unsigned char>> hash160_preimages; //! Set the precomputed data. void Init() { unsigned char keydata[32] = {1}; // All our signatures sign (and are required to sign) this constant message. auto const MESSAGE_HASH{uint256S("f5cd94e18b6fe77dd7aca9e35c2b0c9cbd86356c80a71065")}; // We don't pass additional randomness when creating a schnorr signature. auto const EMPTY_AUX{uint256S("")}; for (size_t i = 0; i < 256; i++) { keydata[31] = i; CKey privkey; privkey.Set(keydata, keydata + 32, true); const Key pubkey = privkey.GetPubKey(); dummy_keys.push_back(pubkey); dummy_key_idx_map.emplace(pubkey, i); dummy_keys_map.insert({pubkey.GetID(), pubkey}); XOnlyPubKey xonly_pubkey{pubkey}; dummy_key_idx_map.emplace(xonly_pubkey, i); uint160 xonly_hash{Hash160(xonly_pubkey)}; dummy_keys_map.emplace(xonly_hash, pubkey); std::vector<unsigned char> sig, schnorr_sig(64); privkey.Sign(MESSAGE_HASH, sig); sig.push_back(1); // SIGHASH_ALL dummy_sigs.insert({pubkey, {sig, i & 1}}); assert(privkey.SignSchnorr(MESSAGE_HASH, schnorr_sig, nullptr, EMPTY_AUX)); schnorr_sig.push_back(1); // Maximally-sized signature has sighash byte schnorr_sigs.emplace(XOnlyPubKey{pubkey}, std::make_pair(std::move(schnorr_sig), i & 1)); std::vector<unsigned char> hash; hash.resize(32); CSHA256().Write(keydata, 32).Finalize(hash.data()); sha256.push_back(hash); if (i & 1) sha256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32); CHash256().Write(keydata).Finalize(hash); hash256.push_back(hash); if (i & 1) hash256_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32); hash.resize(20); CRIPEMD160().Write(keydata, 32).Finalize(hash.data()); assert(hash.size() == 20); ripemd160.push_back(hash); if (i & 1) ripemd160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32); CHash160().Write(keydata).Finalize(hash); hash160.push_back(hash); if (i & 1) hash160_preimages[hash] = std::vector<unsigned char>(keydata, keydata + 32); } } //! Get the (Schnorr or ECDSA, depending on context) signature for this pubkey. const std::pair<std::vector<unsigned char>, bool>* GetSig(const MsCtx script_ctx, const Key& key) const { if (!miniscript::IsTapscript(script_ctx)) { const auto it = dummy_sigs.find(key); if (it == dummy_sigs.end()) return nullptr; return &it->second; } else { const auto it = schnorr_sigs.find(XOnlyPubKey{key}); if (it == schnorr_sigs.end()) return nullptr; return &it->second; } } } TEST_DATA; /** * Context to parse a Miniscript node to and from Script or text representation. * Uses an integer (an index in the dummy keys array from the test data) as keys in order * to focus on fuzzing the Miniscript nodes' test representation, not the key representation. */ struct ParserContext { typedef CPubKey Key; const MsCtx script_ctx; constexpr ParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {} bool KeyCompare(const Key& a, const Key& b) const { return a < b; } std::optional<std::string> ToString(const Key& key) const { auto it = TEST_DATA.dummy_key_idx_map.find(key); if (it == TEST_DATA.dummy_key_idx_map.end()) return {}; uint8_t idx = it->second; return HexStr(Span{&idx, 1}); } std::vector<unsigned char> ToPKBytes(const Key& key) const { if (!miniscript::IsTapscript(script_ctx)) { return {key.begin(), key.end()}; } const XOnlyPubKey xonly_pubkey{key}; return {xonly_pubkey.begin(), xonly_pubkey.end()}; } std::vector<unsigned char> ToPKHBytes(const Key& key) const { if (!miniscript::IsTapscript(script_ctx)) { const auto h = Hash160(key); return {h.begin(), h.end()}; } const auto h = Hash160(XOnlyPubKey{key}); return {h.begin(), h.end()}; } template<typename I> std::optional<Key> FromString(I first, I last) const { if (last - first != 2) return {}; auto idx = ParseHex(std::string(first, last)); if (idx.size() != 1) return {}; return TEST_DATA.dummy_keys[idx[0]]; } template<typename I> std::optional<Key> FromPKBytes(I first, I last) const { if (!miniscript::IsTapscript(script_ctx)) { Key key{first, last}; if (key.IsValid()) return key; return {}; } if (last - first != 32) return {}; XOnlyPubKey xonly_pubkey; std::copy(first, last, xonly_pubkey.begin()); return xonly_pubkey.GetEvenCorrespondingCPubKey(); } template<typename I> std::optional<Key> FromPKHBytes(I first, I last) const { assert(last - first == 20); CKeyID keyid; std::copy(first, last, keyid.begin()); const auto it = TEST_DATA.dummy_keys_map.find(keyid); if (it == TEST_DATA.dummy_keys_map.end()) return {}; return it->second; } MsCtx MsContext() const { return script_ctx; } }; //! Context that implements naive conversion from/to script only, for roundtrip testing. struct ScriptParserContext { const MsCtx script_ctx; constexpr ScriptParserContext(MsCtx ctx) noexcept : script_ctx(ctx) {} //! For Script roundtrip we never need the key from a key hash. struct Key { bool is_hash; std::vector<unsigned char> data; }; bool KeyCompare(const Key& a, const Key& b) const { return a.data < b.data; } const std::vector<unsigned char>& ToPKBytes(const Key& key) const { assert(!key.is_hash); return key.data; } std::vector<unsigned char> ToPKHBytes(const Key& key) const { if (key.is_hash) return key.data; const auto h = Hash160(key.data); return {h.begin(), h.end()}; } template<typename I> std::optional<Key> FromPKBytes(I first, I last) const { Key key; key.data.assign(first, last); key.is_hash = false; return key; } template<typename I> std::optional<Key> FromPKHBytes(I first, I last) const { Key key; key.data.assign(first, last); key.is_hash = true; return key; } MsCtx MsContext() const { return script_ctx; } }; //! Context to produce a satisfaction for a Miniscript node using the pre-computed data. struct SatisfierContext : ParserContext { constexpr SatisfierContext(MsCtx ctx) noexcept : ParserContext(ctx) {} // Timelock challenges satisfaction. Make the value (deterministically) vary to explore different // paths. bool CheckAfter(uint32_t value) const { return value % 2; } bool CheckOlder(uint32_t value) const { return value % 2; } // Signature challenges fulfilled with a dummy signature, if it was one of our dummy keys. miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const { bool sig_available{false}; if (auto res = TEST_DATA.GetSig(script_ctx, key)) { std::tie(sig, sig_available) = *res; } return sig_available ? miniscript::Availability::YES : miniscript::Availability::NO; } //! Lookup generalization for all the hash satisfactions below miniscript::Availability LookupHash(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage, const std::map<std::vector<unsigned char>, std::vector<unsigned char>>& map) const { const auto it = map.find(hash); if (it == map.end()) return miniscript::Availability::NO; preimage = it->second; return miniscript::Availability::YES; } miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { return LookupHash(hash, preimage, TEST_DATA.sha256_preimages); } miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { return LookupHash(hash, preimage, TEST_DATA.ripemd160_preimages); } miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { return LookupHash(hash, preimage, TEST_DATA.hash256_preimages); } miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { return LookupHash(hash, preimage, TEST_DATA.hash160_preimages); } }; //! Context to check a satisfaction against the pre-computed data. const struct CheckerContext: BaseSignatureChecker { // Signature checker methods. Checks the right dummy signature is used. bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { const CPubKey key{vchPubKey}; const auto it = TEST_DATA.dummy_sigs.find(key); if (it == TEST_DATA.dummy_sigs.end()) return false; return it->second.first == sig; } bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion, ScriptExecutionData&, ScriptError*) const override { XOnlyPubKey pk{pubkey}; auto it = TEST_DATA.schnorr_sigs.find(pk); if (it == TEST_DATA.schnorr_sigs.end()) return false; return it->second.first == sig; } bool CheckLockTime(const CScriptNum& nLockTime) const override { return nLockTime.GetInt64() & 1; } bool CheckSequence(const CScriptNum& nSequence) const override { return nSequence.GetInt64() & 1; } } CHECKER_CTX; //! Context to check for duplicates when instancing a Node. const struct KeyComparator { bool KeyCompare(const CPubKey& a, const CPubKey& b) const { return a < b; } } KEY_COMP; // A dummy scriptsig to pass to VerifyScript (we always use Segwit v0). const CScript DUMMY_SCRIPTSIG; //! Public key to be used as internal key for dummy Taproot spends. const std::vector<unsigned char> NUMS_PK{ParseHex("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")}; //! Construct a miniscript node as a shared_ptr. template<typename... Args> NodeRef MakeNodeRef(Args&&... args) { return miniscript::MakeNodeRef<CPubKey>(miniscript::internal::NoDupCheck{}, std::forward<Args>(args)...); } /** Information about a yet to be constructed Miniscript node. */ struct NodeInfo { //! The type of this node Fragment fragment; //! The timelock value for older() and after(), the threshold value for multi() and thresh() uint32_t k; //! Keys for this node, if it has some std::vector<CPubKey> keys; //! The hash value for this node, if it has one std::vector<unsigned char> hash; //! The type requirements for the children of this node. std::vector<Type> subtypes; NodeInfo(Fragment frag): fragment(frag), k(0) {} NodeInfo(Fragment frag, CPubKey key): fragment(frag), k(0), keys({key}) {} NodeInfo(Fragment frag, uint32_t _k): fragment(frag), k(_k) {} NodeInfo(Fragment frag, std::vector<unsigned char> h): fragment(frag), k(0), hash(std::move(h)) {} NodeInfo(std::vector<Type> subt, Fragment frag): fragment(frag), k(0), subtypes(std::move(subt)) {} NodeInfo(std::vector<Type> subt, Fragment frag, uint32_t _k): fragment(frag), k(_k), subtypes(std::move(subt)) {} NodeInfo(Fragment frag, uint32_t _k, std::vector<CPubKey> _keys): fragment(frag), k(_k), keys(std::move(_keys)) {} }; /** Pick an index in a collection from a single byte in the fuzzer's output. */ template<typename T, typename A> T ConsumeIndex(FuzzedDataProvider& provider, A& col) { const uint8_t i = provider.ConsumeIntegral<uint8_t>(); return col[i]; } CPubKey ConsumePubKey(FuzzedDataProvider& provider) { return ConsumeIndex<CPubKey>(provider, TEST_DATA.dummy_keys); } std::vector<unsigned char> ConsumeSha256(FuzzedDataProvider& provider) { return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.sha256); } std::vector<unsigned char> ConsumeHash256(FuzzedDataProvider& provider) { return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash256); } std::vector<unsigned char> ConsumeRipemd160(FuzzedDataProvider& provider) { return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.ripemd160); } std::vector<unsigned char> ConsumeHash160(FuzzedDataProvider& provider) { return ConsumeIndex<std::vector<unsigned char>>(provider, TEST_DATA.hash160); } std::optional<uint32_t> ConsumeTimeLock(FuzzedDataProvider& provider) { const uint32_t k = provider.ConsumeIntegral<uint32_t>(); if (k == 0 || k >= 0x80000000) return {}; return k; } /** * Consume a Miniscript node from the fuzzer's output. * * This version is intended to have a fixed, stable, encoding for Miniscript nodes: * - The first byte sets the type of the fragment. 0, 1 and all non-leaf fragments but thresh() are a * single byte. * - For the other leaf fragments, the following bytes depend on their type. * - For older() and after(), the next 4 bytes define the timelock value. * - For pk_k(), pk_h(), and all hashes, the next byte defines the index of the value in the test data. * - For multi(), the next 2 bytes define respectively the threshold and the number of keys. Then as many * bytes as the number of keys define the index of each key in the test data. * - For multi_a(), same as for multi() but the threshold and the keys count are encoded on two bytes. * - For thresh(), the next byte defines the threshold value and the following one the number of subs. */ std::optional<NodeInfo> ConsumeNodeStable(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) { bool allow_B = (type_needed == ""_mst) || (type_needed << "B"_mst); bool allow_K = (type_needed == ""_mst) || (type_needed << "K"_mst); bool allow_V = (type_needed == ""_mst) || (type_needed << "V"_mst); bool allow_W = (type_needed == ""_mst) || (type_needed << "W"_mst); switch (provider.ConsumeIntegral<uint8_t>()) { case 0: if (!allow_B) return {}; return {{Fragment::JUST_0}}; case 1: if (!allow_B) return {}; return {{Fragment::JUST_1}}; case 2: if (!allow_K) return {}; return {{Fragment::PK_K, ConsumePubKey(provider)}}; case 3: if (!allow_K) return {}; return {{Fragment::PK_H, ConsumePubKey(provider)}}; case 4: { if (!allow_B) return {}; const auto k = ConsumeTimeLock(provider); if (!k) return {}; return {{Fragment::OLDER, *k}}; } case 5: { if (!allow_B) return {}; const auto k = ConsumeTimeLock(provider); if (!k) return {}; return {{Fragment::AFTER, *k}}; } case 6: if (!allow_B) return {}; return {{Fragment::SHA256, ConsumeSha256(provider)}}; case 7: if (!allow_B) return {}; return {{Fragment::HASH256, ConsumeHash256(provider)}}; case 8: if (!allow_B) return {}; return {{Fragment::RIPEMD160, ConsumeRipemd160(provider)}}; case 9: if (!allow_B) return {}; return {{Fragment::HASH160, ConsumeHash160(provider)}}; case 10: { if (!allow_B || IsTapscript(script_ctx)) return {}; const auto k = provider.ConsumeIntegral<uint8_t>(); const auto n_keys = provider.ConsumeIntegral<uint8_t>(); if (n_keys > 20 || k == 0 || k > n_keys) return {}; std::vector<CPubKey> keys{n_keys}; for (auto& key: keys) key = ConsumePubKey(provider); return {{Fragment::MULTI, k, std::move(keys)}}; } case 11: if (!(allow_B || allow_K || allow_V)) return {}; return {{{"B"_mst, type_needed, type_needed}, Fragment::ANDOR}}; case 12: if (!(allow_B || allow_K || allow_V)) return {}; return {{{"V"_mst, type_needed}, Fragment::AND_V}}; case 13: if (!allow_B) return {}; return {{{"B"_mst, "W"_mst}, Fragment::AND_B}}; case 15: if (!allow_B) return {}; return {{{"B"_mst, "W"_mst}, Fragment::OR_B}}; case 16: if (!allow_V) return {}; return {{{"B"_mst, "V"_mst}, Fragment::OR_C}}; case 17: if (!allow_B) return {}; return {{{"B"_mst, "B"_mst}, Fragment::OR_D}}; case 18: if (!(allow_B || allow_K || allow_V)) return {}; return {{{type_needed, type_needed}, Fragment::OR_I}}; case 19: { if (!allow_B) return {}; auto k = provider.ConsumeIntegral<uint8_t>(); auto n_subs = provider.ConsumeIntegral<uint8_t>(); if (k == 0 || k > n_subs) return {}; std::vector<Type> subtypes; subtypes.reserve(n_subs); subtypes.emplace_back("B"_mst); for (size_t i = 1; i < n_subs; ++i) subtypes.emplace_back("W"_mst); return {{std::move(subtypes), Fragment::THRESH, k}}; } case 20: if (!allow_W) return {}; return {{{"B"_mst}, Fragment::WRAP_A}}; case 21: if (!allow_W) return {}; return {{{"B"_mst}, Fragment::WRAP_S}}; case 22: if (!allow_B) return {}; return {{{"K"_mst}, Fragment::WRAP_C}}; case 23: if (!allow_B) return {}; return {{{"V"_mst}, Fragment::WRAP_D}}; case 24: if (!allow_V) return {}; return {{{"B"_mst}, Fragment::WRAP_V}}; case 25: if (!allow_B) return {}; return {{{"B"_mst}, Fragment::WRAP_J}}; case 26: if (!allow_B) return {}; return {{{"B"_mst}, Fragment::WRAP_N}}; case 27: { if (!allow_B || !IsTapscript(script_ctx)) return {}; const auto k = provider.ConsumeIntegral<uint16_t>(); const auto n_keys = provider.ConsumeIntegral<uint16_t>(); if (n_keys > 999 || k == 0 || k > n_keys) return {}; std::vector<CPubKey> keys{n_keys}; for (auto& key: keys) key = ConsumePubKey(provider); return {{Fragment::MULTI_A, k, std::move(keys)}}; } default: break; } return {}; } /* This structure contains a table which for each "target" Type a list of recipes * to construct it, automatically inferred from the behavior of ComputeType. * Note that the Types here are not the final types of the constructed Nodes, but * just the subset that are required. For example, a recipe for the "Bo" type * might construct a "Bondu" sha256() NodeInfo, but cannot construct a "Bz" older(). * Each recipe is a Fragment together with a list of required types for its subnodes. */ struct SmartInfo { using recipe = std::pair<Fragment, std::vector<Type>>; std::map<Type, std::vector<recipe>> wsh_table, tap_table; void Init() { Init(wsh_table, MsCtx::P2WSH); Init(tap_table, MsCtx::TAPSCRIPT); } void Init(std::map<Type, std::vector<recipe>>& table, MsCtx script_ctx) { /* Construct a set of interesting type requirements to reason with (sections of BKVWzondu). */ std::vector<Type> types; for (int base = 0; base < 4; ++base) { /* select from B,K,V,W */ Type type_base = base == 0 ? "B"_mst : base == 1 ? "K"_mst : base == 2 ? "V"_mst : "W"_mst; for (int zo = 0; zo < 3; ++zo) { /* select from z,o,(none) */ Type type_zo = zo == 0 ? "z"_mst : zo == 1 ? "o"_mst : ""_mst; for (int n = 0; n < 2; ++n) { /* select from (none),n */ if (zo == 0 && n == 1) continue; /* z conflicts with n */ if (base == 3 && n == 1) continue; /* W conflicts with n */ Type type_n = n == 0 ? ""_mst : "n"_mst; for (int d = 0; d < 2; ++d) { /* select from (none),d */ if (base == 2 && d == 1) continue; /* V conflicts with d */ Type type_d = d == 0 ? ""_mst : "d"_mst; for (int u = 0; u < 2; ++u) { /* select from (none),u */ if (base == 2 && u == 1) continue; /* V conflicts with u */ Type type_u = u == 0 ? ""_mst : "u"_mst; Type type = type_base | type_zo | type_n | type_d | type_u; types.push_back(type); } } } } } /* We define a recipe a to be a super-recipe of recipe b if they use the same * fragment, the same number of subexpressions, and each of a's subexpression * types is a supertype of the corresponding subexpression type of b. * Within the set of recipes for the construction of a given type requirement, * no recipe should be a super-recipe of another (as the super-recipe is * applicable in every place the sub-recipe is, the sub-recipe is redundant). */ auto is_super_of = [](const recipe& a, const recipe& b) { if (a.first != b.first) return false; if (a.second.size() != b.second.size()) return false; for (size_t i = 0; i < a.second.size(); ++i) { if (!(b.second[i] << a.second[i])) return false; } return true; }; /* Sort the type requirements. Subtypes will always sort later (e.g. Bondu will * sort after Bo or Bu). As we'll be constructing recipes using these types, in * order, in what follows, we'll construct super-recipes before sub-recipes. * That means we never need to go back and delete a sub-recipe because a * super-recipe got added. */ std::sort(types.begin(), types.end()); // Iterate over all possible fragments. for (int fragidx = 0; fragidx <= int(Fragment::MULTI_A); ++fragidx) { int sub_count = 0; //!< The minimum number of child nodes this recipe has. int sub_range = 1; //!< The maximum number of child nodes for this recipe is sub_count+sub_range-1. size_t data_size = 0; size_t n_keys = 0; uint32_t k = 0; Fragment frag{fragidx}; // Only produce recipes valid in the given context. if ((!miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI_A) || (miniscript::IsTapscript(script_ctx) && frag == Fragment::MULTI)) { continue; } // Based on the fragment, determine #subs/data/k/keys to pass to ComputeType. */ switch (frag) { case Fragment::PK_K: case Fragment::PK_H: n_keys = 1; break; case Fragment::MULTI: case Fragment::MULTI_A: n_keys = 1; k = 1; break; case Fragment::OLDER: case Fragment::AFTER: k = 1; break; case Fragment::SHA256: case Fragment::HASH256: data_size = 32; break; case Fragment::RIPEMD160: case Fragment::HASH160: data_size = 20; break; case Fragment::JUST_0: case Fragment::JUST_1: break; case Fragment::WRAP_A: case Fragment::WRAP_S: case Fragment::WRAP_C: case Fragment::WRAP_D: case Fragment::WRAP_V: case Fragment::WRAP_J: case Fragment::WRAP_N: sub_count = 1; break; case Fragment::AND_V: case Fragment::AND_B: case Fragment::OR_B: case Fragment::OR_C: case Fragment::OR_D: case Fragment::OR_I: sub_count = 2; break; case Fragment::ANDOR: sub_count = 3; break; case Fragment::THRESH: // Thresh logic is executed for 1 and 2 arguments. Larger numbers use ad-hoc code to extend. sub_count = 1; sub_range = 2; k = 1; break; } // Iterate over the number of subnodes (sub_count...sub_count+sub_range-1). std::vector<Type> subt; for (int subs = sub_count; subs < sub_count + sub_range; ++subs) { // Iterate over the possible subnode types (at most 3). for (Type x : types) { for (Type y : types) { for (Type z : types) { // Compute the resulting type of a node with the selected fragment / subnode types. subt.clear(); if (subs > 0) subt.push_back(x); if (subs > 1) subt.push_back(y); if (subs > 2) subt.push_back(z); Type res = miniscript::internal::ComputeType(frag, x, y, z, subt, k, data_size, subs, n_keys, script_ctx); // Continue if the result is not a valid node. if ((res << "K"_mst) + (res << "V"_mst) + (res << "B"_mst) + (res << "W"_mst) != 1) continue; recipe entry{frag, subt}; auto super_of_entry = [&](const recipe& rec) { return is_super_of(rec, entry); }; // Iterate over all supertypes of res (because if e.g. our selected fragment/subnodes result // in a Bondu, they can form a recipe that is also applicable for constructing a B, Bou, Bdu, ...). for (Type s : types) { if ((res & "BKVWzondu"_mst) << s) { auto& recipes = table[s]; // If we don't already have a super-recipe to the new one, add it. if (!std::any_of(recipes.begin(), recipes.end(), super_of_entry)) { recipes.push_back(entry); } } } if (subs <= 2) break; } if (subs <= 1) break; } if (subs <= 0) break; } } } /* Find which types are useful. The fuzzer logic only cares about constructing * B,V,K,W nodes, so any type that isn't needed in any recipe (directly or * indirectly) for the construction of those is uninteresting. */ std::set<Type> useful_types{"B"_mst, "V"_mst, "K"_mst, "W"_mst}; // Find the transitive closure by adding types until the set of types does not change. while (true) { size_t set_size = useful_types.size(); for (const auto& [type, recipes] : table) { if (useful_types.count(type) != 0) { for (const auto& [_, subtypes] : recipes) { for (auto subtype : subtypes) useful_types.insert(subtype); } } } if (useful_types.size() == set_size) break; } // Remove all rules that construct uninteresting types. for (auto type_it = table.begin(); type_it != table.end();) { if (useful_types.count(type_it->first) == 0) { type_it = table.erase(type_it); } else { ++type_it; } } /* Find which types are constructible. A type is constructible if there is a leaf * node recipe for constructing it, or a recipe whose subnodes are all constructible. * Types can be non-constructible because they have no recipes to begin with, * because they can only be constructed using recipes that involve otherwise * non-constructible types, or because they require infinite recursion. */ std::set<Type> constructible_types{}; auto known_constructible = [&](Type type) { return constructible_types.count(type) != 0; }; // Find the transitive closure by adding types until the set of types does not change. while (true) { size_t set_size = constructible_types.size(); // Iterate over all types we have recipes for. for (const auto& [type, recipes] : table) { if (!known_constructible(type)) { // For not (yet known to be) constructible types, iterate over their recipes. for (const auto& [_, subt] : recipes) { // If any recipe involves only (already known to be) constructible types, // add the recipe's type to the set. if (std::all_of(subt.begin(), subt.end(), known_constructible)) { constructible_types.insert(type); break; } } } } if (constructible_types.size() == set_size) break; } for (auto type_it = table.begin(); type_it != table.end();) { // Remove all recipes which involve non-constructible types. type_it->second.erase(std::remove_if(type_it->second.begin(), type_it->second.end(), [&](const recipe& rec) { return !std::all_of(rec.second.begin(), rec.second.end(), known_constructible); }), type_it->second.end()); // Delete types entirely which have no recipes left. if (type_it->second.empty()) { type_it = table.erase(type_it); } else { ++type_it; } } for (auto& [type, recipes] : table) { // Sort recipes for determinism, and place those using fewer subnodes first. // This avoids runaway expansion (when reaching the end of the fuzz input, // all zeroes are read, resulting in the first available recipe being picked). std::sort(recipes.begin(), recipes.end(), [](const recipe& a, const recipe& b) { if (a.second.size() < b.second.size()) return true; if (a.second.size() > b.second.size()) return false; return a < b; } ); } } } SMARTINFO; /** * Consume a Miniscript node from the fuzzer's output. * * This is similar to ConsumeNodeStable, but uses a precomputed table with permitted * fragments/subnode type for each required type. It is intended to more quickly explore * interesting miniscripts, at the cost of higher implementation complexity (which could * cause it miss things if incorrect), and with less regard for stability of the seeds * (as improvements to the tables or changes to the typing rules could invalidate * everything). */ std::optional<NodeInfo> ConsumeNodeSmart(MsCtx script_ctx, FuzzedDataProvider& provider, Type type_needed) { /** Table entry for the requested type. */ const auto& table{IsTapscript(script_ctx) ? SMARTINFO.tap_table : SMARTINFO.wsh_table}; auto recipes_it = table.find(type_needed); assert(recipes_it != table.end()); /** Pick one recipe from the available ones for that type. */ const auto& [frag, subt] = PickValue(provider, recipes_it->second); // Based on the fragment the recipe uses, fill in other data (k, keys, data). switch (frag) { case Fragment::PK_K: case Fragment::PK_H: return {{frag, ConsumePubKey(provider)}}; case Fragment::MULTI: { const auto n_keys = provider.ConsumeIntegralInRange<uint8_t>(1, 20); const auto k = provider.ConsumeIntegralInRange<uint8_t>(1, n_keys); std::vector<CPubKey> keys{n_keys}; for (auto& key: keys) key = ConsumePubKey(provider); return {{frag, k, std::move(keys)}}; } case Fragment::MULTI_A: { const auto n_keys = provider.ConsumeIntegralInRange<uint16_t>(1, 999); const auto k = provider.ConsumeIntegralInRange<uint16_t>(1, n_keys); std::vector<CPubKey> keys{n_keys}; for (auto& key: keys) key = ConsumePubKey(provider); return {{frag, k, std::move(keys)}}; } case Fragment::OLDER: case Fragment::AFTER: return {{frag, provider.ConsumeIntegralInRange<uint32_t>(1, 0x7FFFFFF)}}; case Fragment::SHA256: return {{frag, PickValue(provider, TEST_DATA.sha256)}}; case Fragment::HASH256: return {{frag, PickValue(provider, TEST_DATA.hash256)}}; case Fragment::RIPEMD160: return {{frag, PickValue(provider, TEST_DATA.ripemd160)}}; case Fragment::HASH160: return {{frag, PickValue(provider, TEST_DATA.hash160)}}; case Fragment::JUST_0: case Fragment::JUST_1: case Fragment::WRAP_A: case Fragment::WRAP_S: case Fragment::WRAP_C: case Fragment::WRAP_D: case Fragment::WRAP_V: case Fragment::WRAP_J: case Fragment::WRAP_N: case Fragment::AND_V: case Fragment::AND_B: case Fragment::OR_B: case Fragment::OR_C: case Fragment::OR_D: case Fragment::OR_I: case Fragment::ANDOR: return {{subt, frag}}; case Fragment::THRESH: { uint32_t children; if (subt.size() < 2) { children = subt.size(); } else { // If we hit a thresh with 2 subnodes, artificially extend it to any number // (2 or larger) by replicating the type of the last subnode. children = provider.ConsumeIntegralInRange<uint32_t>(2, MAX_OPS_PER_SCRIPT / 2); } auto k = provider.ConsumeIntegralInRange<uint32_t>(1, children); std::vector<Type> subs = subt; while (subs.size() < children) subs.push_back(subs.back()); return {{std::move(subs), frag, k}}; } } assert(false); } /** * Generate a Miniscript node based on the fuzzer's input. * * - ConsumeNode is a function object taking a Type, and returning an std::optional<NodeInfo>. * - root_type is the required type properties of the constructed NodeRef. * - strict_valid sets whether ConsumeNode is expected to guarantee a NodeInfo that results in * a NodeRef whose Type() matches the type fed to ConsumeNode. */ template<typename F> NodeRef GenNode(MsCtx script_ctx, F ConsumeNode, Type root_type, bool strict_valid = false) { /** A stack of miniscript Nodes being built up. */ std::vector<NodeRef> stack; /** The queue of instructions. */ std::vector<std::pair<Type, std::optional<NodeInfo>>> todo{{root_type, {}}}; /** Predict the number of (static) script ops. */ uint32_t ops{0}; /** Predict the total script size (every unexplored subnode is counted as one, as every leaf is * at least one script byte). */ uint32_t scriptsize{1}; while (!todo.empty()) { // The expected type we have to construct. auto type_needed = todo.back().first; if (!todo.back().second) { // Fragment/children have not been decided yet. Decide them. auto node_info = ConsumeNode(type_needed); if (!node_info) return {}; // Update predicted resource limits. Since every leaf Miniscript node is at least one // byte long, we move one byte from each child to their parent. A similar technique is // used in the miniscript::internal::Parse function to prevent runaway string parsing. scriptsize += miniscript::internal::ComputeScriptLen(node_info->fragment, ""_mst, node_info->subtypes.size(), node_info->k, node_info->subtypes.size(), node_info->keys.size(), script_ctx) - 1; if (scriptsize > MAX_STANDARD_P2WSH_SCRIPT_SIZE) return {}; switch (node_info->fragment) { case Fragment::JUST_0: case Fragment::JUST_1: break; case Fragment::PK_K: break; case Fragment::PK_H: ops += 3; break; case Fragment::OLDER: case Fragment::AFTER: ops += 1; break; case Fragment::RIPEMD160: case Fragment::SHA256: case Fragment::HASH160: case Fragment::HASH256: ops += 4; break; case Fragment::ANDOR: ops += 3; break; case Fragment::AND_V: break; case Fragment::AND_B: case Fragment::OR_B: ops += 1; break; case Fragment::OR_C: ops += 2; break; case Fragment::OR_D: ops += 3; break; case Fragment::OR_I: ops += 3; break; case Fragment::THRESH: ops += node_info->subtypes.size(); break; case Fragment::MULTI: ops += 1; break; case Fragment::MULTI_A: ops += node_info->keys.size() + 1; break; case Fragment::WRAP_A: ops += 2; break; case Fragment::WRAP_S: ops += 1; break; case Fragment::WRAP_C: ops += 1; break; case Fragment::WRAP_D: ops += 3; break; case Fragment::WRAP_V: // We don't account for OP_VERIFY here; that will be corrected for when the actual // node is constructed below. break; case Fragment::WRAP_J: ops += 4; break; case Fragment::WRAP_N: ops += 1; break; } if (ops > MAX_OPS_PER_SCRIPT) return {}; auto subtypes = node_info->subtypes; todo.back().second = std::move(node_info); todo.reserve(todo.size() + subtypes.size()); // As elements on the todo stack are processed back to front, construct // them in reverse order (so that the first subnode is generated first). for (size_t i = 0; i < subtypes.size(); ++i) { todo.emplace_back(*(subtypes.rbegin() + i), std::nullopt); } } else { // The back of todo has fragment and number of children decided, and // those children have been constructed at the back of stack. Pop // that entry off todo, and use it to construct a new NodeRef on // stack. NodeInfo& info = *todo.back().second; // Gather children from the back of stack. std::vector<NodeRef> sub; sub.reserve(info.subtypes.size()); for (size_t i = 0; i < info.subtypes.size(); ++i) { sub.push_back(std::move(*(stack.end() - info.subtypes.size() + i))); } stack.erase(stack.end() - info.subtypes.size(), stack.end()); // Construct new NodeRef. NodeRef node; if (info.keys.empty()) { node = MakeNodeRef(script_ctx, info.fragment, std::move(sub), std::move(info.hash), info.k); } else { assert(sub.empty()); assert(info.hash.empty()); node = MakeNodeRef(script_ctx, info.fragment, std::move(info.keys), info.k); } // Verify acceptability. if (!node || (node->GetType() & "KVWB"_mst) == ""_mst) { assert(!strict_valid); return {}; } if (!(type_needed == ""_mst)) { assert(node->GetType() << type_needed); } if (!node->IsValid()) return {}; // Update resource predictions. if (node->fragment == Fragment::WRAP_V && node->subs[0]->GetType() << "x"_mst) { ops += 1; scriptsize += 1; } if (!miniscript::IsTapscript(script_ctx) && ops > MAX_OPS_PER_SCRIPT) return {}; if (scriptsize > miniscript::internal::MaxScriptSize(script_ctx)) { return {}; } // Move it to the stack. stack.push_back(std::move(node)); todo.pop_back(); } } assert(stack.size() == 1); assert(stack[0]->GetStaticOps() == ops); assert(stack[0]->ScriptSize() == scriptsize); stack[0]->DuplicateKeyCheck(KEY_COMP); return std::move(stack[0]); } //! The spk for this script under the given context. If it's a Taproot output also record the spend data. CScript ScriptPubKey(MsCtx ctx, const CScript& script, TaprootBuilder& builder) { if (!miniscript::IsTapscript(ctx)) return CScript() << OP_0 << WitnessV0ScriptHash(script); // For Taproot outputs we always use a tree with a single script and a dummy internal key. builder.Add(0, script, TAPROOT_LEAF_TAPSCRIPT); builder.Finalize(XOnlyPubKey{NUMS_PK}); return GetScriptForDestination(builder.GetOutput()); } //! Fill the witness with the data additional to the script satisfaction. void SatisfactionToWitness(MsCtx ctx, CScriptWitness& witness, const CScript& script, TaprootBuilder& builder) { // For P2WSH, it's only the witness script. witness.stack.emplace_back(script.begin(), script.end()); if (!miniscript::IsTapscript(ctx)) return; // For Tapscript we also need the control block. witness.stack.push_back(*builder.GetSpendData().scripts.begin()->second.begin()); } /** Perform various applicable tests on a miniscript Node. */ void TestNode(const MsCtx script_ctx, const NodeRef& node, FuzzedDataProvider& provider) { if (!node) return; // Check that it roundtrips to text representation const ParserContext parser_ctx{script_ctx}; std::optional<std::string> str{node->ToString(parser_ctx)}; assert(str); auto parsed = miniscript::FromString(*str, parser_ctx); assert(parsed); assert(*parsed == *node); // Check consistency between script size estimation and real size. auto script = node->ToScript(parser_ctx); assert(node->ScriptSize() == script.size()); // Check consistency of "x" property with the script (type K is excluded, because it can end // with a push of a key, which could match these opcodes). if (!(node->GetType() << "K"_mst)) { bool ends_in_verify = !(node->GetType() << "x"_mst); assert(ends_in_verify == (script.back() == OP_CHECKSIG || script.back() == OP_CHECKMULTISIG || script.back() == OP_EQUAL || script.back() == OP_NUMEQUAL)); } // The rest of the checks only apply when testing a valid top-level script. if (!node->IsValidTopLevel()) return; // Check roundtrip to script auto decoded = miniscript::FromScript(script, parser_ctx); assert(decoded); // Note we can't use *decoded == *node because the miniscript representation may differ, so we check that: // - The script corresponding to that decoded form matches exactly // - The type matches exactly assert(decoded->ToScript(parser_ctx) == script); assert(decoded->GetType() == node->GetType()); // Optionally pad the script or the witness in order to increase the sensitivity of the tests of // the resources limits logic. CScriptWitness witness_mal, witness_nonmal; if (provider.ConsumeBool()) { // Under P2WSH, optionally pad the script with OP_NOPs to max op the ops limit of the constructed script. // This makes the script obviously not actually miniscript-compatible anymore, but the // signatures constructed in this test don't commit to the script anyway, so the same // miniscript satisfier will work. This increases the sensitivity of the test to the ops // counting logic being too low, especially for simple scripts. // Do this optionally because we're not solely interested in cases where the number of ops is // maximal. // Do not pad more than what would cause MAX_STANDARD_P2WSH_SCRIPT_SIZE to be reached, however, // as that also invalidates scripts. const auto node_ops{node->GetOps()}; if (!IsTapscript(script_ctx) && node_ops && *node_ops < MAX_OPS_PER_SCRIPT && node->ScriptSize() < MAX_STANDARD_P2WSH_SCRIPT_SIZE) { int add = std::min<int>( MAX_OPS_PER_SCRIPT - *node_ops, MAX_STANDARD_P2WSH_SCRIPT_SIZE - node->ScriptSize()); for (int i = 0; i < add; ++i) script.push_back(OP_NOP); } // Under Tapscript, optionally pad the stack up to the limit minus the calculated maximum execution stack // size to assert a Miniscript would never add more elements to the stack during execution than anticipated. const auto node_exec_ss{node->GetExecStackSize()}; if (miniscript::IsTapscript(script_ctx) && node_exec_ss && *node_exec_ss < MAX_STACK_SIZE) { unsigned add{(unsigned)MAX_STACK_SIZE - *node_exec_ss}; witness_mal.stack.resize(add); witness_nonmal.stack.resize(add); script.reserve(add); for (unsigned i = 0; i < add; ++i) script.push_back(OP_NIP); } } const SatisfierContext satisfier_ctx{script_ctx}; // Get the ScriptPubKey for this script, filling spend data if it's Taproot. TaprootBuilder builder; const CScript script_pubkey{ScriptPubKey(script_ctx, script, builder)}; // Run malleable satisfaction algorithm. std::vector<std::vector<unsigned char>> stack_mal; const bool mal_success = node->Satisfy(satisfier_ctx, stack_mal, false) == miniscript::Availability::YES; // Run non-malleable satisfaction algorithm. std::vector<std::vector<unsigned char>> stack_nonmal; const bool nonmal_success = node->Satisfy(satisfier_ctx, stack_nonmal, true) == miniscript::Availability::YES; if (nonmal_success) { // Non-malleable satisfactions are bounded by the satisfaction size plus: // - For P2WSH spends, the witness script // - For Tapscript spends, both the witness script and the control block const size_t max_stack_size{*node->GetStackSize() + 1 + miniscript::IsTapscript(script_ctx)}; assert(stack_nonmal.size() <= max_stack_size); // If a non-malleable satisfaction exists, the malleable one must also exist, and be identical to it. assert(mal_success); assert(stack_nonmal == stack_mal); // Compute witness size (excluding script push, control block, and witness count encoding). const size_t wit_size = GetSerializeSize(stack_nonmal) - GetSizeOfCompactSize(stack_nonmal.size()); assert(wit_size <= *node->GetWitnessSize()); // Test non-malleable satisfaction. witness_nonmal.stack.insert(witness_nonmal.stack.end(), std::make_move_iterator(stack_nonmal.begin()), std::make_move_iterator(stack_nonmal.end())); SatisfactionToWitness(script_ctx, witness_nonmal, script, builder); ScriptError serror; bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_nonmal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror); // Non-malleable satisfactions are guaranteed to be valid if ValidSatisfactions(). if (node->ValidSatisfactions()) assert(res); // More detailed: non-malleable satisfactions must be valid, or could fail with ops count error (if CheckOpsLimit failed), // or with a stack size error (if CheckStackSize check failed). assert(res || (!node->CheckOpsLimit() && serror == ScriptError::SCRIPT_ERR_OP_COUNT) || (!node->CheckStackSize() && serror == ScriptError::SCRIPT_ERR_STACK_SIZE)); } if (mal_success && (!nonmal_success || witness_mal.stack != witness_nonmal.stack)) { // Test malleable satisfaction only if it's different from the non-malleable one. witness_mal.stack.insert(witness_mal.stack.end(), std::make_move_iterator(stack_mal.begin()), std::make_move_iterator(stack_mal.end())); SatisfactionToWitness(script_ctx, witness_mal, script, builder); ScriptError serror; bool res = VerifyScript(DUMMY_SCRIPTSIG, script_pubkey, &witness_mal, STANDARD_SCRIPT_VERIFY_FLAGS, CHECKER_CTX, &serror); // Malleable satisfactions are not guaranteed to be valid under any conditions, but they can only // fail due to stack or ops limits. assert(res || serror == ScriptError::SCRIPT_ERR_OP_COUNT || serror == ScriptError::SCRIPT_ERR_STACK_SIZE); } if (node->IsSane()) { // For sane nodes, the two algorithms behave identically. assert(mal_success == nonmal_success); } // Verify that if a node is policy-satisfiable, the malleable satisfaction // algorithm succeeds. Given that under IsSane() both satisfactions // are identical, this implies that for such nodes, the non-malleable // satisfaction will also match the expected policy. const auto is_key_satisfiable = [script_ctx](const CPubKey& pubkey) -> bool { auto sig_ptr{TEST_DATA.GetSig(script_ctx, pubkey)}; return sig_ptr != nullptr && sig_ptr->second; }; bool satisfiable = node->IsSatisfiable([&](const Node& node) -> bool { switch (node.fragment) { case Fragment::PK_K: case Fragment::PK_H: return is_key_satisfiable(node.keys[0]); case Fragment::MULTI: case Fragment::MULTI_A: { size_t sats = std::count_if(node.keys.begin(), node.keys.end(), [&](const auto& key) { return size_t(is_key_satisfiable(key)); }); return sats >= node.k; } case Fragment::OLDER: case Fragment::AFTER: return node.k & 1; case Fragment::SHA256: return TEST_DATA.sha256_preimages.count(node.data); case Fragment::HASH256: return TEST_DATA.hash256_preimages.count(node.data); case Fragment::RIPEMD160: return TEST_DATA.ripemd160_preimages.count(node.data); case Fragment::HASH160: return TEST_DATA.hash160_preimages.count(node.data); default: assert(false); } return false; }); assert(mal_success == satisfiable); } } // namespace void FuzzInit() { ECC_Start(); TEST_DATA.Init(); } void FuzzInitSmart() { FuzzInit(); SMARTINFO.Init(); } /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeStable. */ FUZZ_TARGET(miniscript_stable, .init = FuzzInit) { // Run it under both P2WSH and Tapscript contexts. for (const auto script_ctx: {MsCtx::P2WSH, MsCtx::TAPSCRIPT}) { FuzzedDataProvider provider(buffer.data(), buffer.size()); TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) { return ConsumeNodeStable(script_ctx, provider, needed_type); }, ""_mst), provider); } } /** Fuzz target that runs TestNode on nodes generated using ConsumeNodeSmart. */ FUZZ_TARGET(miniscript_smart, .init = FuzzInitSmart) { /** The set of types we aim to construct nodes for. Together they cover all. */ static constexpr std::array<Type, 4> BASE_TYPES{"B"_mst, "V"_mst, "K"_mst, "W"_mst}; FuzzedDataProvider provider(buffer.data(), buffer.size()); const auto script_ctx{(MsCtx)provider.ConsumeBool()}; TestNode(script_ctx, GenNode(script_ctx, [&](Type needed_type) { return ConsumeNodeSmart(script_ctx, provider, needed_type); }, PickValue(provider, BASE_TYPES), true), provider); } /* Fuzz tests that test parsing from a string, and roundtripping via string. */ FUZZ_TARGET(miniscript_string, .init = FuzzInit) { if (buffer.empty()) return; FuzzedDataProvider provider(buffer.data(), buffer.size()); auto str = provider.ConsumeBytesAsString(provider.remaining_bytes() - 1); const ParserContext parser_ctx{(MsCtx)provider.ConsumeBool()}; auto parsed = miniscript::FromString(str, parser_ctx); if (!parsed) return; const auto str2 = parsed->ToString(parser_ctx); assert(str2); auto parsed2 = miniscript::FromString(*str2, parser_ctx); assert(parsed2); assert(*parsed == *parsed2); } /* Fuzz tests that test parsing from a script, and roundtripping via script. */ FUZZ_TARGET(miniscript_script) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider); if (!script) return; const ScriptParserContext script_parser_ctx{(MsCtx)fuzzed_data_provider.ConsumeBool()}; const auto ms = miniscript::FromScript(*script, script_parser_ctx); if (!ms) return; assert(ms->ToScript(script_parser_ctx) == *script); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/pow.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <chainparams.h> #include <pow.h> #include <primitives/block.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/chaintype.h> #include <util/check.h> #include <util/overflow.h> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_pow() { SelectParams(ChainType::MAIN); } FUZZ_TARGET(pow, .init = initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params = Params().GetConsensus(); std::vector<std::unique_ptr<CBlockIndex>> blocks; const uint32_t fixed_time = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const uint32_t fixed_bits = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 10000) { const std::optional<CBlockHeader> block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider); if (!block_header) { continue; } CBlockIndex& current_block{ *blocks.emplace_back(std::make_unique<CBlockIndex>(*block_header))}; { CBlockIndex* previous_block = blocks.empty() ? nullptr : PickValue(fuzzed_data_provider, blocks).get(); const int current_height = (previous_block != nullptr && previous_block->nHeight != std::numeric_limits<int>::max()) ? previous_block->nHeight + 1 : 0; if (fuzzed_data_provider.ConsumeBool()) { current_block.pprev = previous_block; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nHeight = current_height; } if (fuzzed_data_provider.ConsumeBool()) { const uint32_t seconds = current_height * consensus_params.nPowTargetSpacing; if (!AdditionOverflow(fixed_time, seconds)) { current_block.nTime = fixed_time + seconds; } } if (fuzzed_data_provider.ConsumeBool()) { current_block.nBits = fixed_bits; } if (fuzzed_data_provider.ConsumeBool()) { current_block.nChainWork = previous_block != nullptr ? previous_block->nChainWork + GetBlockProof(*previous_block) : arith_uint256{0}; } else { current_block.nChainWork = ConsumeArithUInt256(fuzzed_data_provider); } } { (void)GetBlockProof(current_block); (void)CalculateNextWorkRequired(&current_block, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, std::numeric_limits<int64_t>::max()), consensus_params); if (current_block.nHeight != std::numeric_limits<int>::max() && current_block.nHeight - (consensus_params.DifficultyAdjustmentInterval() - 1) >= 0) { (void)GetNextWorkRequired(&current_block, &(*block_header), consensus_params); } } { const auto& to = PickValue(fuzzed_data_provider, blocks); const auto& from = PickValue(fuzzed_data_provider, blocks); const auto& tip = PickValue(fuzzed_data_provider, blocks); try { (void)GetBlockProofEquivalentTime(*to, *from, *tip, consensus_params); } catch (const uint_error&) { } } { const std::optional<uint256> hash = ConsumeDeserializable<uint256>(fuzzed_data_provider); if (hash) { (void)CheckProofOfWork(*hash, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), consensus_params); } } } } FUZZ_TARGET(pow_transition, .init = initialize_pow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const Consensus::Params& consensus_params{Params().GetConsensus()}; std::vector<std::unique_ptr<CBlockIndex>> blocks; const uint32_t old_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const uint32_t new_time{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const int32_t version{fuzzed_data_provider.ConsumeIntegral<int32_t>()}; uint32_t nbits{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const arith_uint256 pow_limit = UintToArith256(consensus_params.powLimit); arith_uint256 old_target; old_target.SetCompact(nbits); if (old_target > pow_limit) { nbits = pow_limit.GetCompact(); } // Create one difficulty adjustment period worth of headers for (int height = 0; height < consensus_params.DifficultyAdjustmentInterval(); ++height) { CBlockHeader header; header.nVersion = version; header.nTime = old_time; header.nBits = nbits; if (height == consensus_params.DifficultyAdjustmentInterval() - 1) { header.nTime = new_time; } auto current_block{std::make_unique<CBlockIndex>(header)}; current_block->pprev = blocks.empty() ? nullptr : blocks.back().get(); current_block->nHeight = height; blocks.emplace_back(std::move(current_block)); } auto last_block{blocks.back().get()}; unsigned int new_nbits{GetNextWorkRequired(last_block, nullptr, consensus_params)}; Assert(PermittedDifficultyTransition(consensus_params, last_block->nHeight + 1, last_block->nBits, new_nbits)); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script.cpp
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <compressor.h> #include <core_io.h> #include <core_memusage.h> #include <key_io.h> #include <policy/policy.h> #include <pubkey.h> #include <rpc/util.h> #include <script/descriptor.h> #include <script/interpreter.h> #include <script/script.h> #include <script/script_error.h> #include <script/sign.h> #include <script/signingprovider.h> #include <script/solver.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <univalue.h> #include <util/chaintype.h> #include <algorithm> #include <cassert> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_script() { SelectParams(ChainType::REGTEST); } FUZZ_TARGET(script, .init = initialize_script) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CScript script{ConsumeScript(fuzzed_data_provider)}; CompressedScript compressed; if (CompressScript(script, compressed)) { const unsigned int size = compressed[0]; compressed.erase(compressed.begin()); assert(size <= 5); CScript decompressed_script; const bool ok = DecompressScript(decompressed_script, size, compressed); assert(ok); assert(script == decompressed_script); } TxoutType which_type; bool is_standard_ret = IsStandard(script, std::nullopt, which_type); if (!is_standard_ret) { assert(which_type == TxoutType::NONSTANDARD || which_type == TxoutType::NULL_DATA || which_type == TxoutType::MULTISIG); } if (which_type == TxoutType::NONSTANDARD) { assert(!is_standard_ret); } if (which_type == TxoutType::NULL_DATA) { assert(script.IsUnspendable()); } if (script.IsUnspendable()) { assert(which_type == TxoutType::NULL_DATA || which_type == TxoutType::NONSTANDARD); } CTxDestination address; bool extract_destination_ret = ExtractDestination(script, address); if (!extract_destination_ret) { assert(which_type == TxoutType::PUBKEY || which_type == TxoutType::NONSTANDARD || which_type == TxoutType::NULL_DATA || which_type == TxoutType::MULTISIG); } if (which_type == TxoutType::NONSTANDARD || which_type == TxoutType::NULL_DATA || which_type == TxoutType::MULTISIG) { assert(!extract_destination_ret); } const FlatSigningProvider signing_provider; (void)InferDescriptor(script, signing_provider); (void)IsSegWitOutput(signing_provider, script); (void)RecursiveDynamicUsage(script); std::vector<std::vector<unsigned char>> solutions; (void)Solver(script, solutions); (void)script.HasValidOps(); (void)script.IsPayToScriptHash(); (void)script.IsPayToWitnessScriptHash(); (void)script.IsPushOnly(); (void)script.GetSigOpCount(/* fAccurate= */ false); { const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider); CompressedScript compressed_script; compressed_script.assign(bytes.begin(), bytes.end()); // DecompressScript(..., ..., bytes) is not guaranteed to be defined if the bytes vector is too short if (compressed_script.size() >= 32) { CScript decompressed_script; DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), compressed_script); } } const std::optional<CScript> other_script = ConsumeDeserializable<CScript>(fuzzed_data_provider); if (other_script) { { CScript script_mut{script}; (void)FindAndDelete(script_mut, *other_script); } const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider); const uint32_t u32{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; const uint32_t flags{u32 | SCRIPT_VERIFY_P2SH}; { CScriptWitness wit; for (const auto& s : random_string_vector) { wit.stack.emplace_back(s.begin(), s.end()); } (void)CountWitnessSigOps(script, *other_script, &wit, flags); wit.SetNull(); } } (void)GetOpName(ConsumeOpcodeType(fuzzed_data_provider)); (void)ScriptErrorString(static_cast<ScriptError>(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, SCRIPT_ERR_ERROR_COUNT))); { const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider); CScript append_script{bytes.begin(), bytes.end()}; append_script << fuzzed_data_provider.ConsumeIntegral<int64_t>(); append_script << ConsumeOpcodeType(fuzzed_data_provider); append_script << CScriptNum{fuzzed_data_provider.ConsumeIntegral<int64_t>()}; append_script << ConsumeRandomLengthByteVector(fuzzed_data_provider); } { const CTxDestination tx_destination_1{ fuzzed_data_provider.ConsumeBool() ? DecodeDestination(fuzzed_data_provider.ConsumeRandomLengthString()) : ConsumeTxDestination(fuzzed_data_provider)}; const CTxDestination tx_destination_2{ConsumeTxDestination(fuzzed_data_provider)}; const std::string encoded_dest{EncodeDestination(tx_destination_1)}; const UniValue json_dest{DescribeAddress(tx_destination_1)}; (void)GetKeyForDestination(/*store=*/{}, tx_destination_1); const CScript dest{GetScriptForDestination(tx_destination_1)}; const bool valid{IsValidDestination(tx_destination_1)}; if (!std::get_if<PubKeyDestination>(&tx_destination_1)) { // Only try to round trip non-pubkey destinations since PubKeyDestination has no encoding Assert(dest.empty() != valid); Assert(tx_destination_1 == DecodeDestination(encoded_dest)); Assert(valid == IsValidDestinationString(encoded_dest)); } (void)(tx_destination_1 < tx_destination_2); if (tx_destination_1 == tx_destination_2) { Assert(encoded_dest == EncodeDestination(tx_destination_2)); Assert(json_dest.write() == DescribeAddress(tx_destination_2).write()); Assert(dest == GetScriptForDestination(tx_destination_2)); } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/secp256k1_ec_seckey_import_export_der.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key.h> #include <secp256k1.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <vector> int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char* out32, const unsigned char* seckey, size_t seckeylen); int ec_seckey_export_der(const secp256k1_context* ctx, unsigned char* seckey, size_t* seckeylen, const unsigned char* key32, bool compressed); FUZZ_TARGET(secp256k1_ec_seckey_import_export_der) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; secp256k1_context* secp256k1_context_sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); { std::vector<uint8_t> out32(32); (void)ec_seckey_import_der(secp256k1_context_sign, out32.data(), ConsumeFixedLengthByteVector(fuzzed_data_provider, CKey::SIZE).data(), CKey::SIZE); } { std::vector<uint8_t> seckey(CKey::SIZE); const std::vector<uint8_t> key32 = ConsumeFixedLengthByteVector(fuzzed_data_provider, 32); size_t seckeylen = CKey::SIZE; const bool compressed = fuzzed_data_provider.ConsumeBool(); const bool exported = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, key32.data(), compressed); if (exported) { std::vector<uint8_t> out32(32); const bool imported = ec_seckey_import_der(secp256k1_context_sign, out32.data(), seckey.data(), seckey.size()) == 1; assert(imported && key32 == out32); } } secp256k1_context_destroy(secp256k1_context_sign); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_sign.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <key.h> #include <psbt.h> #include <pubkey.h> #include <script/keyorigin.h> #include <script/sign.h> #include <script/signingprovider.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/chaintype.h> #include <util/translation.h> #include <cassert> #include <cstdint> #include <iostream> #include <map> #include <optional> #include <string> #include <vector> void initialize_script_sign() { ECC_Start(); SelectParams(ChainType::REGTEST); } FUZZ_TARGET(script_sign, .init = initialize_script_sign) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::vector<uint8_t> key = ConsumeRandomLengthByteVector(fuzzed_data_provider, 128); { DataStream random_data_stream{ConsumeDataStream(fuzzed_data_provider)}; std::map<CPubKey, KeyOriginInfo> hd_keypaths; try { DeserializeHDKeypaths(random_data_stream, key, hd_keypaths); } catch (const std::ios_base::failure&) { } DataStream serialized{}; SerializeHDKeypaths(serialized, hd_keypaths, CompactSizeWriter(fuzzed_data_provider.ConsumeIntegral<uint8_t>())); } { std::map<CPubKey, KeyOriginInfo> hd_keypaths; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const std::optional<CPubKey> pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider); if (!pub_key) { break; } const std::optional<KeyOriginInfo> key_origin_info = ConsumeDeserializable<KeyOriginInfo>(fuzzed_data_provider); if (!key_origin_info) { break; } hd_keypaths[*pub_key] = *key_origin_info; } DataStream serialized{}; try { SerializeHDKeypaths(serialized, hd_keypaths, CompactSizeWriter(fuzzed_data_provider.ConsumeIntegral<uint8_t>())); } catch (const std::ios_base::failure&) { } std::map<CPubKey, KeyOriginInfo> deserialized_hd_keypaths; try { DeserializeHDKeypaths(serialized, key, hd_keypaths); } catch (const std::ios_base::failure&) { } assert(hd_keypaths.size() >= deserialized_hd_keypaths.size()); } { SignatureData signature_data_1{ConsumeScript(fuzzed_data_provider)}; SignatureData signature_data_2{ConsumeScript(fuzzed_data_provider)}; signature_data_1.MergeSignatureData(signature_data_2); } FillableSigningProvider provider; CKey k = ConsumePrivateKey(fuzzed_data_provider); if (k.IsValid()) { provider.AddKey(k); } { const std::optional<CMutableTransaction> mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); const std::optional<CTxOut> tx_out = ConsumeDeserializable<CTxOut>(fuzzed_data_provider); const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); if (mutable_transaction && tx_out && mutable_transaction->vin.size() > n_in) { SignatureData signature_data_1 = DataFromTransaction(*mutable_transaction, n_in, *tx_out); CTxIn input; UpdateInput(input, signature_data_1); const CScript script = ConsumeScript(fuzzed_data_provider); SignatureData signature_data_2{script}; signature_data_1.MergeSignatureData(signature_data_2); } if (mutable_transaction) { CTransaction tx_from{*mutable_transaction}; CMutableTransaction tx_to; const std::optional<CMutableTransaction> opt_tx_to = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (opt_tx_to) { tx_to = *opt_tx_to; } CMutableTransaction script_tx_to = tx_to; CMutableTransaction sign_transaction_tx_to = tx_to; if (n_in < tx_to.vin.size() && tx_to.vin[n_in].prevout.n < tx_from.vout.size()) { SignatureData empty; (void)SignSignature(provider, tx_from, tx_to, n_in, fuzzed_data_provider.ConsumeIntegral<int>(), empty); } if (n_in < script_tx_to.vin.size()) { SignatureData empty; (void)SignSignature(provider, ConsumeScript(fuzzed_data_provider), script_tx_to, n_in, ConsumeMoney(fuzzed_data_provider), fuzzed_data_provider.ConsumeIntegral<int>(), empty); MutableTransactionSignatureCreator signature_creator{tx_to, n_in, ConsumeMoney(fuzzed_data_provider), fuzzed_data_provider.ConsumeIntegral<int>()}; std::vector<unsigned char> vch_sig; CKeyID address; if (fuzzed_data_provider.ConsumeBool()) { if (k.IsValid()) { address = k.GetPubKey().GetID(); } } else { address = CKeyID{ConsumeUInt160(fuzzed_data_provider)}; } (void)signature_creator.CreateSig(provider, vch_sig, address, ConsumeScript(fuzzed_data_provider), fuzzed_data_provider.PickValueInArray({SigVersion::BASE, SigVersion::WITNESS_V0})); } std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)}; std::map<int, bilingual_str> input_errors; (void)SignTransaction(sign_transaction_tx_to, &provider, coins, fuzzed_data_provider.ConsumeIntegral<int>(), input_errors); } } { SignatureData signature_data_1; (void)ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, ConsumeScript(fuzzed_data_provider), signature_data_1); SignatureData signature_data_2; (void)ProduceSignature(provider, DUMMY_MAXIMUM_SIGNATURE_CREATOR, ConsumeScript(fuzzed_data_provider), signature_data_2); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_bitcoin_consensus.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/bitcoinconsensus.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(script_bitcoin_consensus) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::vector<uint8_t> random_bytes_1 = ConsumeRandomLengthByteVector(fuzzed_data_provider); const std::vector<uint8_t> random_bytes_2 = ConsumeRandomLengthByteVector(fuzzed_data_provider); const CAmount money = ConsumeMoney(fuzzed_data_provider); bitcoinconsensus_error err; bitcoinconsensus_error* err_p = fuzzed_data_provider.ConsumeBool() ? &err : nullptr; const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const unsigned int flags = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); assert(bitcoinconsensus_version() == BITCOINCONSENSUS_API_VER); if ((flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) { return; } (void)bitcoinconsensus_verify_script(random_bytes_1.data(), random_bytes_1.size(), random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p); (void)bitcoinconsensus_verify_script_with_amount(random_bytes_1.data(), random_bytes_1.size(), money, random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p); std::vector<UTXO> spent_outputs; std::vector<std::vector<unsigned char>> spent_spks; if (n_in <= 24386) { spent_outputs.reserve(n_in); spent_spks.reserve(n_in); for (size_t i = 0; i < n_in; ++i) { spent_spks.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider)); const CAmount value{ConsumeMoney(fuzzed_data_provider)}; const auto spk_size{static_cast<unsigned>(spent_spks.back().size())}; spent_outputs.push_back({.scriptPubKey = spent_spks.back().data(), .scriptPubKeySize = spk_size, .value = value}); } } const auto spent_outs_size{static_cast<unsigned>(spent_outputs.size())}; (void)bitcoinconsensus_verify_script_with_spent_outputs( random_bytes_1.data(), random_bytes_1.size(), money, random_bytes_2.data(), random_bytes_2.size(), spent_outputs.data(), spent_outs_size, n_in, flags, err_p); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/random.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <algorithm> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(random) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)}; (void)fast_random_context.rand64(); (void)fast_random_context.randbits(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 64)); (void)fast_random_context.randrange(fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(FastRandomContext::min() + 1, FastRandomContext::max())); (void)fast_random_context.randbytes(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 1024)); (void)fast_random_context.rand32(); (void)fast_random_context.rand256(); (void)fast_random_context.randbool(); (void)fast_random_context(); std::vector<int64_t> integrals = ConsumeRandomLengthIntegralVector<int64_t>(fuzzed_data_provider); Shuffle(integrals.begin(), integrals.end(), fast_random_context); std::shuffle(integrals.begin(), integrals.end(), fast_random_context); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/coins_view.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <coins.h> #include <consensus/amount.h> #include <consensus/tx_check.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <util/hasher.h> #include <cassert> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <stdexcept> #include <string> #include <utility> #include <vector> namespace { const TestingSetup* g_setup; const Coin EMPTY_COIN{}; bool operator==(const Coin& a, const Coin& b) { if (a.IsSpent() && b.IsSpent()) return true; return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out; } } // namespace void initialize_coins_view() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } FUZZ_TARGET(coins_view, .init = initialize_coins_view) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; bool good_data{true}; CCoinsView backend_coins_view; CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true}; COutPoint random_out_point; Coin random_coin; CMutableTransaction random_mutable_transaction; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000) { CallOneOf( fuzzed_data_provider, [&] { if (random_coin.IsSpent()) { return; } Coin coin = random_coin; bool expected_code_path = false; const bool possible_overwrite = fuzzed_data_provider.ConsumeBool(); try { coins_view_cache.AddCoin(random_out_point, std::move(coin), possible_overwrite); expected_code_path = true; } catch (const std::logic_error& e) { if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) { assert(!possible_overwrite); expected_code_path = true; } } assert(expected_code_path); }, [&] { (void)coins_view_cache.Flush(); }, [&] { (void)coins_view_cache.Sync(); }, [&] { coins_view_cache.SetBestBlock(ConsumeUInt256(fuzzed_data_provider)); }, [&] { Coin move_to; (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr); }, [&] { coins_view_cache.Uncache(random_out_point); }, [&] { if (fuzzed_data_provider.ConsumeBool()) { backend_coins_view = CCoinsView{}; } coins_view_cache.SetBackend(backend_coins_view); }, [&] { const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider); if (!opt_out_point) { good_data = false; return; } random_out_point = *opt_out_point; }, [&] { const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider); if (!opt_coin) { good_data = false; return; } random_coin = *opt_coin; }, [&] { const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!opt_mutable_transaction) { good_data = false; return; } random_mutable_transaction = *opt_mutable_transaction; }, [&] { CCoinsMapMemoryResource resource; CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource}; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000) { CCoinsCacheEntry coins_cache_entry; coins_cache_entry.flags = fuzzed_data_provider.ConsumeIntegral<unsigned char>(); if (fuzzed_data_provider.ConsumeBool()) { coins_cache_entry.coin = random_coin; } else { const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider); if (!opt_coin) { good_data = false; return; } coins_cache_entry.coin = *opt_coin; } coins_map.emplace(random_out_point, std::move(coins_cache_entry)); } bool expected_code_path = false; try { coins_view_cache.BatchWrite(coins_map, fuzzed_data_provider.ConsumeBool() ? ConsumeUInt256(fuzzed_data_provider) : coins_view_cache.GetBestBlock()); expected_code_path = true; } catch (const std::logic_error& e) { if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) { expected_code_path = true; } } assert(expected_code_path); }); } { const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point); const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN); const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point); const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point); Coin coin_using_get_coin; const bool exists_using_get_coin = coins_view_cache.GetCoin(random_out_point, coin_using_get_coin); if (exists_using_get_coin) { assert(coin_using_get_coin == coin_using_access_coin); } assert((exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin && exists_using_get_coin) || (!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin && !exists_using_get_coin)); // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent. const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point); if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) { assert(exists_using_have_coin); } Coin coin_using_backend_get_coin; if (backend_coins_view.GetCoin(random_out_point, coin_using_backend_get_coin)) { assert(exists_using_have_coin_in_backend); // Note we can't assert that `coin_using_get_coin == coin_using_backend_get_coin` because the coin in // the cache may have been modified but not yet flushed. } else { assert(!exists_using_have_coin_in_backend); } } { bool expected_code_path = false; try { (void)coins_view_cache.Cursor(); } catch (const std::logic_error&) { expected_code_path = true; } assert(expected_code_path); (void)coins_view_cache.DynamicMemoryUsage(); (void)coins_view_cache.EstimateSize(); (void)coins_view_cache.GetBestBlock(); (void)coins_view_cache.GetCacheSize(); (void)coins_view_cache.GetHeadBlocks(); (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction}); } { std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor(); assert(!coins_view_cursor); (void)backend_coins_view.EstimateSize(); (void)backend_coins_view.GetBestBlock(); (void)backend_coins_view.GetHeadBlocks(); } if (fuzzed_data_provider.ConsumeBool()) { CallOneOf( fuzzed_data_provider, [&] { const CTransaction transaction{random_mutable_transaction}; bool is_spent = false; for (const CTxOut& tx_out : transaction.vout) { if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) { is_spent = true; } } if (is_spent) { // Avoid: // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed. return; } bool expected_code_path = false; const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)}; const bool possible_overwrite = fuzzed_data_provider.ConsumeBool(); try { AddCoins(coins_view_cache, transaction, height, possible_overwrite); expected_code_path = true; } catch (const std::logic_error& e) { if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) { assert(!possible_overwrite); expected_code_path = true; } } assert(expected_code_path); }, [&] { (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache); }, [&] { TxValidationState state; CAmount tx_fee_out; const CTransaction transaction{random_mutable_transaction}; if (ContainsSpentInput(transaction, coins_view_cache)) { // Avoid: // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed. return; } TxValidationState dummy; if (!CheckTransaction(transaction, dummy)) { // It is not allowed to call CheckTxInputs if CheckTransaction failed return; } if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) { assert(MoneyRange(tx_fee_out)); } }, [&] { const CTransaction transaction{random_mutable_transaction}; if (ContainsSpentInput(transaction, coins_view_cache)) { // Avoid: // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed. return; } (void)GetP2SHSigOpCount(transaction, coins_view_cache); }, [&] { const CTransaction transaction{random_mutable_transaction}; if (ContainsSpentInput(transaction, coins_view_cache)) { // Avoid: // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed. return; } const auto flags{fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) { // Avoid: // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness *, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed. return; } (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags); }, [&] { (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache); }); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/poolresource.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <span.h> #include <support/allocators/pool.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/poolresourcetester.h> #include <test/util/xoroshiro128plusplus.h> #include <cstdint> #include <tuple> #include <vector> namespace { template <std::size_t MAX_BLOCK_SIZE_BYTES, std::size_t ALIGN_BYTES> class PoolResourceFuzzer { FuzzedDataProvider& m_provider; PoolResource<MAX_BLOCK_SIZE_BYTES, ALIGN_BYTES> m_test_resource; uint64_t m_sequence{0}; size_t m_total_allocated{}; struct Entry { Span<std::byte> span; size_t alignment; uint64_t seed; Entry(Span<std::byte> s, size_t a, uint64_t se) : span(s), alignment(a), seed(se) {} }; std::vector<Entry> m_entries; public: PoolResourceFuzzer(FuzzedDataProvider& provider) : m_provider{provider}, m_test_resource{provider.ConsumeIntegralInRange<size_t>(MAX_BLOCK_SIZE_BYTES, 262144)} { } void Allocate(size_t size, size_t alignment) { assert(size > 0); // Must allocate at least 1 byte. assert(alignment > 0); // Alignment must be at least 1. assert((alignment & (alignment - 1)) == 0); // Alignment must be power of 2. assert((size & (alignment - 1)) == 0); // Size must be a multiple of alignment. auto span = Span(static_cast<std::byte*>(m_test_resource.Allocate(size, alignment)), size); m_total_allocated += size; auto ptr_val = reinterpret_cast<std::uintptr_t>(span.data()); assert((ptr_val & (alignment - 1)) == 0); uint64_t seed = m_sequence++; RandomContentFill(m_entries.emplace_back(span, alignment, seed)); } void Allocate() { if (m_total_allocated > 0x1000000) return; size_t alignment_bits = m_provider.ConsumeIntegralInRange<size_t>(0, 7); size_t alignment = 1 << alignment_bits; size_t size_bits = m_provider.ConsumeIntegralInRange<size_t>(0, 16 - alignment_bits); size_t size = m_provider.ConsumeIntegralInRange<size_t>(1U << size_bits, (1U << (size_bits + 1)) - 1U) << alignment_bits; Allocate(size, alignment); } void RandomContentFill(Entry& entry) { XoRoShiRo128PlusPlus rng(entry.seed); auto ptr = entry.span.data(); auto size = entry.span.size(); while (size >= 8) { auto r = rng(); std::memcpy(ptr, &r, 8); size -= 8; ptr += 8; } if (size > 0) { auto r = rng(); std::memcpy(ptr, &r, size); } } void RandomContentCheck(const Entry& entry) { XoRoShiRo128PlusPlus rng(entry.seed); auto ptr = entry.span.data(); auto size = entry.span.size(); std::byte buf[8]; while (size >= 8) { auto r = rng(); std::memcpy(buf, &r, 8); assert(std::memcmp(buf, ptr, 8) == 0); size -= 8; ptr += 8; } if (size > 0) { auto r = rng(); std::memcpy(buf, &r, size); assert(std::memcmp(buf, ptr, size) == 0); } } void Deallocate(const Entry& entry) { auto ptr_val = reinterpret_cast<std::uintptr_t>(entry.span.data()); assert((ptr_val & (entry.alignment - 1)) == 0); RandomContentCheck(entry); m_total_allocated -= entry.span.size(); m_test_resource.Deallocate(entry.span.data(), entry.span.size(), entry.alignment); } void Deallocate() { if (m_entries.empty()) { return; } size_t idx = m_provider.ConsumeIntegralInRange<size_t>(0, m_entries.size() - 1); Deallocate(m_entries[idx]); if (idx != m_entries.size() - 1) { m_entries[idx] = std::move(m_entries.back()); } m_entries.pop_back(); } void Clear() { while (!m_entries.empty()) { Deallocate(); } PoolResourceTester::CheckAllDataAccountedFor(m_test_resource); } void Fuzz() { LIMITED_WHILE(m_provider.ConsumeBool(), 10000) { CallOneOf( m_provider, [&] { Allocate(); }, [&] { Deallocate(); }); } Clear(); } }; } // namespace FUZZ_TARGET(pool_resource) { FuzzedDataProvider provider(buffer.data(), buffer.size()); CallOneOf( provider, [&] { PoolResourceFuzzer<128, 1>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<128, 2>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<128, 4>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<128, 8>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<8, 8>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<16, 16>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<256, alignof(max_align_t)>{provider}.Fuzz(); }, [&] { PoolResourceFuzzer<256, 64>{provider}.Fuzz(); }); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/FuzzedDataProvider.h
//===- FuzzedDataProvider.h - Utility header for fuzz targets ---*- C++ -* ===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // A single header library providing an utility class to break up an array of // bytes. Whenever run on the same input, provides the same output, as long as // its methods are called in the same order, with the same arguments. //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_ #define LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_ #include <algorithm> #include <array> #include <climits> #include <cstddef> #include <cstdint> #include <cstring> #include <initializer_list> #include <limits> #include <string> #include <type_traits> #include <utility> #include <vector> // In addition to the comments below, the API is also briefly documented at // https://github.com/google/fuzzing/blob/master/docs/split-inputs.md#fuzzed-data-provider class FuzzedDataProvider { public: // |data| is an array of length |size| that the FuzzedDataProvider wraps to // provide more granular access. |data| must outlive the FuzzedDataProvider. FuzzedDataProvider(const uint8_t *data, size_t size) : data_ptr_(data), remaining_bytes_(size) {} ~FuzzedDataProvider() = default; // See the implementation below (after the class definition) for more verbose // comments for each of the methods. // Methods returning std::vector of bytes. These are the most popular choice // when splitting fuzzing input into pieces, as every piece is put into a // separate buffer (i.e. ASan would catch any under-/overflow) and the memory // will be released automatically. template <typename T> std::vector<T> ConsumeBytes(size_t num_bytes); template <typename T> std::vector<T> ConsumeBytesWithTerminator(size_t num_bytes, T terminator = 0); template <typename T> std::vector<T> ConsumeRemainingBytes(); // Methods returning strings. Use only when you need a std::string or a null // terminated C-string. Otherwise, prefer the methods returning std::vector. std::string ConsumeBytesAsString(size_t num_bytes); std::string ConsumeRandomLengthString(size_t max_length); std::string ConsumeRandomLengthString(); std::string ConsumeRemainingBytesAsString(); // Methods returning integer values. template <typename T> T ConsumeIntegral(); template <typename T> T ConsumeIntegralInRange(T min, T max); // Methods returning floating point values. template <typename T> T ConsumeFloatingPoint(); template <typename T> T ConsumeFloatingPointInRange(T min, T max); // 0 <= return value <= 1. template <typename T> T ConsumeProbability(); bool ConsumeBool(); // Returns a value chosen from the given enum. template <typename T> T ConsumeEnum(); // Returns a value from the given array. template <typename T, size_t size> T PickValueInArray(const T (&array)[size]); template <typename T, size_t size> T PickValueInArray(const std::array<T, size> &array); template <typename T> T PickValueInArray(std::initializer_list<const T> list); // Writes data to the given destination and returns number of bytes written. size_t ConsumeData(void *destination, size_t num_bytes); // Reports the remaining bytes available for fuzzed input. size_t remaining_bytes() { return remaining_bytes_; } private: FuzzedDataProvider(const FuzzedDataProvider &) = delete; FuzzedDataProvider &operator=(const FuzzedDataProvider &) = delete; void CopyAndAdvance(void *destination, size_t num_bytes); void Advance(size_t num_bytes); template <typename T> std::vector<T> ConsumeBytes(size_t size, size_t num_bytes); template <typename TS, typename TU> TS ConvertUnsignedToSigned(TU value); const uint8_t *data_ptr_; size_t remaining_bytes_; }; // Returns a std::vector containing |num_bytes| of input data. If fewer than // |num_bytes| of data remain, returns a shorter std::vector containing all // of the data that's left. Can be used with any byte sized type, such as // char, unsigned char, uint8_t, etc. template <typename T> std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t num_bytes) { num_bytes = std::min(num_bytes, remaining_bytes_); return ConsumeBytes<T>(num_bytes, num_bytes); } // Similar to |ConsumeBytes|, but also appends the terminator value at the end // of the resulting vector. Useful, when a mutable null-terminated C-string is // needed, for example. But that is a rare case. Better avoid it, if possible, // and prefer using |ConsumeBytes| or |ConsumeBytesAsString| methods. template <typename T> std::vector<T> FuzzedDataProvider::ConsumeBytesWithTerminator(size_t num_bytes, T terminator) { num_bytes = std::min(num_bytes, remaining_bytes_); std::vector<T> result = ConsumeBytes<T>(num_bytes + 1, num_bytes); result.back() = terminator; return result; } // Returns a std::vector containing all remaining bytes of the input data. template <typename T> std::vector<T> FuzzedDataProvider::ConsumeRemainingBytes() { return ConsumeBytes<T>(remaining_bytes_); } // Returns a std::string containing |num_bytes| of input data. Using this and // |.c_str()| on the resulting string is the best way to get an immutable // null-terminated C string. If fewer than |num_bytes| of data remain, returns // a shorter std::string containing all of the data that's left. inline std::string FuzzedDataProvider::ConsumeBytesAsString(size_t num_bytes) { static_assert(sizeof(std::string::value_type) == sizeof(uint8_t), "ConsumeBytesAsString cannot convert the data to a string."); num_bytes = std::min(num_bytes, remaining_bytes_); std::string result( reinterpret_cast<const std::string::value_type *>(data_ptr_), num_bytes); Advance(num_bytes); return result; } // Returns a std::string of length from 0 to |max_length|. When it runs out of // input data, returns what remains of the input. Designed to be more stable // with respect to a fuzzer inserting characters than just picking a random // length and then consuming that many bytes with |ConsumeBytes|. inline std::string FuzzedDataProvider::ConsumeRandomLengthString(size_t max_length) { // Reads bytes from the start of |data_ptr_|. Maps "\\" to "\", and maps "\" // followed by anything else to the end of the string. As a result of this // logic, a fuzzer can insert characters into the string, and the string // will be lengthened to include those new characters, resulting in a more // stable fuzzer than picking the length of a string independently from // picking its contents. std::string result; // Reserve the anticipated capacity to prevent several reallocations. result.reserve(std::min(max_length, remaining_bytes_)); for (size_t i = 0; i < max_length && remaining_bytes_ != 0; ++i) { char next = ConvertUnsignedToSigned<char>(data_ptr_[0]); Advance(1); if (next == '\\' && remaining_bytes_ != 0) { next = ConvertUnsignedToSigned<char>(data_ptr_[0]); Advance(1); if (next != '\\') break; } result += next; } result.shrink_to_fit(); return result; } // Returns a std::string of length from 0 to |remaining_bytes_|. inline std::string FuzzedDataProvider::ConsumeRandomLengthString() { return ConsumeRandomLengthString(remaining_bytes_); } // Returns a std::string containing all remaining bytes of the input data. // Prefer using |ConsumeRemainingBytes| unless you actually need a std::string // object. inline std::string FuzzedDataProvider::ConsumeRemainingBytesAsString() { return ConsumeBytesAsString(remaining_bytes_); } // Returns a number in the range [Type's min, Type's max]. The value might // not be uniformly distributed in the given range. If there's no input data // left, always returns |min|. template <typename T> T FuzzedDataProvider::ConsumeIntegral() { return ConsumeIntegralInRange(std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); } // Returns a number in the range [min, max] by consuming bytes from the // input data. The value might not be uniformly distributed in the given // range. If there's no input data left, always returns |min|. |min| must // be less than or equal to |max|. template <typename T> T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) { static_assert(std::is_integral<T>::value, "An integral type is required."); static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type."); if (min > max) abort(); // Use the biggest type possible to hold the range and the result. uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min); uint64_t result = 0; size_t offset = 0; while (offset < sizeof(T) * CHAR_BIT && (range >> offset) > 0 && remaining_bytes_ != 0) { // Pull bytes off the end of the seed data. Experimentally, this seems to // allow the fuzzer to more easily explore the input space. This makes // sense, since it works by modifying inputs that caused new code to run, // and this data is often used to encode length of data read by // |ConsumeBytes|. Separating out read lengths makes it easier modify the // contents of the data that is actually read. --remaining_bytes_; result = (result << CHAR_BIT) | data_ptr_[remaining_bytes_]; offset += CHAR_BIT; } // Avoid division by 0, in case |range + 1| results in overflow. if (range != std::numeric_limits<decltype(range)>::max()) result = result % (range + 1); return static_cast<T>(static_cast<uint64_t>(min) + result); } // Returns a floating point value in the range [Type's lowest, Type's max] by // consuming bytes from the input data. If there's no input data left, always // returns approximately 0. template <typename T> T FuzzedDataProvider::ConsumeFloatingPoint() { return ConsumeFloatingPointInRange<T>(std::numeric_limits<T>::lowest(), std::numeric_limits<T>::max()); } // Returns a floating point value in the given range by consuming bytes from // the input data. If there's no input data left, returns |min|. Note that // |min| must be less than or equal to |max|. template <typename T> T FuzzedDataProvider::ConsumeFloatingPointInRange(T min, T max) { if (min > max) abort(); T range = .0; T result = min; constexpr T zero(.0); if (max > zero && min < zero && max > min + std::numeric_limits<T>::max()) { // The diff |max - min| would overflow the given floating point type. Use // the half of the diff as the range and consume a bool to decide whether // the result is in the first of the second part of the diff. range = (max / 2.0) - (min / 2.0); if (ConsumeBool()) { result += range; } } else { range = max - min; } return result + range * ConsumeProbability<T>(); } // Returns a floating point number in the range [0.0, 1.0]. If there's no // input data left, always returns 0. template <typename T> T FuzzedDataProvider::ConsumeProbability() { static_assert(std::is_floating_point<T>::value, "A floating point type is required."); // Use different integral types for different floating point types in order // to provide better density of the resulting values. using IntegralType = typename std::conditional<(sizeof(T) <= sizeof(uint32_t)), uint32_t, uint64_t>::type; T result = static_cast<T>(ConsumeIntegral<IntegralType>()); result /= static_cast<T>(std::numeric_limits<IntegralType>::max()); return result; } // Reads one byte and returns a bool, or false when no data remains. inline bool FuzzedDataProvider::ConsumeBool() { return 1 & ConsumeIntegral<uint8_t>(); } // Returns an enum value. The enum must start at 0 and be contiguous. It must // also contain |kMaxValue| aliased to its largest (inclusive) value. Such as: // enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue }; template <typename T> T FuzzedDataProvider::ConsumeEnum() { static_assert(std::is_enum<T>::value, "|T| must be an enum type."); return static_cast<T>( ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue))); } // Returns a copy of the value selected from the given fixed-size |array|. template <typename T, size_t size> T FuzzedDataProvider::PickValueInArray(const T (&array)[size]) { static_assert(size > 0, "The array must be non empty."); return array[ConsumeIntegralInRange<size_t>(0, size - 1)]; } template <typename T, size_t size> T FuzzedDataProvider::PickValueInArray(const std::array<T, size> &array) { static_assert(size > 0, "The array must be non empty."); return array[ConsumeIntegralInRange<size_t>(0, size - 1)]; } template <typename T> T FuzzedDataProvider::PickValueInArray(std::initializer_list<const T> list) { // TODO(Dor1s): switch to static_assert once C++14 is allowed. if (!list.size()) abort(); return *(list.begin() + ConsumeIntegralInRange<size_t>(0, list.size() - 1)); } // Writes |num_bytes| of input data to the given destination pointer. If there // is not enough data left, writes all remaining bytes. Return value is the // number of bytes written. // In general, it's better to avoid using this function, but it may be useful // in cases when it's necessary to fill a certain buffer or object with // fuzzing data. inline size_t FuzzedDataProvider::ConsumeData(void *destination, size_t num_bytes) { num_bytes = std::min(num_bytes, remaining_bytes_); CopyAndAdvance(destination, num_bytes); return num_bytes; } // Private methods. inline void FuzzedDataProvider::CopyAndAdvance(void *destination, size_t num_bytes) { std::memcpy(destination, data_ptr_, num_bytes); Advance(num_bytes); } inline void FuzzedDataProvider::Advance(size_t num_bytes) { if (num_bytes > remaining_bytes_) abort(); data_ptr_ += num_bytes; remaining_bytes_ -= num_bytes; } template <typename T> std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t size, size_t num_bytes) { static_assert(sizeof(T) == sizeof(uint8_t), "Incompatible data type."); // The point of using the size-based constructor below is to increase the // odds of having a vector object with capacity being equal to the length. // That part is always implementation specific, but at least both libc++ and // libstdc++ allocate the requested number of bytes in that constructor, // which seems to be a natural choice for other implementations as well. // To increase the odds even more, we also call |shrink_to_fit| below. std::vector<T> result(size); if (size == 0) { if (num_bytes != 0) abort(); return result; } CopyAndAdvance(result.data(), num_bytes); // Even though |shrink_to_fit| is also implementation specific, we expect it // to provide an additional assurance in case vector's constructor allocated // a buffer which is larger than the actual amount of data we put inside it. result.shrink_to_fit(); return result; } template <typename TS, typename TU> TS FuzzedDataProvider::ConvertUnsignedToSigned(TU value) { static_assert(sizeof(TS) == sizeof(TU), "Incompatible data types."); static_assert(!std::numeric_limits<TU>::is_signed, "Source type must be unsigned."); // TODO(Dor1s): change to `if constexpr` once C++17 becomes mainstream. if (std::numeric_limits<TS>::is_modulo) return static_cast<TS>(value); // Avoid using implementation-defined unsigned to signed conversions. // To learn more, see https://stackoverflow.com/questions/13150449. if (value <= std::numeric_limits<TS>::max()) { return static_cast<TS>(value); } else { constexpr auto TS_min = std::numeric_limits<TS>::min(); return TS_min + static_cast<TS>(value - TS_min); } } #endif // LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
0
bitcoin/src/test
bitcoin/src/test/fuzz/block.cpp
// Copyright (c) 2019-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <core_io.h> #include <core_memusage.h> #include <primitives/block.h> #include <pubkey.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <util/chaintype.h> #include <validation.h> #include <cassert> #include <string> void initialize_block() { SelectParams(ChainType::REGTEST); } FUZZ_TARGET(block, .init = initialize_block) { DataStream ds{buffer}; CBlock block; try { ds >> TX_WITH_WITNESS(block); } catch (const std::ios_base::failure&) { return; } const Consensus::Params& consensus_params = Params().GetConsensus(); BlockValidationState validation_state_pow_and_merkle; const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true); assert(validation_state_pow_and_merkle.IsValid() || validation_state_pow_and_merkle.IsInvalid() || validation_state_pow_and_merkle.IsError()); (void)validation_state_pow_and_merkle.Error(""); BlockValidationState validation_state_pow; const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false); assert(validation_state_pow.IsValid() || validation_state_pow.IsInvalid() || validation_state_pow.IsError()); BlockValidationState validation_state_merkle; const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true); assert(validation_state_merkle.IsValid() || validation_state_merkle.IsInvalid() || validation_state_merkle.IsError()); BlockValidationState validation_state_none; const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false); assert(validation_state_none.IsValid() || validation_state_none.IsInvalid() || validation_state_none.IsError()); if (valid_incl_pow_and_merkle) { assert(valid_incl_pow && valid_incl_merkle && valid_incl_none); } else if (valid_incl_merkle || valid_incl_pow) { assert(valid_incl_none); } (void)block.GetHash(); (void)block.ToString(); (void)BlockMerkleRoot(block); if (!block.vtx.empty()) { (void)BlockWitnessMerkleRoot(block); } (void)GetBlockWeight(block); (void)GetWitnessCommitmentIndex(block); const size_t raw_memory_size = RecursiveDynamicUsage(block); const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared<CBlock>(block)); assert(raw_memory_size_as_shared_ptr > raw_memory_size); CBlock block_copy = block; block_copy.SetNull(); const bool is_null = block_copy.IsNull(); assert(is_null); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/netbase_dns_lookup.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <netbase.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util/net.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(netbase_dns_lookup) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const std::string name = fuzzed_data_provider.ConsumeRandomLengthString(512); const unsigned int max_results = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const bool allow_lookup = fuzzed_data_provider.ConsumeBool(); const uint16_t default_port = fuzzed_data_provider.ConsumeIntegral<uint16_t>(); auto fuzzed_dns_lookup_function = [&](const std::string&, bool) { std::vector<CNetAddr> resolved_addresses; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { resolved_addresses.push_back(ConsumeNetAddr(fuzzed_data_provider)); } return resolved_addresses; }; { const std::vector<CNetAddr> resolved_addresses{LookupHost(name, max_results, allow_lookup, fuzzed_dns_lookup_function)}; for (const CNetAddr& resolved_address : resolved_addresses) { assert(!resolved_address.IsInternal()); } assert(resolved_addresses.size() <= max_results || max_results == 0); } { const std::optional<CNetAddr> resolved_address{LookupHost(name, allow_lookup, fuzzed_dns_lookup_function)}; if (resolved_address.has_value()) { assert(!resolved_address.value().IsInternal()); } } { const std::vector<CService> resolved_services{Lookup(name, default_port, allow_lookup, max_results, fuzzed_dns_lookup_function)}; for (const CNetAddr& resolved_service : resolved_services) { assert(!resolved_service.IsInternal()); } assert(resolved_services.size() <= max_results || max_results == 0); } { const std::optional<CService> resolved_service{Lookup(name, default_port, allow_lookup, fuzzed_dns_lookup_function)}; if (resolved_service.has_value()) { assert(!resolved_service.value().IsInternal()); } } { CService resolved_service = LookupNumeric(name, default_port, fuzzed_dns_lookup_function); assert(!resolved_service.IsInternal()); } { (void)LookupSubNet(name); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/parse_script.cpp
// Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <script/script.h> #include <test/fuzz/fuzz.h> FUZZ_TARGET(parse_script) { const std::string script_string(buffer.begin(), buffer.end()); try { (void)ParseScript(script_string); } catch (const std::runtime_error&) { } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/connman.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addrman.h> #include <chainparams.h> #include <common/args.h> #include <net.h> #include <netaddress.h> #include <protocol.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/net.h> #include <test/util/setup_common.h> #include <util/translation.h> #include <cstdint> #include <vector> namespace { const TestingSetup* g_setup; } // namespace void initialize_connman() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } FUZZ_TARGET(connman, .init = initialize_connman) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; SetMockTime(ConsumeTime(fuzzed_data_provider)); ConnmanTestMsg connman{fuzzed_data_provider.ConsumeIntegral<uint64_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>(), *g_setup->m_node.addrman, *g_setup->m_node.netgroupman, Params(), fuzzed_data_provider.ConsumeBool()}; CNetAddr random_netaddr; CNode random_node = ConsumeNode(fuzzed_data_provider); CSubNet random_subnet; std::string random_string; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100) { CNode& p2p_node{*ConsumeNodeAsUniquePtr(fuzzed_data_provider).release()}; connman.AddTestNode(p2p_node); } LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { CallOneOf( fuzzed_data_provider, [&] { random_netaddr = ConsumeNetAddr(fuzzed_data_provider); }, [&] { random_subnet = ConsumeSubNet(fuzzed_data_provider); }, [&] { random_string = fuzzed_data_provider.ConsumeRandomLengthString(64); }, [&] { connman.AddNode({random_string, fuzzed_data_provider.ConsumeBool()}); }, [&] { connman.CheckIncomingNonce(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); }, [&] { connman.DisconnectNode(fuzzed_data_provider.ConsumeIntegral<NodeId>()); }, [&] { connman.DisconnectNode(random_netaddr); }, [&] { connman.DisconnectNode(random_string); }, [&] { connman.DisconnectNode(random_subnet); }, [&] { connman.ForEachNode([](auto) {}); }, [&] { (void)connman.ForNode(fuzzed_data_provider.ConsumeIntegral<NodeId>(), [&](auto) { return fuzzed_data_provider.ConsumeBool(); }); }, [&] { (void)connman.GetAddresses( /*max_addresses=*/fuzzed_data_provider.ConsumeIntegral<size_t>(), /*max_pct=*/fuzzed_data_provider.ConsumeIntegral<size_t>(), /*network=*/std::nullopt, /*filtered=*/fuzzed_data_provider.ConsumeBool()); }, [&] { (void)connman.GetAddresses( /*requestor=*/random_node, /*max_addresses=*/fuzzed_data_provider.ConsumeIntegral<size_t>(), /*max_pct=*/fuzzed_data_provider.ConsumeIntegral<size_t>()); }, [&] { (void)connman.GetDeterministicRandomizer(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); }, [&] { (void)connman.GetNodeCount(fuzzed_data_provider.PickValueInArray({ConnectionDirection::None, ConnectionDirection::In, ConnectionDirection::Out, ConnectionDirection::Both})); }, [&] { (void)connman.OutboundTargetReached(fuzzed_data_provider.ConsumeBool()); }, [&] { CSerializedNetMsg serialized_net_msg; serialized_net_msg.m_type = fuzzed_data_provider.ConsumeRandomLengthString(CMessageHeader::COMMAND_SIZE); serialized_net_msg.data = ConsumeRandomLengthByteVector(fuzzed_data_provider); connman.PushMessage(&random_node, std::move(serialized_net_msg)); }, [&] { connman.RemoveAddedNode(random_string); }, [&] { connman.SetNetworkActive(fuzzed_data_provider.ConsumeBool()); }, [&] { connman.SetTryNewOutboundPeer(fuzzed_data_provider.ConsumeBool()); }); } (void)connman.GetAddedNodeInfo(fuzzed_data_provider.ConsumeBool()); (void)connman.GetExtraFullOutboundCount(); (void)connman.GetLocalServices(); (void)connman.GetMaxOutboundTarget(); (void)connman.GetMaxOutboundTimeframe(); (void)connman.GetMaxOutboundTimeLeftInCycle(); (void)connman.GetNetworkActive(); std::vector<CNodeStats> stats; connman.GetNodeStats(stats); (void)connman.GetOutboundTargetBytesLeft(); (void)connman.GetTotalBytesRecv(); (void)connman.GetTotalBytesSent(); (void)connman.GetTryNewOutboundPeer(); (void)connman.GetUseAddrmanOutgoing(); connman.ClearTestNodes(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/rbf.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <node/mempool_args.h> #include <policy/rbf.h> #include <primitives/transaction.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/mempool.h> #include <test/util/setup_common.h> #include <test/util/txmempool.h> #include <txmempool.h> #include <cstdint> #include <optional> #include <string> #include <vector> namespace { const BasicTestingSetup* g_setup; } // namespace void initialize_rbf() { static const auto testing_setup = MakeNoLogFileContext<>(); g_setup = testing_setup.get(); } FUZZ_TARGET(rbf, .init = initialize_rbf) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!mtx) { return; } CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node)}; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const std::optional<CMutableTransaction> another_mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!another_mtx) { break; } const CTransaction another_tx{*another_mtx}; if (fuzzed_data_provider.ConsumeBool() && !mtx->vin.empty()) { mtx->vin[0].prevout = COutPoint{another_tx.GetHash(), 0}; } LOCK2(cs_main, pool.cs); pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, another_tx)); } const CTransaction tx{*mtx}; if (fuzzed_data_provider.ConsumeBool()) { LOCK2(cs_main, pool.cs); pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, tx)); } { LOCK(pool.cs); (void)IsRBFOptIn(tx, pool); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/bitdeque.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/util.h> #include <util/bitdeque.h> #include <deque> #include <vector> namespace { constexpr int LEN_BITS = 16; constexpr int RANDDATA_BITS = 20; using bitdeque_type = bitdeque<128>; //! Deterministic random vector of bools, for begin/end insertions to draw from. std::vector<bool> RANDDATA; void InitRandData() { FastRandomContext ctx(true); RANDDATA.clear(); for (size_t i = 0; i < (1U << RANDDATA_BITS) + (1U << LEN_BITS); ++i) { RANDDATA.push_back(ctx.randbool()); } } } // namespace FUZZ_TARGET(bitdeque, .init = InitRandData) { FuzzedDataProvider provider(buffer.data(), buffer.size()); FastRandomContext ctx(true); size_t maxlen = (1U << provider.ConsumeIntegralInRange<size_t>(0, LEN_BITS)) - 1; size_t limitlen = 4 * maxlen; std::deque<bool> deq; bitdeque_type bitdeq; const auto& cdeq = deq; const auto& cbitdeq = bitdeq; size_t initlen = provider.ConsumeIntegralInRange<size_t>(0, maxlen); while (initlen) { bool val = ctx.randbool(); deq.push_back(val); bitdeq.push_back(val); --initlen; } const auto iter_limit{maxlen > 6000 ? 90U : 900U}; LIMITED_WHILE(provider.remaining_bytes() > 0, iter_limit) { CallOneOf( provider, [&] { // constructor() deq = std::deque<bool>{}; bitdeq = bitdeque_type{}; }, [&] { // clear() deq.clear(); bitdeq.clear(); }, [&] { // resize() auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); deq.resize(count); bitdeq.resize(count); }, [&] { // assign(count, val) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); bool val = ctx.randbool(); deq.assign(count, val); bitdeq.assign(count, val); }, [&] { // constructor(count, val) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); bool val = ctx.randbool(); deq = std::deque<bool>(count, val); bitdeq = bitdeque_type(count, val); }, [&] { // constructor(count) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); deq = std::deque<bool>(count); bitdeq = bitdeque_type(count); }, [&] { // construct(begin, end) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; deq = std::deque<bool>(rand_begin, rand_end); bitdeq = bitdeque_type(rand_begin, rand_end); }, [&] { // assign(begin, end) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; deq.assign(rand_begin, rand_end); bitdeq.assign(rand_begin, rand_end); }, [&] { // construct(initializer_list) std::initializer_list<bool> ilist{ctx.randbool(), ctx.randbool(), ctx.randbool(), ctx.randbool(), ctx.randbool()}; deq = std::deque<bool>(ilist); bitdeq = bitdeque_type(ilist); }, [&] { // assign(initializer_list) std::initializer_list<bool> ilist{ctx.randbool(), ctx.randbool(), ctx.randbool()}; deq.assign(ilist); bitdeq.assign(ilist); }, [&] { // operator=(const&) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); bool val = ctx.randbool(); const std::deque<bool> deq2(count, val); deq = deq2; const bitdeque_type bitdeq2(count, val); bitdeq = bitdeq2; }, [&] { // operator=(&&) auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); bool val = ctx.randbool(); std::deque<bool> deq2(count, val); deq = std::move(deq2); bitdeque_type bitdeq2(count, val); bitdeq = std::move(bitdeq2); }, [&] { // deque swap auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; std::deque<bool> deq2(rand_begin, rand_end); bitdeque_type bitdeq2(rand_begin, rand_end); using std::swap; assert(deq.size() == bitdeq.size()); assert(deq2.size() == bitdeq2.size()); swap(deq, deq2); swap(bitdeq, bitdeq2); assert(deq.size() == bitdeq.size()); assert(deq2.size() == bitdeq2.size()); }, [&] { // deque.swap auto count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; std::deque<bool> deq2(rand_begin, rand_end); bitdeque_type bitdeq2(rand_begin, rand_end); assert(deq.size() == bitdeq.size()); assert(deq2.size() == bitdeq2.size()); deq.swap(deq2); bitdeq.swap(bitdeq2); assert(deq.size() == bitdeq.size()); assert(deq2.size() == bitdeq2.size()); }, [&] { // operator=(initializer_list) std::initializer_list<bool> ilist{ctx.randbool(), ctx.randbool(), ctx.randbool()}; deq = ilist; bitdeq = ilist; }, [&] { // iterator arithmetic auto pos1 = provider.ConsumeIntegralInRange<long>(0, cdeq.size()); auto pos2 = provider.ConsumeIntegralInRange<long>(0, cdeq.size()); auto it = deq.begin() + pos1; auto bitit = bitdeq.begin() + pos1; if ((size_t)pos1 != cdeq.size()) assert(*it == *bitit); assert(it - deq.begin() == pos1); assert(bitit - bitdeq.begin() == pos1); if (provider.ConsumeBool()) { it += pos2 - pos1; bitit += pos2 - pos1; } else { it -= pos1 - pos2; bitit -= pos1 - pos2; } if ((size_t)pos2 != cdeq.size()) assert(*it == *bitit); assert(deq.end() - it == bitdeq.end() - bitit); if (provider.ConsumeBool()) { if ((size_t)pos2 != cdeq.size()) { ++it; ++bitit; } } else { if (pos2 != 0) { --it; --bitit; } } assert(deq.end() - it == bitdeq.end() - bitit); }, [&] { // begin() and end() assert(deq.end() - deq.begin() == bitdeq.end() - bitdeq.begin()); }, [&] { // begin() and end() (const) assert(cdeq.end() - cdeq.begin() == cbitdeq.end() - cbitdeq.begin()); }, [&] { // rbegin() and rend() assert(deq.rend() - deq.rbegin() == bitdeq.rend() - bitdeq.rbegin()); }, [&] { // rbegin() and rend() (const) assert(cdeq.rend() - cdeq.rbegin() == cbitdeq.rend() - cbitdeq.rbegin()); }, [&] { // cbegin() and cend() assert(cdeq.cend() - cdeq.cbegin() == cbitdeq.cend() - cbitdeq.cbegin()); }, [&] { // crbegin() and crend() assert(cdeq.crend() - cdeq.crbegin() == cbitdeq.crend() - cbitdeq.crbegin()); }, [&] { // size() and maxsize() assert(cdeq.size() == cbitdeq.size()); assert(cbitdeq.size() <= cbitdeq.max_size()); }, [&] { // empty assert(cdeq.empty() == cbitdeq.empty()); }, [&] { // at (in range) and flip if (!cdeq.empty()) { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); auto& ref = deq.at(pos); auto bitref = bitdeq.at(pos); assert(ref == bitref); if (ctx.randbool()) { ref = !ref; bitref.flip(); } } }, [&] { // at (maybe out of range) and bit assign size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() + maxlen); bool newval = ctx.randbool(); bool throw_deq{false}, throw_bitdeq{false}; bool val_deq{false}, val_bitdeq{false}; try { auto& ref = deq.at(pos); val_deq = ref; ref = newval; } catch (const std::out_of_range&) { throw_deq = true; } try { auto ref = bitdeq.at(pos); val_bitdeq = ref; ref = newval; } catch (const std::out_of_range&) { throw_bitdeq = true; } assert(throw_deq == throw_bitdeq); assert(throw_bitdeq == (pos >= cdeq.size())); if (!throw_deq) assert(val_deq == val_bitdeq); }, [&] { // at (maybe out of range) (const) size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() + maxlen); bool throw_deq{false}, throw_bitdeq{false}; bool val_deq{false}, val_bitdeq{false}; try { auto& ref = cdeq.at(pos); val_deq = ref; } catch (const std::out_of_range&) { throw_deq = true; } try { auto ref = cbitdeq.at(pos); val_bitdeq = ref; } catch (const std::out_of_range&) { throw_bitdeq = true; } assert(throw_deq == throw_bitdeq); assert(throw_bitdeq == (pos >= cdeq.size())); if (!throw_deq) assert(val_deq == val_bitdeq); }, [&] { // operator[] if (!cdeq.empty()) { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); assert(deq[pos] == bitdeq[pos]); if (ctx.randbool()) { deq[pos] = !deq[pos]; bitdeq[pos].flip(); } } }, [&] { // operator[] const if (!cdeq.empty()) { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); assert(deq[pos] == bitdeq[pos]); } }, [&] { // front() if (!cdeq.empty()) { auto& ref = deq.front(); auto bitref = bitdeq.front(); assert(ref == bitref); if (ctx.randbool()) { ref = !ref; bitref = !bitref; } } }, [&] { // front() const if (!cdeq.empty()) { auto& ref = cdeq.front(); auto bitref = cbitdeq.front(); assert(ref == bitref); } }, [&] { // back() and swap(bool, ref) if (!cdeq.empty()) { auto& ref = deq.back(); auto bitref = bitdeq.back(); assert(ref == bitref); if (ctx.randbool()) { ref = !ref; bitref.flip(); } } }, [&] { // back() const if (!cdeq.empty()) { const auto& cdeq = deq; const auto& cbitdeq = bitdeq; auto& ref = cdeq.back(); auto bitref = cbitdeq.back(); assert(ref == bitref); } }, [&] { // push_back() if (cdeq.size() < limitlen) { bool val = ctx.randbool(); if (cdeq.empty()) { deq.push_back(val); bitdeq.push_back(val); } else { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); auto& ref = deq[pos]; auto bitref = bitdeq[pos]; assert(ref == bitref); deq.push_back(val); bitdeq.push_back(val); assert(ref == bitref); // references are not invalidated } } }, [&] { // push_front() if (cdeq.size() < limitlen) { bool val = ctx.randbool(); if (cdeq.empty()) { deq.push_front(val); bitdeq.push_front(val); } else { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); auto& ref = deq[pos]; auto bitref = bitdeq[pos]; assert(ref == bitref); deq.push_front(val); bitdeq.push_front(val); assert(ref == bitref); // references are not invalidated } } }, [&] { // pop_back() if (!cdeq.empty()) { if (cdeq.size() == 1) { deq.pop_back(); bitdeq.pop_back(); } else { size_t pos = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 2); auto& ref = deq[pos]; auto bitref = bitdeq[pos]; assert(ref == bitref); deq.pop_back(); bitdeq.pop_back(); assert(ref == bitref); // references to other elements are not invalidated } } }, [&] { // pop_front() if (!cdeq.empty()) { if (cdeq.size() == 1) { deq.pop_front(); bitdeq.pop_front(); } else { size_t pos = provider.ConsumeIntegralInRange<size_t>(1, cdeq.size() - 1); auto& ref = deq[pos]; auto bitref = bitdeq[pos]; assert(ref == bitref); deq.pop_front(); bitdeq.pop_front(); assert(ref == bitref); // references to other elements are not invalidated } } }, [&] { // erase (in middle, single) if (!cdeq.empty()) { size_t before = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - 1); size_t after = cdeq.size() - 1 - before; auto it = deq.erase(cdeq.begin() + before); auto bitit = bitdeq.erase(cbitdeq.begin() + before); assert(it == cdeq.begin() + before && it == cdeq.end() - after); assert(bitit == cbitdeq.begin() + before && bitit == cbitdeq.end() - after); } }, [&] { // erase (at front, range) size_t count = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); auto it = deq.erase(cdeq.begin(), cdeq.begin() + count); auto bitit = bitdeq.erase(cbitdeq.begin(), cbitdeq.begin() + count); assert(it == deq.begin()); assert(bitit == bitdeq.begin()); }, [&] { // erase (at back, range) size_t count = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); auto it = deq.erase(cdeq.end() - count, cdeq.end()); auto bitit = bitdeq.erase(cbitdeq.end() - count, cbitdeq.end()); assert(it == deq.end()); assert(bitit == bitdeq.end()); }, [&] { // erase (in middle, range) size_t count = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); size_t before = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size() - count); size_t after = cdeq.size() - count - before; auto it = deq.erase(cdeq.begin() + before, cdeq.end() - after); auto bitit = bitdeq.erase(cbitdeq.begin() + before, cbitdeq.end() - after); assert(it == cdeq.begin() + before && it == cdeq.end() - after); assert(bitit == cbitdeq.begin() + before && bitit == cbitdeq.end() - after); }, [&] { // insert/emplace (in middle, single) if (cdeq.size() < limitlen) { size_t before = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); bool val = ctx.randbool(); bool do_emplace = provider.ConsumeBool(); auto it = deq.insert(cdeq.begin() + before, val); auto bitit = do_emplace ? bitdeq.emplace(cbitdeq.begin() + before, val) : bitdeq.insert(cbitdeq.begin() + before, val); assert(it == deq.begin() + before); assert(bitit == bitdeq.begin() + before); } }, [&] { // insert (at front, begin/end) if (cdeq.size() < limitlen) { size_t count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; auto it = deq.insert(cdeq.begin(), rand_begin, rand_end); auto bitit = bitdeq.insert(cbitdeq.begin(), rand_begin, rand_end); assert(it == cdeq.begin()); assert(bitit == cbitdeq.begin()); } }, [&] { // insert (at back, begin/end) if (cdeq.size() < limitlen) { size_t count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; auto it = deq.insert(cdeq.end(), rand_begin, rand_end); auto bitit = bitdeq.insert(cbitdeq.end(), rand_begin, rand_end); assert(it == cdeq.end() - count); assert(bitit == cbitdeq.end() - count); } }, [&] { // insert (in middle, range) if (cdeq.size() < limitlen) { size_t count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); size_t before = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); bool val = ctx.randbool(); auto it = deq.insert(cdeq.begin() + before, count, val); auto bitit = bitdeq.insert(cbitdeq.begin() + before, count, val); assert(it == deq.begin() + before); assert(bitit == bitdeq.begin() + before); } }, [&] { // insert (in middle, begin/end) if (cdeq.size() < limitlen) { size_t count = provider.ConsumeIntegralInRange<size_t>(0, maxlen); size_t before = provider.ConsumeIntegralInRange<size_t>(0, cdeq.size()); auto rand_begin = RANDDATA.begin() + ctx.randbits(RANDDATA_BITS); auto rand_end = rand_begin + count; auto it = deq.insert(cdeq.begin() + before, rand_begin, rand_end); auto bitit = bitdeq.insert(cbitdeq.begin() + before, rand_begin, rand_end); assert(it == deq.begin() + before); assert(bitit == bitdeq.begin() + before); } }); } { assert(deq.size() == bitdeq.size()); auto it = deq.begin(); auto bitit = bitdeq.begin(); auto itend = deq.end(); while (it != itend) { assert(*it == *bitit); ++it; ++bitit; } } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/bloom_filter.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <common/bloom.h> #include <primitives/transaction.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <uint256.h> #include <cassert> #include <limits> #include <optional> #include <vector> FUZZ_TARGET(bloom_filter) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); bool good_data{true}; CBloomFilter bloom_filter{ fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(1, 10000000), 1.0 / fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(1, std::numeric_limits<unsigned int>::max()), fuzzed_data_provider.ConsumeIntegral<unsigned int>(), static_cast<unsigned char>(fuzzed_data_provider.PickValueInArray({BLOOM_UPDATE_NONE, BLOOM_UPDATE_ALL, BLOOM_UPDATE_P2PUBKEY_ONLY, BLOOM_UPDATE_MASK}))}; LIMITED_WHILE(good_data && fuzzed_data_provider.remaining_bytes() > 0, 10'000) { CallOneOf( fuzzed_data_provider, [&] { const std::vector<unsigned char> b = ConsumeRandomLengthByteVector(fuzzed_data_provider); (void)bloom_filter.contains(b); bloom_filter.insert(b); const bool present = bloom_filter.contains(b); assert(present); }, [&] { const std::optional<COutPoint> out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider); if (!out_point) { good_data = false; return; } (void)bloom_filter.contains(*out_point); bloom_filter.insert(*out_point); const bool present = bloom_filter.contains(*out_point); assert(present); }, [&] { const std::optional<uint256> u256 = ConsumeDeserializable<uint256>(fuzzed_data_provider); if (!u256) { good_data = false; return; } (void)bloom_filter.contains(*u256); bloom_filter.insert(*u256); const bool present = bloom_filter.contains(*u256); assert(present); }, [&] { const std::optional<CMutableTransaction> mut_tx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!mut_tx) { good_data = false; return; } const CTransaction tx{*mut_tx}; (void)bloom_filter.IsRelevantAndUpdate(tx); }); (void)bloom_filter.IsWithinSizeConstraints(); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/partially_downloaded_block.cpp
#include <blockencodings.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/mempool.h> #include <test/util/setup_common.h> #include <test/util/txmempool.h> #include <txmempool.h> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <set> #include <vector> namespace { const TestingSetup* g_setup; } // namespace void initialize_pdb() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } PartiallyDownloadedBlock::CheckBlockFn FuzzedCheckBlock(std::optional<BlockValidationResult> result) { return [result](const CBlock&, BlockValidationState& state, const Consensus::Params&, bool, bool) { if (result) { return state.Invalid(*result); } return true; }; } FUZZ_TARGET(partially_downloaded_block, .init = initialize_pdb) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; auto block{ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS)}; if (!block || block->vtx.size() == 0 || block->vtx.size() >= std::numeric_limits<uint16_t>::max()) { return; } CBlockHeaderAndShortTxIDs cmpctblock{*block}; CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node)}; PartiallyDownloadedBlock pdb{&pool}; // Set of available transactions (mempool or extra_txn) std::set<uint16_t> available; // The coinbase is always available available.insert(0); std::vector<std::pair<uint256, CTransactionRef>> extra_txn; for (size_t i = 1; i < block->vtx.size(); ++i) { auto tx{block->vtx[i]}; bool add_to_extra_txn{fuzzed_data_provider.ConsumeBool()}; bool add_to_mempool{fuzzed_data_provider.ConsumeBool()}; if (add_to_extra_txn) { extra_txn.emplace_back(tx->GetWitnessHash(), tx); available.insert(i); } if (add_to_mempool) { LOCK2(cs_main, pool.cs); pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, *tx)); available.insert(i); } } auto init_status{pdb.InitData(cmpctblock, extra_txn)}; std::vector<CTransactionRef> missing; // Whether we skipped a transaction that should be included in `missing`. // FillBlock should never return READ_STATUS_OK if that is the case. bool skipped_missing{false}; for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) { // If init_status == READ_STATUS_OK then a available transaction in the // compact block (i.e. IsTxAvailable(i) == true) implies that we marked // that transaction as available above (i.e. available.count(i) > 0). // The reverse is not true, due to possible compact block short id // collisions (i.e. available.count(i) > 0 does not imply // IsTxAvailable(i) == true). if (init_status == READ_STATUS_OK) { assert(!pdb.IsTxAvailable(i) || available.count(i) > 0); } bool skip{fuzzed_data_provider.ConsumeBool()}; if (!pdb.IsTxAvailable(i) && !skip) { missing.push_back(block->vtx[i]); } skipped_missing |= (!pdb.IsTxAvailable(i) && skip); } // Mock CheckBlock bool fail_check_block{fuzzed_data_provider.ConsumeBool()}; auto validation_result = fuzzed_data_provider.PickValueInArray( {BlockValidationResult::BLOCK_RESULT_UNSET, BlockValidationResult::BLOCK_CONSENSUS, BlockValidationResult::BLOCK_RECENT_CONSENSUS_CHANGE, BlockValidationResult::BLOCK_CACHED_INVALID, BlockValidationResult::BLOCK_INVALID_HEADER, BlockValidationResult::BLOCK_MUTATED, BlockValidationResult::BLOCK_MISSING_PREV, BlockValidationResult::BLOCK_INVALID_PREV, BlockValidationResult::BLOCK_TIME_FUTURE, BlockValidationResult::BLOCK_CHECKPOINT, BlockValidationResult::BLOCK_HEADER_LOW_WORK}); pdb.m_check_block_mock = FuzzedCheckBlock( fail_check_block ? std::optional<BlockValidationResult>{validation_result} : std::nullopt); CBlock reconstructed_block; auto fill_status{pdb.FillBlock(reconstructed_block, missing)}; switch (fill_status) { case READ_STATUS_OK: assert(!skipped_missing); assert(!fail_check_block); assert(block->GetHash() == reconstructed_block.GetHash()); break; case READ_STATUS_CHECKBLOCK_FAILED: [[fallthrough]]; case READ_STATUS_FAILED: assert(fail_check_block); break; case READ_STATUS_INVALID: break; } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/policy_estimator.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <kernel/mempool_entry.h> #include <policy/fees.h> #include <policy/fees_args.h> #include <primitives/transaction.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/mempool.h> #include <test/util/setup_common.h> #include <memory> #include <optional> #include <vector> namespace { const BasicTestingSetup* g_setup; } // namespace void initialize_policy_estimator() { static const auto testing_setup = MakeNoLogFileContext<>(); g_setup = testing_setup.get(); } FUZZ_TARGET(policy_estimator, .init = initialize_policy_estimator) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); bool good_data{true}; CBlockPolicyEstimator block_policy_estimator{FeeestPath(*g_setup->m_node.args), DEFAULT_ACCEPT_STALE_FEE_ESTIMATES}; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000) { CallOneOf( fuzzed_data_provider, [&] { const std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!mtx) { good_data = false; return; } const CTransaction tx{*mtx}; const CTxMemPoolEntry& entry = ConsumeTxMemPoolEntry(fuzzed_data_provider, tx); const auto tx_info = NewMempoolTransactionInfo(entry.GetSharedTx(), entry.GetFee(), entry.GetTxSize(), entry.GetHeight(), /* m_from_disconnected_block */ false, /* m_submitted_in_package */ false, /* m_chainstate_is_current */ true, /* m_has_no_mempool_parents */ fuzzed_data_provider.ConsumeBool()); block_policy_estimator.processTransaction(tx_info); if (fuzzed_data_provider.ConsumeBool()) { (void)block_policy_estimator.removeTx(tx.GetHash()); } }, [&] { std::list<CTxMemPoolEntry> mempool_entries; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); if (!mtx) { good_data = false; break; } const CTransaction tx{*mtx}; mempool_entries.emplace_back(CTxMemPoolEntry::ExplicitCopy, ConsumeTxMemPoolEntry(fuzzed_data_provider, tx)); } std::vector<RemovedMempoolTransactionInfo> txs; txs.reserve(mempool_entries.size()); for (const CTxMemPoolEntry& mempool_entry : mempool_entries) { txs.emplace_back(mempool_entry); } block_policy_estimator.processBlock(txs, fuzzed_data_provider.ConsumeIntegral<unsigned int>()); }, [&] { (void)block_policy_estimator.removeTx(ConsumeUInt256(fuzzed_data_provider)); }, [&] { block_policy_estimator.FlushUnconfirmed(); }); (void)block_policy_estimator.estimateFee(fuzzed_data_provider.ConsumeIntegral<int>()); EstimationResult result; (void)block_policy_estimator.estimateRawFee(fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeFloatingPoint<double>(), fuzzed_data_provider.PickValueInArray(ALL_FEE_ESTIMATE_HORIZONS), fuzzed_data_provider.ConsumeBool() ? &result : nullptr); FeeCalculation fee_calculation; (void)block_policy_estimator.estimateSmartFee(fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeBool() ? &fee_calculation : nullptr, fuzzed_data_provider.ConsumeBool()); (void)block_policy_estimator.HighestTargetTracked(fuzzed_data_provider.PickValueInArray(ALL_FEE_ESTIMATE_HORIZONS)); } { FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider}; AutoFile fuzzed_auto_file{fuzzed_file_provider.open()}; block_policy_estimator.Write(fuzzed_auto_file); block_policy_estimator.Read(fuzzed_auto_file); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/process_message.cpp
// Copyright (c) 2020-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/consensus.h> #include <net.h> #include <net_processing.h> #include <primitives/transaction.h> #include <protocol.h> #include <script/script.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/net.h> #include <test/util/mining.h> #include <test/util/net.h> #include <test/util/setup_common.h> #include <test/util/validation.h> #include <util/check.h> #include <util/time.h> #include <validationinterface.h> #include <cstdlib> #include <iostream> #include <memory> #include <string> #include <string_view> #include <vector> namespace { const TestingSetup* g_setup; std::string_view LIMIT_TO_MESSAGE_TYPE{}; } // namespace void initialize_process_message() { if (const auto val{std::getenv("LIMIT_TO_MESSAGE_TYPE")}) { LIMIT_TO_MESSAGE_TYPE = val; Assert(std::count(getAllNetMessageTypes().begin(), getAllNetMessageTypes().end(), LIMIT_TO_MESSAGE_TYPE)); // Unknown message type passed } static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>( /*chain_type=*/ChainType::REGTEST, /*extra_args=*/{"-txreconciliation"}); g_setup = testing_setup.get(); for (int i = 0; i < 2 * COINBASE_MATURITY; i++) { MineBlock(g_setup->m_node, CScript() << OP_TRUE); } SyncWithValidationInterfaceQueue(); } FUZZ_TARGET(process_message, .init = initialize_process_message) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); ConnmanTestMsg& connman = *static_cast<ConnmanTestMsg*>(g_setup->m_node.connman.get()); auto& chainman = static_cast<TestChainstateManager&>(*g_setup->m_node.chainman); SetMockTime(1610000000); // any time to successfully reset ibd chainman.ResetIbd(); LOCK(NetEventsInterface::g_msgproc_mutex); const std::string random_message_type{fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE).c_str()}; if (!LIMIT_TO_MESSAGE_TYPE.empty() && random_message_type != LIMIT_TO_MESSAGE_TYPE) { return; } CNode& p2p_node = *ConsumeNodeAsUniquePtr(fuzzed_data_provider).release(); connman.AddTestNode(p2p_node); FillNode(fuzzed_data_provider, connman, p2p_node); const auto mock_time = ConsumeTime(fuzzed_data_provider); SetMockTime(mock_time); CSerializedNetMsg net_msg; net_msg.m_type = random_message_type; net_msg.data = ConsumeRandomLengthByteVector(fuzzed_data_provider, MAX_PROTOCOL_MESSAGE_LENGTH); connman.FlushSendBuffer(p2p_node); (void)connman.ReceiveMsgFrom(p2p_node, std::move(net_msg)); bool more_work{true}; while (more_work) { p2p_node.fPauseSend = false; try { more_work = connman.ProcessMessagesOnce(p2p_node); } catch (const std::ios_base::failure&) { } g_setup->m_node.peerman->SendMessages(&p2p_node); } SyncWithValidationInterfaceQueue(); g_setup->m_node.connman->StopNodes(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/script_flags.cpp
// Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <serialize.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <test/util/script.h> #include <cassert> #include <ios> #include <utility> #include <vector> FUZZ_TARGET(script_flags) { if (buffer.size() > 100'000) return; DataStream ds{buffer}; try { const CTransaction tx(deserialize, TX_WITH_WITNESS, ds); unsigned int verify_flags; ds >> verify_flags; if (!IsValidFlagCombination(verify_flags)) return; unsigned int fuzzed_flags; ds >> fuzzed_flags; std::vector<CTxOut> spent_outputs; for (unsigned i = 0; i < tx.vin.size(); ++i) { CTxOut prevout; ds >> prevout; if (!MoneyRange(prevout.nValue)) { // prevouts should be consensus-valid prevout.nValue = 1; } spent_outputs.push_back(prevout); } PrecomputedTransactionData txdata; txdata.Init(tx, std::move(spent_outputs)); for (unsigned i = 0; i < tx.vin.size(); ++i) { const CTxOut& prevout = txdata.m_spent_outputs.at(i); const TransactionSignatureChecker checker{&tx, i, prevout.nValue, txdata, MissingDataBehavior::ASSERT_FAIL}; ScriptError serror; const bool ret = VerifyScript(tx.vin.at(i).scriptSig, prevout.scriptPubKey, &tx.vin.at(i).scriptWitness, verify_flags, checker, &serror); assert(ret == (serror == SCRIPT_ERR_OK)); // Verify that removing flags from a passing test or adding flags to a failing test does not change the result if (ret) { verify_flags &= ~fuzzed_flags; } else { verify_flags |= fuzzed_flags; } if (!IsValidFlagCombination(verify_flags)) return; ScriptError serror_fuzzed; const bool ret_fuzzed = VerifyScript(tx.vin.at(i).scriptSig, prevout.scriptPubKey, &tx.vin.at(i).scriptWitness, verify_flags, checker, &serror_fuzzed); assert(ret_fuzzed == (serror_fuzzed == SCRIPT_ERR_OK)); assert(ret_fuzzed == ret); } } catch (const std::ios_base::failure&) { return; } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/multiplication_overflow.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> namespace { template <typename T> void TestMultiplicationOverflow(FuzzedDataProvider& fuzzed_data_provider) { const T i = fuzzed_data_provider.ConsumeIntegral<T>(); const T j = fuzzed_data_provider.ConsumeIntegral<T>(); const bool is_multiplication_overflow_custom = MultiplicationOverflow(i, j); #if defined(HAVE_BUILTIN_MUL_OVERFLOW) T result_builtin; const bool is_multiplication_overflow_builtin = __builtin_mul_overflow(i, j, &result_builtin); assert(is_multiplication_overflow_custom == is_multiplication_overflow_builtin); if (!is_multiplication_overflow_custom) { assert(i * j == result_builtin); } #else if (!is_multiplication_overflow_custom) { (void)(i * j); } #endif } } // namespace FUZZ_TARGET(multiplication_overflow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); TestMultiplicationOverflow<int64_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint64_t>(fuzzed_data_provider); TestMultiplicationOverflow<int32_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint32_t>(fuzzed_data_provider); TestMultiplicationOverflow<int16_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint16_t>(fuzzed_data_provider); TestMultiplicationOverflow<char>(fuzzed_data_provider); TestMultiplicationOverflow<unsigned char>(fuzzed_data_provider); TestMultiplicationOverflow<signed char>(fuzzed_data_provider); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/string.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <blockfilter.h> #include <clientversion.h> #include <common/args.h> #include <common/settings.h> #include <common/system.h> #include <common/url.h> #include <netbase.h> #include <outputtype.h> #include <rpc/client.h> #include <rpc/request.h> #include <rpc/server.h> #include <rpc/util.h> #include <script/descriptor.h> #include <script/script.h> #include <serialize.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/error.h> #include <util/fees.h> #include <util/strencodings.h> #include <util/string.h> #include <util/translation.h> #include <cassert> #include <cstdint> #include <cstdlib> #include <ios> #include <stdexcept> #include <string> #include <vector> enum class FeeEstimateMode; FUZZ_TARGET(string) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::string random_string_1 = fuzzed_data_provider.ConsumeRandomLengthString(32); const std::string random_string_2 = fuzzed_data_provider.ConsumeRandomLengthString(32); const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider); (void)AmountErrMsg(random_string_1, random_string_2); (void)AmountHighWarn(random_string_1); BlockFilterType block_filter_type; (void)BlockFilterTypeByName(random_string_1, block_filter_type); (void)Capitalize(random_string_1); (void)CopyrightHolders(random_string_1); FeeEstimateMode fee_estimate_mode; (void)FeeModeFromString(random_string_1, fee_estimate_mode); const auto width{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 1000)}; (void)FormatParagraph(random_string_1, width, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, width)); (void)FormatSubVersion(random_string_1, fuzzed_data_provider.ConsumeIntegral<int>(), random_string_vector); (void)GetDescriptorChecksum(random_string_1); (void)HelpExampleCli(random_string_1, random_string_2); (void)HelpExampleRpc(random_string_1, random_string_2); (void)HelpMessageGroup(random_string_1); (void)HelpMessageOpt(random_string_1, random_string_2); (void)IsDeprecatedRPCEnabled(random_string_1); (void)Join(random_string_vector, random_string_1); (void)JSONRPCError(fuzzed_data_provider.ConsumeIntegral<int>(), random_string_1); const common::Settings settings; (void)OnlyHasDefaultSectionSetting(settings, random_string_1, random_string_2); (void)ParseNetwork(random_string_1); (void)ParseOutputType(random_string_1); (void)RemovePrefix(random_string_1, random_string_2); (void)ResolveErrMsg(random_string_1, random_string_2); try { (void)RPCConvertNamedValues(random_string_1, random_string_vector); } catch (const std::runtime_error&) { } try { (void)RPCConvertValues(random_string_1, random_string_vector); } catch (const std::runtime_error&) { } (void)SanitizeString(random_string_1); (void)SanitizeString(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 3)); #ifndef WIN32 (void)ShellEscape(random_string_1); #endif // WIN32 uint16_t port_out; std::string host_out; SplitHostPort(random_string_1, port_out, host_out); (void)TimingResistantEqual(random_string_1, random_string_2); (void)ToLower(random_string_1); (void)ToUpper(random_string_1); (void)TrimString(random_string_1); (void)TrimString(random_string_1, random_string_2); (void)urlDecode(random_string_1); (void)ContainsNoNUL(random_string_1); (void)_(random_string_1.c_str()); try { throw scriptnum_error{random_string_1}; } catch (const std::runtime_error&) { } { DataStream data_stream{}; std::string s; auto limited_string = LIMITED_STRING(s, 10); data_stream << random_string_1; try { data_stream >> limited_string; assert(data_stream.empty()); assert(s.size() <= random_string_1.size()); assert(s.size() <= 10); if (!random_string_1.empty()) { assert(!s.empty()); } } catch (const std::ios_base::failure&) { } } { DataStream data_stream{}; const auto limited_string = LIMITED_STRING(random_string_1, 10); data_stream << limited_string; std::string deserialized_string; data_stream >> deserialized_string; assert(data_stream.empty()); assert(deserialized_string == random_string_1); } { int64_t amount_out; (void)ParseFixedPoint(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 1024), &amount_out); } { const auto single_split{SplitString(random_string_1, fuzzed_data_provider.ConsumeIntegral<char>())}; assert(single_split.size() >= 1); const auto any_split{SplitString(random_string_1, random_string_2)}; assert(any_split.size() >= 1); } { (void)Untranslated(random_string_1); const bilingual_str bs1{random_string_1, random_string_2}; const bilingual_str bs2{random_string_2, random_string_1}; (void)(bs1 + bs2); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/txrequest.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/common.h> #include <crypto/sha256.h> #include <crypto/siphash.h> #include <primitives/transaction.h> #include <test/fuzz/fuzz.h> #include <txrequest.h> #include <bitset> #include <cstdint> #include <queue> #include <vector> namespace { constexpr int MAX_TXHASHES = 16; constexpr int MAX_PEERS = 16; //! Randomly generated GenTxids used in this test (length is MAX_TXHASHES). uint256 TXHASHES[MAX_TXHASHES]; //! Precomputed random durations (positive and negative, each ~exponentially distributed). std::chrono::microseconds DELAYS[256]; struct Initializer { Initializer() { for (uint8_t txhash = 0; txhash < MAX_TXHASHES; txhash += 1) { CSHA256().Write(&txhash, 1).Finalize(TXHASHES[txhash].begin()); } int i = 0; // DELAYS[N] for N=0..15 is just N microseconds. for (; i < 16; ++i) { DELAYS[i] = std::chrono::microseconds{i}; } // DELAYS[N] for N=16..127 has randomly-looking but roughly exponentially increasing values up to // 198.416453 seconds. for (; i < 128; ++i) { int diff_bits = ((i - 10) * 2) / 9; uint64_t diff = 1 + (CSipHasher(0, 0).Write(i).Finalize() >> (64 - diff_bits)); DELAYS[i] = DELAYS[i - 1] + std::chrono::microseconds{diff}; } // DELAYS[N] for N=128..255 are negative delays with the same magnitude as N=0..127. for (; i < 256; ++i) { DELAYS[i] = -DELAYS[255 - i]; } } } g_initializer; /** Tester class for TxRequestTracker * * It includes a naive reimplementation of its behavior, for a limited set * of MAX_TXHASHES distinct txids, and MAX_PEERS peer identifiers. * * All of the public member functions perform the same operation on * an actual TxRequestTracker and on the state of the reimplementation. * The output of GetRequestable is compared with the expected value * as well. * * Check() calls the TxRequestTracker's sanity check, plus compares the * output of the constant accessors (Size(), CountLoad(), CountTracked()) * with expected values. */ class Tester { //! TxRequestTracker object being tested. TxRequestTracker m_tracker; //! States for txid/peer combinations in the naive data structure. enum class State { NOTHING, //!< Absence of this txid/peer combination // Note that this implementation does not distinguish between DELAYED/READY/BEST variants of CANDIDATE. CANDIDATE, REQUESTED, COMPLETED, }; //! Sequence numbers, incremented whenever a new CANDIDATE is added. uint64_t m_current_sequence{0}; //! List of future 'events' (all inserted reqtimes/exptimes). This is used to implement AdvanceToEvent. std::priority_queue<std::chrono::microseconds, std::vector<std::chrono::microseconds>, std::greater<std::chrono::microseconds>> m_events; //! Information about a txhash/peer combination. struct Announcement { std::chrono::microseconds m_time; uint64_t m_sequence; State m_state{State::NOTHING}; bool m_preferred; bool m_is_wtxid; uint64_t m_priority; //!< Precomputed priority. }; //! Information about all txhash/peer combination. Announcement m_announcements[MAX_TXHASHES][MAX_PEERS]; //! The current time; can move forward and backward. std::chrono::microseconds m_now{244466666}; //! Delete txhashes whose only announcements are COMPLETED. void Cleanup(int txhash) { bool all_nothing = true; for (int peer = 0; peer < MAX_PEERS; ++peer) { const Announcement& ann = m_announcements[txhash][peer]; if (ann.m_state != State::NOTHING) { if (ann.m_state != State::COMPLETED) return; all_nothing = false; } } if (all_nothing) return; for (int peer = 0; peer < MAX_PEERS; ++peer) { m_announcements[txhash][peer].m_state = State::NOTHING; } } //! Find the current best peer to request from for a txhash (or -1 if none). int GetSelected(int txhash) const { int ret = -1; uint64_t ret_priority = 0; for (int peer = 0; peer < MAX_PEERS; ++peer) { const Announcement& ann = m_announcements[txhash][peer]; // Return -1 if there already is a (non-expired) in-flight request. if (ann.m_state == State::REQUESTED) return -1; // If it's a viable candidate, see if it has lower priority than the best one so far. if (ann.m_state == State::CANDIDATE && ann.m_time <= m_now) { if (ret == -1 || ann.m_priority > ret_priority) { std::tie(ret, ret_priority) = std::tie(peer, ann.m_priority); } } } return ret; } public: Tester() : m_tracker(true) {} std::chrono::microseconds Now() const { return m_now; } void AdvanceTime(std::chrono::microseconds offset) { m_now += offset; while (!m_events.empty() && m_events.top() <= m_now) m_events.pop(); } void AdvanceToEvent() { while (!m_events.empty() && m_events.top() <= m_now) m_events.pop(); if (!m_events.empty()) { m_now = m_events.top(); m_events.pop(); } } void DisconnectedPeer(int peer) { // Apply to naive structure: all announcements for that peer are wiped. for (int txhash = 0; txhash < MAX_TXHASHES; ++txhash) { if (m_announcements[txhash][peer].m_state != State::NOTHING) { m_announcements[txhash][peer].m_state = State::NOTHING; Cleanup(txhash); } } // Call TxRequestTracker's implementation. m_tracker.DisconnectedPeer(peer); } void ForgetTxHash(int txhash) { // Apply to naive structure: all announcements for that txhash are wiped. for (int peer = 0; peer < MAX_PEERS; ++peer) { m_announcements[txhash][peer].m_state = State::NOTHING; } Cleanup(txhash); // Call TxRequestTracker's implementation. m_tracker.ForgetTxHash(TXHASHES[txhash]); } void ReceivedInv(int peer, int txhash, bool is_wtxid, bool preferred, std::chrono::microseconds reqtime) { // Apply to naive structure: if no announcement for txidnum/peer combination // already, create a new CANDIDATE; otherwise do nothing. Announcement& ann = m_announcements[txhash][peer]; if (ann.m_state == State::NOTHING) { ann.m_preferred = preferred; ann.m_state = State::CANDIDATE; ann.m_time = reqtime; ann.m_is_wtxid = is_wtxid; ann.m_sequence = m_current_sequence++; ann.m_priority = m_tracker.ComputePriority(TXHASHES[txhash], peer, ann.m_preferred); // Add event so that AdvanceToEvent can quickly jump to the point where its reqtime passes. if (reqtime > m_now) m_events.push(reqtime); } // Call TxRequestTracker's implementation. m_tracker.ReceivedInv(peer, is_wtxid ? GenTxid::Wtxid(TXHASHES[txhash]) : GenTxid::Txid(TXHASHES[txhash]), preferred, reqtime); } void RequestedTx(int peer, int txhash, std::chrono::microseconds exptime) { // Apply to naive structure: if a CANDIDATE announcement exists for peer/txhash, // convert it to REQUESTED, and change any existing REQUESTED announcement for the same txhash to COMPLETED. if (m_announcements[txhash][peer].m_state == State::CANDIDATE) { for (int peer2 = 0; peer2 < MAX_PEERS; ++peer2) { if (m_announcements[txhash][peer2].m_state == State::REQUESTED) { m_announcements[txhash][peer2].m_state = State::COMPLETED; } } m_announcements[txhash][peer].m_state = State::REQUESTED; m_announcements[txhash][peer].m_time = exptime; } // Add event so that AdvanceToEvent can quickly jump to the point where its exptime passes. if (exptime > m_now) m_events.push(exptime); // Call TxRequestTracker's implementation. m_tracker.RequestedTx(peer, TXHASHES[txhash], exptime); } void ReceivedResponse(int peer, int txhash) { // Apply to naive structure: convert anything to COMPLETED. if (m_announcements[txhash][peer].m_state != State::NOTHING) { m_announcements[txhash][peer].m_state = State::COMPLETED; Cleanup(txhash); } // Call TxRequestTracker's implementation. m_tracker.ReceivedResponse(peer, TXHASHES[txhash]); } void GetRequestable(int peer) { // Implement using naive structure: //! list of (sequence number, txhash, is_wtxid) tuples. std::vector<std::tuple<uint64_t, int, bool>> result; std::vector<std::pair<NodeId, GenTxid>> expected_expired; for (int txhash = 0; txhash < MAX_TXHASHES; ++txhash) { // Mark any expired REQUESTED announcements as COMPLETED. for (int peer2 = 0; peer2 < MAX_PEERS; ++peer2) { Announcement& ann2 = m_announcements[txhash][peer2]; if (ann2.m_state == State::REQUESTED && ann2.m_time <= m_now) { expected_expired.emplace_back(peer2, ann2.m_is_wtxid ? GenTxid::Wtxid(TXHASHES[txhash]) : GenTxid::Txid(TXHASHES[txhash])); ann2.m_state = State::COMPLETED; break; } } // And delete txids with only COMPLETED announcements left. Cleanup(txhash); // CANDIDATEs for which this announcement has the highest priority get returned. const Announcement& ann = m_announcements[txhash][peer]; if (ann.m_state == State::CANDIDATE && GetSelected(txhash) == peer) { result.emplace_back(ann.m_sequence, txhash, ann.m_is_wtxid); } } // Sort the results by sequence number. std::sort(result.begin(), result.end()); std::sort(expected_expired.begin(), expected_expired.end()); // Compare with TxRequestTracker's implementation. std::vector<std::pair<NodeId, GenTxid>> expired; const auto actual = m_tracker.GetRequestable(peer, m_now, &expired); std::sort(expired.begin(), expired.end()); assert(expired == expected_expired); m_tracker.PostGetRequestableSanityCheck(m_now); assert(result.size() == actual.size()); for (size_t pos = 0; pos < actual.size(); ++pos) { assert(TXHASHES[std::get<1>(result[pos])] == actual[pos].GetHash()); assert(std::get<2>(result[pos]) == actual[pos].IsWtxid()); } } void Check() { // Compare CountTracked and CountLoad with naive structure. size_t total = 0; for (int peer = 0; peer < MAX_PEERS; ++peer) { size_t tracked = 0; size_t inflight = 0; size_t candidates = 0; for (int txhash = 0; txhash < MAX_TXHASHES; ++txhash) { tracked += m_announcements[txhash][peer].m_state != State::NOTHING; inflight += m_announcements[txhash][peer].m_state == State::REQUESTED; candidates += m_announcements[txhash][peer].m_state == State::CANDIDATE; } assert(m_tracker.Count(peer) == tracked); assert(m_tracker.CountInFlight(peer) == inflight); assert(m_tracker.CountCandidates(peer) == candidates); total += tracked; } // Compare Size. assert(m_tracker.Size() == total); // Invoke internal consistency check of TxRequestTracker object. m_tracker.SanityCheck(); } }; } // namespace FUZZ_TARGET(txrequest) { // Tester object (which encapsulates a TxRequestTracker). Tester tester; // Decode the input as a sequence of instructions with parameters auto it = buffer.begin(); while (it != buffer.end()) { int cmd = *(it++) % 11; int peer, txidnum, delaynum; switch (cmd) { case 0: // Make time jump to the next event (m_time of CANDIDATE or REQUESTED) tester.AdvanceToEvent(); break; case 1: // Change time delaynum = it == buffer.end() ? 0 : *(it++); tester.AdvanceTime(DELAYS[delaynum]); break; case 2: // Query for requestable txs peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; tester.GetRequestable(peer); break; case 3: // Peer went offline peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; tester.DisconnectedPeer(peer); break; case 4: // No longer need tx txidnum = it == buffer.end() ? 0 : *(it++); tester.ForgetTxHash(txidnum % MAX_TXHASHES); break; case 5: // Received immediate preferred inv case 6: // Same, but non-preferred. peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; txidnum = it == buffer.end() ? 0 : *(it++); tester.ReceivedInv(peer, txidnum % MAX_TXHASHES, (txidnum / MAX_TXHASHES) & 1, cmd & 1, std::chrono::microseconds::min()); break; case 7: // Received delayed preferred inv case 8: // Same, but non-preferred. peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; txidnum = it == buffer.end() ? 0 : *(it++); delaynum = it == buffer.end() ? 0 : *(it++); tester.ReceivedInv(peer, txidnum % MAX_TXHASHES, (txidnum / MAX_TXHASHES) & 1, cmd & 1, tester.Now() + DELAYS[delaynum]); break; case 9: // Requested tx from peer peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; txidnum = it == buffer.end() ? 0 : *(it++); delaynum = it == buffer.end() ? 0 : *(it++); tester.RequestedTx(peer, txidnum % MAX_TXHASHES, tester.Now() + DELAYS[delaynum]); break; case 10: // Received response peer = it == buffer.end() ? 0 : *(it++) % MAX_PEERS; txidnum = it == buffer.end() ? 0 : *(it++); tester.ReceivedResponse(peer, txidnum % MAX_TXHASHES); break; default: assert(false); } } tester.Check(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/merkleblock.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <merkleblock.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <uint256.h> #include <cstdint> #include <optional> #include <string> #include <vector> FUZZ_TARGET(merkleblock) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); CPartialMerkleTree partial_merkle_tree; CallOneOf( fuzzed_data_provider, [&] { const std::optional<CPartialMerkleTree> opt_partial_merkle_tree = ConsumeDeserializable<CPartialMerkleTree>(fuzzed_data_provider); if (opt_partial_merkle_tree) { partial_merkle_tree = *opt_partial_merkle_tree; } }, [&] { CMerkleBlock merkle_block; const std::optional<CBlock> opt_block = ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS); CBloomFilter bloom_filter; std::set<Txid> txids; if (opt_block && !opt_block->vtx.empty()) { if (fuzzed_data_provider.ConsumeBool()) { merkle_block = CMerkleBlock{*opt_block, bloom_filter}; } else if (fuzzed_data_provider.ConsumeBool()) { LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { txids.insert(Txid::FromUint256(ConsumeUInt256(fuzzed_data_provider))); } merkle_block = CMerkleBlock{*opt_block, txids}; } } partial_merkle_tree = merkle_block.txn; }); (void)partial_merkle_tree.GetNumTransactions(); std::vector<uint256> matches; std::vector<unsigned int> indices; (void)partial_merkle_tree.ExtractMatches(matches, indices); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/mini_miner.cpp
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/mempool.h> #include <test/util/script.h> #include <test/util/setup_common.h> #include <test/util/txmempool.h> #include <test/util/mining.h> #include <node/mini_miner.h> #include <node/miner.h> #include <primitives/transaction.h> #include <random.h> #include <txmempool.h> #include <deque> #include <vector> namespace { const TestingSetup* g_setup; std::deque<COutPoint> g_available_coins; void initialize_miner() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); for (uint32_t i = 0; i < uint32_t{100}; ++i) { g_available_coins.emplace_back(Txid::FromUint256(uint256::ZERO), i); } } // Test that the MiniMiner can run with various outpoints and feerates. FUZZ_TARGET(mini_miner, .init = initialize_miner) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; CTxMemPool pool{CTxMemPool::Options{}}; std::vector<COutPoint> outpoints; std::deque<COutPoint> available_coins = g_available_coins; LOCK2(::cs_main, pool.cs); // Cluster size cannot exceed 500 LIMITED_WHILE(!available_coins.empty(), 500) { CMutableTransaction mtx = CMutableTransaction(); const size_t num_inputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, available_coins.size()); const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50); for (size_t n{0}; n < num_inputs; ++n) { auto prevout = available_coins.front(); mtx.vin.emplace_back(prevout, CScript()); available_coins.pop_front(); } for (uint32_t n{0}; n < num_outputs; ++n) { mtx.vout.emplace_back(100, P2WSH_OP_TRUE); } CTransactionRef tx = MakeTransactionRef(mtx); TestMemPoolEntryHelper entry; const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)}; assert(MoneyRange(fee)); pool.addUnchecked(entry.Fee(fee).FromTx(tx)); // All outputs are available to spend for (uint32_t n{0}; n < num_outputs; ++n) { if (fuzzed_data_provider.ConsumeBool()) { available_coins.emplace_back(tx->GetHash(), n); } } if (fuzzed_data_provider.ConsumeBool() && !tx->vout.empty()) { // Add outpoint from this tx (may or not be spent by a later tx) outpoints.emplace_back(tx->GetHash(), (uint32_t)fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, tx->vout.size())); } else { // Add some random outpoint (will be interpreted as confirmed or not yet submitted // to mempool). auto outpoint = ConsumeDeserializable<COutPoint>(fuzzed_data_provider); if (outpoint.has_value() && std::find(outpoints.begin(), outpoints.end(), *outpoint) == outpoints.end()) { outpoints.push_back(*outpoint); } } } const CFeeRate target_feerate{CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/1000)}}; std::optional<CAmount> total_bumpfee; CAmount sum_fees = 0; { node::MiniMiner mini_miner{pool, outpoints}; assert(mini_miner.IsReadyToCalculate()); const auto bump_fees = mini_miner.CalculateBumpFees(target_feerate); for (const auto& outpoint : outpoints) { auto it = bump_fees.find(outpoint); assert(it != bump_fees.end()); assert(it->second >= 0); sum_fees += it->second; } assert(!mini_miner.IsReadyToCalculate()); } { node::MiniMiner mini_miner{pool, outpoints}; assert(mini_miner.IsReadyToCalculate()); total_bumpfee = mini_miner.CalculateTotalBumpFees(target_feerate); assert(total_bumpfee.has_value()); assert(!mini_miner.IsReadyToCalculate()); } // Overlapping ancestry across multiple outpoints can only reduce the total bump fee. assert (sum_fees >= *total_bumpfee); } // Test that MiniMiner and BlockAssembler build the same block given the same transactions and constraints. FUZZ_TARGET(mini_miner_selection, .init = initialize_miner) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; CTxMemPool pool{CTxMemPool::Options{}}; // Make a copy to preserve determinism. std::deque<COutPoint> available_coins = g_available_coins; std::vector<CTransactionRef> transactions; LOCK2(::cs_main, pool.cs); LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100) { CMutableTransaction mtx = CMutableTransaction(); assert(!available_coins.empty()); const size_t num_inputs = std::min(size_t{2}, available_coins.size()); const size_t num_outputs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(2, 5); for (size_t n{0}; n < num_inputs; ++n) { auto prevout = available_coins.at(0); mtx.vin.emplace_back(prevout, CScript()); available_coins.pop_front(); } for (uint32_t n{0}; n < num_outputs; ++n) { mtx.vout.emplace_back(100, P2WSH_OP_TRUE); } CTransactionRef tx = MakeTransactionRef(mtx); // First 2 outputs are available to spend. The rest are added to outpoints to calculate bumpfees. // There is no overlap between spendable coins and outpoints passed to MiniMiner because the // MiniMiner interprets spent coins as to-be-replaced and excludes them. for (uint32_t n{0}; n < num_outputs - 1; ++n) { if (fuzzed_data_provider.ConsumeBool()) { available_coins.emplace_front(tx->GetHash(), n); } else { available_coins.emplace_back(tx->GetHash(), n); } } // Stop if pool reaches DEFAULT_BLOCK_MAX_WEIGHT because BlockAssembler will stop when the // block template reaches that, but the MiniMiner will keep going. if (pool.GetTotalTxSize() + GetVirtualTransactionSize(*tx) >= DEFAULT_BLOCK_MAX_WEIGHT) break; TestMemPoolEntryHelper entry; const CAmount fee{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)}; assert(MoneyRange(fee)); pool.addUnchecked(entry.Fee(fee).FromTx(tx)); transactions.push_back(tx); } std::vector<COutPoint> outpoints; for (const auto& coin : g_available_coins) { if (!pool.GetConflictTx(coin)) outpoints.push_back(coin); } for (const auto& tx : transactions) { assert(pool.exists(GenTxid::Txid(tx->GetHash()))); for (uint32_t n{0}; n < tx->vout.size(); ++n) { COutPoint coin{tx->GetHash(), n}; if (!pool.GetConflictTx(coin)) outpoints.push_back(coin); } } const CFeeRate target_feerate{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY/100000)}; node::BlockAssembler::Options miner_options; miner_options.blockMinFeeRate = target_feerate; miner_options.nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT; miner_options.test_block_validity = false; node::BlockAssembler miner{g_setup->m_node.chainman->ActiveChainstate(), &pool, miner_options}; node::MiniMiner mini_miner{pool, outpoints}; assert(mini_miner.IsReadyToCalculate()); CScript spk_placeholder = CScript() << OP_0; // Use BlockAssembler as oracle. BlockAssembler and MiniMiner should select the same // transactions, stopping once packages do not meet target_feerate. const auto blocktemplate{miner.CreateNewBlock(spk_placeholder)}; mini_miner.BuildMockTemplate(target_feerate); assert(!mini_miner.IsReadyToCalculate()); auto mock_template_txids = mini_miner.GetMockTemplateTxids(); // MiniMiner doesn't add a coinbase tx. assert(mock_template_txids.count(blocktemplate->block.vtx[0]->GetHash()) == 0); mock_template_txids.emplace(blocktemplate->block.vtx[0]->GetHash()); assert(mock_template_txids.size() <= blocktemplate->block.vtx.size()); assert(mock_template_txids.size() >= blocktemplate->block.vtx.size()); assert(mock_template_txids.size() == blocktemplate->block.vtx.size()); for (const auto& tx : blocktemplate->block.vtx) { assert(mock_template_txids.count(tx->GetHash())); } } } // namespace
0
bitcoin/src/test
bitcoin/src/test/fuzz/eval_script.cpp
// Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <pubkey.h> #include <script/interpreter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <limits> FUZZ_TARGET(eval_script) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const unsigned int flags = fuzzed_data_provider.ConsumeIntegral<unsigned int>(); const std::vector<uint8_t> script_bytes = [&] { if (fuzzed_data_provider.remaining_bytes() != 0) { return fuzzed_data_provider.ConsumeRemainingBytes<uint8_t>(); } else { // Avoid UBSan warning: // test/fuzz/FuzzedDataProvider.h:212:17: runtime error: null pointer passed as argument 1, which is declared to never be null // /usr/include/string.h:43:28: note: nonnull attribute specified here return std::vector<uint8_t>(); } }(); const CScript script(script_bytes.begin(), script_bytes.end()); for (const auto sig_version : {SigVersion::BASE, SigVersion::WITNESS_V0}) { std::vector<std::vector<unsigned char>> stack; (void)EvalScript(stack, script, flags, BaseSignatureChecker(), sig_version, nullptr); } }
0
bitcoin/src/test
bitcoin/src/test/fuzz/http_request.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <httpserver.h> #include <netaddress.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/signalinterrupt.h> #include <util/strencodings.h> #include <event2/buffer.h> #include <event2/event.h> #include <event2/http.h> #include <event2/http_struct.h> #include <cassert> #include <cstdint> #include <string> #include <vector> extern "C" int evhttp_parse_firstline_(struct evhttp_request*, struct evbuffer*); extern "C" int evhttp_parse_headers_(struct evhttp_request*, struct evbuffer*); std::string RequestMethodString(HTTPRequest::RequestMethod m); FUZZ_TARGET(http_request) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; evhttp_request* evreq = evhttp_request_new(nullptr, nullptr); assert(evreq != nullptr); evreq->kind = EVHTTP_REQUEST; evbuffer* evbuf = evbuffer_new(); assert(evbuf != nullptr); const std::vector<uint8_t> http_buffer = ConsumeRandomLengthByteVector(fuzzed_data_provider, 4096); evbuffer_add(evbuf, http_buffer.data(), http_buffer.size()); // Avoid constructing requests that will be interpreted by libevent as PROXY requests to avoid triggering // a nullptr dereference. The dereference (req->evcon->http_server) takes place in evhttp_parse_request_line // and is a consequence of our hacky but necessary use of the internal function evhttp_parse_firstline_ in // this fuzzing harness. The workaround is not aesthetically pleasing, but it successfully avoids the troublesome // code path. " http:// HTTP/1.1\n" was a crashing input prior to this workaround. const std::string http_buffer_str = ToLower(std::string{http_buffer.begin(), http_buffer.end()}); if (http_buffer_str.find(" http://") != std::string::npos || http_buffer_str.find(" https://") != std::string::npos || evhttp_parse_firstline_(evreq, evbuf) != 1 || evhttp_parse_headers_(evreq, evbuf) != 1) { evbuffer_free(evbuf); evhttp_request_free(evreq); return; } util::SignalInterrupt interrupt; HTTPRequest http_request{evreq, interrupt, true}; const HTTPRequest::RequestMethod request_method = http_request.GetRequestMethod(); (void)RequestMethodString(request_method); (void)http_request.GetURI(); (void)http_request.GetHeader("Host"); const std::string header = fuzzed_data_provider.ConsumeRandomLengthString(16); (void)http_request.GetHeader(header); (void)http_request.WriteHeader(header, fuzzed_data_provider.ConsumeRandomLengthString(16)); (void)http_request.GetHeader(header); const std::string body = http_request.ReadBody(); assert(body.empty()); const CService service = http_request.GetPeer(); assert(service.ToStringAddrPort() == "[::]:0"); evbuffer_free(evbuf); evhttp_request_free(evreq); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/net.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <net.h> #include <net_permissions.h> #include <netaddress.h> #include <protocol.h> #include <random.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/net.h> #include <test/util/net.h> #include <test/util/setup_common.h> #include <util/asmap.h> #include <util/chaintype.h> #include <cstdint> #include <optional> #include <string> #include <vector> void initialize_net() { static const auto testing_setup = MakeNoLogFileContext<>(ChainType::MAIN); } FUZZ_TARGET(net, .init = initialize_net) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); SetMockTime(ConsumeTime(fuzzed_data_provider)); CNode node{ConsumeNode(fuzzed_data_provider)}; node.SetCommonVersion(fuzzed_data_provider.ConsumeIntegral<int>()); LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { CallOneOf( fuzzed_data_provider, [&] { node.CloseSocketDisconnect(); }, [&] { CNodeStats stats; node.CopyStats(stats); }, [&] { const CNode* add_ref_node = node.AddRef(); assert(add_ref_node == &node); }, [&] { if (node.GetRefCount() > 0) { node.Release(); } }, [&] { const std::optional<CService> service_opt = ConsumeDeserializable<CService>(fuzzed_data_provider, ConsumeDeserializationParams<CNetAddr::SerParams>(fuzzed_data_provider)); if (!service_opt) { return; } node.SetAddrLocal(*service_opt); }, [&] { const std::vector<uint8_t> b = ConsumeRandomLengthByteVector(fuzzed_data_provider); bool complete; node.ReceiveMsgBytes(b, complete); }); } (void)node.GetAddrLocal(); (void)node.GetId(); (void)node.GetLocalNonce(); const int ref_count = node.GetRefCount(); assert(ref_count >= 0); (void)node.GetCommonVersion(); const NetPermissionFlags net_permission_flags = ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS); (void)node.HasPermission(net_permission_flags); (void)node.ConnectedThroughNetwork(); }
0
bitcoin/src/test
bitcoin/src/test/fuzz/cuckoocache.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <cuckoocache.h> #include <script/sigcache.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <cstdint> #include <string> #include <vector> namespace { FuzzedDataProvider* fuzzed_data_provider_ptr = nullptr; struct RandomHasher { template <uint8_t> uint32_t operator()(const bool& /* unused */) const { assert(fuzzed_data_provider_ptr != nullptr); return fuzzed_data_provider_ptr->ConsumeIntegral<uint32_t>(); } }; } // namespace FUZZ_TARGET(cuckoocache) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); fuzzed_data_provider_ptr = &fuzzed_data_provider; CuckooCache::cache<int, RandomHasher> cuckoo_cache{}; if (fuzzed_data_provider.ConsumeBool()) { const size_t megabytes = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 16); cuckoo_cache.setup_bytes(megabytes << 20); } else { cuckoo_cache.setup(fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, 4096)); } LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { if (fuzzed_data_provider.ConsumeBool()) { cuckoo_cache.insert(fuzzed_data_provider.ConsumeBool()); } else { cuckoo_cache.contains(fuzzed_data_provider.ConsumeBool(), fuzzed_data_provider.ConsumeBool()); } } fuzzed_data_provider_ptr = nullptr; }
0
bitcoin/src/test
bitcoin/src/test/fuzz/node_eviction.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <net.h> #include <protocol.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/net.h> #include <algorithm> #include <cassert> #include <cstdint> #include <optional> #include <vector> FUZZ_TARGET(node_eviction) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; std::vector<NodeEvictionCandidate> eviction_candidates; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { eviction_candidates.push_back({ /*id=*/fuzzed_data_provider.ConsumeIntegral<NodeId>(), /*m_connected=*/std::chrono::seconds{fuzzed_data_provider.ConsumeIntegral<int64_t>()}, /*m_min_ping_time=*/std::chrono::microseconds{fuzzed_data_provider.ConsumeIntegral<int64_t>()}, /*m_last_block_time=*/std::chrono::seconds{fuzzed_data_provider.ConsumeIntegral<int64_t>()}, /*m_last_tx_time=*/std::chrono::seconds{fuzzed_data_provider.ConsumeIntegral<int64_t>()}, /*fRelevantServices=*/fuzzed_data_provider.ConsumeBool(), /*m_relay_txs=*/fuzzed_data_provider.ConsumeBool(), /*fBloomFilter=*/fuzzed_data_provider.ConsumeBool(), /*nKeyedNetGroup=*/fuzzed_data_provider.ConsumeIntegral<uint64_t>(), /*prefer_evict=*/fuzzed_data_provider.ConsumeBool(), /*m_is_local=*/fuzzed_data_provider.ConsumeBool(), /*m_network=*/fuzzed_data_provider.PickValueInArray(ALL_NETWORKS), /*m_noban=*/fuzzed_data_provider.ConsumeBool(), /*m_conn_type=*/fuzzed_data_provider.PickValueInArray(ALL_CONNECTION_TYPES), }); } // Make a copy since eviction_candidates may be in some valid but otherwise // indeterminate state after the SelectNodeToEvict(&&) call. const std::vector<NodeEvictionCandidate> eviction_candidates_copy = eviction_candidates; const std::optional<NodeId> node_to_evict = SelectNodeToEvict(std::move(eviction_candidates)); if (node_to_evict) { assert(std::any_of(eviction_candidates_copy.begin(), eviction_candidates_copy.end(), [&node_to_evict](const NodeEvictionCandidate& eviction_candidate) { return *node_to_evict == eviction_candidate.id; })); } }
0