Merge bitcoin/bitcoin#31486: fuzz: Abort when using global PRNG without re-seed

fae63bf130 fuzz: Clarify that only SeedRandomStateForTest(SeedRand::ZEROS) is allowed (MarcoFalke)
fa18acb457 fuzz: Abort when using global PRNG without re-seed (MarcoFalke)
fa7809aeab fuzz: Add missing SeedRandomStateForTest(SeedRand::ZEROS) (MarcoFalke)

Pull request description:

  This is the first step toward improving fuzz stability and determinism (https://github.com/bitcoin/bitcoin/issues/29018).

  A fuzz target using the global test-only PRNG will now abort if the seed is re-used across fuzz inputs.

  Also, temporarily add `SeedRandomStateForTest(SeedRand::ZEROS)` to all affected fuzz targets. This may slow down the libfuzzer leak detector, but it will disable itself after some time, or it can be disabled explicitly with `-detect_leaks=0`.

  In a follow-up, each affected fuzz target can be stripped of the global random use and a local `RandomMixin` (or similar) can be added instead.

  (Can be tested by removing any one of the re-seed calls and observing a fuzz abort)

ACKs for top commit:
  hodlinator:
    ACK fae63bf130
  dergoegge:
    utACK fae63bf130
  marcofleon:
    Tested ACK fae63bf130

Tree-SHA512: 4a0db69af7f715408edf4f8b08b44f34ce12ee2c79d33b336ad19a6e6bd079c4ff7c971af0a3efa428213407c1171f4e2837ec6a2577086c2f94cd15618a0892
This commit is contained in:
Ryan Ofsky 2024-12-17 12:33:41 -05:00
commit a60d5702fd
No known key found for this signature in database
GPG key ID: 46800E30FC748A66
39 changed files with 131 additions and 7 deletions

View file

@ -671,9 +671,11 @@ void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept
{ {
GetRNGState().MakeDeterministic(seed); GetRNGState().MakeDeterministic(seed);
} }
std::atomic<bool> g_used_g_prng{false}; // Only accessed from tests
void GetRandBytes(Span<unsigned char> bytes) noexcept void GetRandBytes(Span<unsigned char> bytes) noexcept
{ {
g_used_g_prng = true;
ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST, /*always_use_real_rng=*/false); ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST, /*always_use_real_rng=*/false);
} }

View file

@ -41,6 +41,7 @@ void initialize_addrman()
FUZZ_TARGET(data_stream_addr_man, .init = initialize_addrman) FUZZ_TARGET(data_stream_addr_man, .init = initialize_addrman)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
DataStream data_stream = ConsumeDataStream(fuzzed_data_provider); DataStream data_stream = ConsumeDataStream(fuzzed_data_provider);
NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)}; NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
@ -113,6 +114,7 @@ void FillAddrman(AddrMan& addrman, FuzzedDataProvider& fuzzed_data_provider)
FUZZ_TARGET(addrman, .init = initialize_addrman) FUZZ_TARGET(addrman, .init = initialize_addrman)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));
NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)}; NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
@ -197,6 +199,7 @@ FUZZ_TARGET(addrman, .init = initialize_addrman)
// Check that serialize followed by unserialize produces the same addrman. // Check that serialize followed by unserialize produces the same addrman.
FUZZ_TARGET(addrman_serdeser, .init = initialize_addrman) FUZZ_TARGET(addrman_serdeser, .init = initialize_addrman)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));

View file

@ -42,6 +42,7 @@ static bool operator==(const CBanEntry& lhs, const CBanEntry& rhs)
FUZZ_TARGET(banman, .init = initialize_banman) FUZZ_TARGET(banman, .init = initialize_banman)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));
fs::path banlist_file = gArgs.GetDataDirNet() / "fuzzed_banlist"; fs::path banlist_file = gArgs.GetDataDirNet() / "fuzzed_banlist";

View file

@ -6,6 +6,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h> #include <test/fuzz/util.h>
#include <test/util/random.h>
#include <cstdint> #include <cstdint>
#include <optional> #include <optional>
@ -14,6 +15,7 @@
FUZZ_TARGET(blockfilter) FUZZ_TARGET(blockfilter)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::optional<BlockFilter> block_filter = ConsumeDeserializable<BlockFilter>(fuzzed_data_provider); const std::optional<BlockFilter> block_filter = ConsumeDeserializable<BlockFilter>(fuzzed_data_provider);
if (!block_filter) { if (!block_filter) {

View file

@ -36,6 +36,7 @@ void initialize_connman()
FUZZ_TARGET(connman, .init = initialize_connman) FUZZ_TARGET(connman, .init = initialize_connman)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));
auto netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)}; auto netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};

View file

@ -6,6 +6,7 @@
#include <netaddress.h> #include <netaddress.h>
#include <netbase.h> #include <netbase.h>
#include <test/fuzz/util/check_globals.h>
#include <test/util/random.h> #include <test/util/random.h>
#include <test/util/setup_common.h> #include <test/util/setup_common.h>
#include <util/check.h> #include <util/check.h>
@ -78,6 +79,12 @@ void FuzzFrameworkRegisterTarget(std::string_view name, TypeTestOneInput target,
static std::string_view g_fuzz_target; static std::string_view g_fuzz_target;
static const TypeTestOneInput* g_test_one_input{nullptr}; static const TypeTestOneInput* g_test_one_input{nullptr};
inline void test_one_input(FuzzBufferType buffer)
{
CheckGlobals check{};
(*Assert(g_test_one_input))(buffer);
}
const std::function<std::string()> G_TEST_GET_FULL_NAME{[]{ const std::function<std::string()> G_TEST_GET_FULL_NAME{[]{
return std::string{g_fuzz_target}; return std::string{g_fuzz_target};
}}; }};
@ -210,7 +217,6 @@ void signal_handler(int signal)
// This function is used by libFuzzer // This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{ {
static const auto& test_one_input = *Assert(g_test_one_input);
test_one_input({data, size}); test_one_input({data, size});
return 0; return 0;
} }
@ -227,7 +233,6 @@ extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
initialize(); initialize();
static const auto& test_one_input = *Assert(g_test_one_input);
#ifdef __AFL_LOOP #ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++. // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details. // See fuzzing.md for details.

View file

@ -8,6 +8,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h> #include <test/fuzz/util.h>
#include <test/util/random.h>
#include <util/bytevectorhash.h> #include <util/bytevectorhash.h>
#include <util/golombrice.h> #include <util/golombrice.h>
@ -42,6 +43,7 @@ std::vector<uint64_t> BuildHashedSet(const std::unordered_set<std::vector<uint8_
FUZZ_TARGET(golomb_rice) FUZZ_TARGET(golomb_rice)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
std::vector<uint8_t> golomb_rice_data; std::vector<uint8_t> golomb_rice_data;
std::vector<uint64_t> encoded_deltas; std::vector<uint64_t> encoded_deltas;

View file

@ -48,6 +48,7 @@ public:
FUZZ_TARGET(headers_sync_state, .init = initialize_headers_sync_state_fuzz) FUZZ_TARGET(headers_sync_state, .init = initialize_headers_sync_state_fuzz)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
auto mock_time{ConsumeTime(fuzzed_data_provider)}; auto mock_time{ConsumeTime(fuzzed_data_provider)};

View file

@ -21,6 +21,7 @@ void initialize_i2p()
FUZZ_TARGET(i2p, .init = initialize_i2p) FUZZ_TARGET(i2p, .init = initialize_i2p)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));

View file

@ -18,6 +18,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h> #include <test/fuzz/util.h>
#include <test/util/random.h>
#include <util/chaintype.h> #include <util/chaintype.h>
#include <util/strencodings.h> #include <util/strencodings.h>
@ -38,6 +39,7 @@ void initialize_key()
FUZZ_TARGET(key, .init = initialize_key) FUZZ_TARGET(key, .init = initialize_key)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
const CKey key = [&] { const CKey key = [&] {
CKey k; CKey k;
k.Set(buffer.begin(), buffer.end(), true); k.Set(buffer.begin(), buffer.end(), true);

View file

@ -34,6 +34,7 @@ void initialize_miner()
// Test that the MiniMiner can run with various outpoints and feerates. // Test that the MiniMiner can run with various outpoints and feerates.
FUZZ_TARGET(mini_miner, .init = initialize_miner) FUZZ_TARGET(mini_miner, .init = initialize_miner)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
bilingual_str error; bilingual_str error;
CTxMemPool pool{CTxMemPool::Options{}, error}; CTxMemPool pool{CTxMemPool::Options{}, error};
@ -112,6 +113,7 @@ FUZZ_TARGET(mini_miner, .init = initialize_miner)
// Test that MiniMiner and BlockAssembler build the same block given the same transactions and constraints. // Test that MiniMiner and BlockAssembler build the same block given the same transactions and constraints.
FUZZ_TARGET(mini_miner_selection, .init = initialize_miner) FUZZ_TARGET(mini_miner_selection, .init = initialize_miner)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
bilingual_str error; bilingual_str error;
CTxMemPool pool{CTxMemPool::Options{}, error}; CTxMemPool pool{CTxMemPool::Options{}, error};

View file

@ -6,6 +6,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util/net.h> #include <test/fuzz/util/net.h>
#include <test/util/random.h>
#include <cassert> #include <cassert>
#include <cstdint> #include <cstdint>
@ -13,6 +14,7 @@
FUZZ_TARGET(netaddress) FUZZ_TARGET(netaddress)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider);

View file

@ -39,6 +39,7 @@ void initialize()
FUZZ_TARGET(p2p_handshake, .init = ::initialize) FUZZ_TARGET(p2p_handshake, .init = ::initialize)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*g_setup->m_node.connman); ConnmanTestMsg& connman = static_cast<ConnmanTestMsg&>(*g_setup->m_node.connman);

View file

@ -153,6 +153,7 @@ void initialize()
FUZZ_TARGET(p2p_headers_presync, .init = initialize) FUZZ_TARGET(p2p_headers_presync, .init = initialize)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
ChainstateManager& chainman = *g_testing_setup->m_node.chainman; ChainstateManager& chainman = *g_testing_setup->m_node.chainman;
LOCK(NetEventsInterface::g_msgproc_mutex); LOCK(NetEventsInterface::g_msgproc_mutex);

View file

@ -192,6 +192,7 @@ std::optional<COutPoint> GetChildEvictingPrevout(const CTxMemPool& tx_pool)
FUZZ_TARGET(ephemeral_package_eval, .init = initialize_tx_pool) FUZZ_TARGET(ephemeral_package_eval, .init = initialize_tx_pool)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node; const auto& node = g_setup->m_node;
auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())}; auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
@ -346,6 +347,7 @@ FUZZ_TARGET(ephemeral_package_eval, .init = initialize_tx_pool)
FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool) FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node; const auto& node = g_setup->m_node;
auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())}; auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};

View file

@ -44,6 +44,7 @@ PartiallyDownloadedBlock::CheckBlockFn FuzzedCheckBlock(std::optional<BlockValid
FUZZ_TARGET(partially_downloaded_block, .init = initialize_pdb) FUZZ_TARGET(partially_downloaded_block, .init = initialize_pdb)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
auto block{ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS)}; auto block{ConsumeDeserializable<CBlock>(fuzzed_data_provider, TX_WITH_WITNESS)};

View file

@ -52,6 +52,7 @@ void initialize_process_message()
FUZZ_TARGET(process_message, .init = initialize_process_message) FUZZ_TARGET(process_message, .init = initialize_process_message)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
ConnmanTestMsg& connman = *static_cast<ConnmanTestMsg*>(g_setup->m_node.connman.get()); ConnmanTestMsg& connman = *static_cast<ConnmanTestMsg*>(g_setup->m_node.connman.get());

View file

@ -42,6 +42,7 @@ void initialize_process_messages()
FUZZ_TARGET(process_messages, .init = initialize_process_messages) FUZZ_TARGET(process_messages, .init = initialize_process_messages)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
ConnmanTestMsg& connman = *static_cast<ConnmanTestMsg*>(g_setup->m_node.connman.get()); ConnmanTestMsg& connman = *static_cast<ConnmanTestMsg*>(g_setup->m_node.connman.get());

View file

@ -2,14 +2,14 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // 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 <node/psbt.h>
#include <psbt.h> #include <psbt.h>
#include <pubkey.h> #include <pubkey.h>
#include <script/script.h> #include <script/script.h>
#include <streams.h> #include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/util/random.h>
#include <util/check.h> #include <util/check.h>
#include <cstdint> #include <cstdint>
@ -23,6 +23,7 @@ using node::PSBTInputAnalysis;
FUZZ_TARGET(psbt) FUZZ_TARGET(psbt)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
PartiallySignedTransaction psbt_mut; PartiallySignedTransaction psbt_mut;
std::string error; std::string error;

View file

@ -51,6 +51,7 @@ void initialize_package_rbf()
FUZZ_TARGET(rbf, .init = initialize_rbf) FUZZ_TARGET(rbf, .init = initialize_rbf)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));
std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS); std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
@ -92,6 +93,7 @@ FUZZ_TARGET(rbf, .init = initialize_rbf)
FUZZ_TARGET(package_rbf, .init = initialize_package_rbf) FUZZ_TARGET(package_rbf, .init = initialize_package_rbf)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));

View file

@ -6,6 +6,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h> #include <test/fuzz/util.h>
#include <test/util/random.h>
#include <uint256.h> #include <uint256.h>
#include <cassert> #include <cassert>
@ -16,6 +17,7 @@
FUZZ_TARGET(rolling_bloom_filter) FUZZ_TARGET(rolling_bloom_filter)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
CRollingBloomFilter rolling_bloom_filter{ CRollingBloomFilter rolling_bloom_filter{

View file

@ -365,6 +365,7 @@ void initialize_rpc()
FUZZ_TARGET(rpc, .init = initialize_rpc) FUZZ_TARGET(rpc, .init = initialize_rpc)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
bool good_data{true}; bool good_data{true};
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));

View file

@ -25,6 +25,7 @@ void initialize_script_sigcache()
FUZZ_TARGET(script_sigcache, .init = initialize_script_sigcache) FUZZ_TARGET(script_sigcache, .init = initialize_script_sigcache)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto max_sigcache_bytes{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, DEFAULT_SIGNATURE_CACHE_BYTES)}; const auto max_sigcache_bytes{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, DEFAULT_SIGNATURE_CACHE_BYTES)};

View file

@ -7,6 +7,7 @@
#include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h> #include <test/fuzz/util.h>
#include <test/util/random.h>
#include <cstdint> #include <cstdint>
#include <vector> #include <vector>
@ -16,6 +17,7 @@ int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned
FUZZ_TARGET(secp256k1_ecdsa_signature_parse_der_lax) FUZZ_TARGET(secp256k1_ecdsa_signature_parse_der_lax)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
const std::vector<uint8_t> signature_bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider); const std::vector<uint8_t> signature_bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
if (signature_bytes.data() == nullptr) { if (signature_bytes.data() == nullptr) {

View file

@ -14,6 +14,7 @@
#include <primitives/transaction.h> #include <primitives/transaction.h>
#include <streams.h> #include <streams.h>
#include <test/fuzz/fuzz.h> #include <test/fuzz/fuzz.h>
#include <test/util/random.h>
#include <univalue.h> #include <univalue.h>
#include <util/chaintype.h> #include <util/chaintype.h>
#include <util/rbf.h> #include <util/rbf.h>
@ -28,6 +29,7 @@ void initialize_transaction()
FUZZ_TARGET(transaction, .init = initialize_transaction) FUZZ_TARGET(transaction, .init = initialize_transaction)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
DataStream ds{buffer}; DataStream ds{buffer};
bool valid_tx = true; bool valid_tx = true;
const CTransaction tx = [&] { const CTransaction tx = [&] {

View file

@ -190,6 +190,7 @@ void CheckATMPInvariants(const MempoolAcceptResult& res, bool txid_in_mempool, b
FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool) FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node; const auto& node = g_setup->m_node;
auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())}; auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
@ -368,6 +369,7 @@ FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
FUZZ_TARGET(tx_pool, .init = initialize_tx_pool) FUZZ_TARGET(tx_pool, .init = initialize_tx_pool)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node; const auto& node = g_setup->m_node;
auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())}; auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};

View file

@ -165,6 +165,7 @@ void CheckPackageToValidate(const node::PackageToValidate& package_to_validate,
FUZZ_TARGET(txdownloadman, .init = initialize) FUZZ_TARGET(txdownloadman, .init = initialize)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
// Initialize txdownloadman // Initialize txdownloadman
@ -294,6 +295,7 @@ static void CheckInvariants(const node::TxDownloadManagerImpl& txdownload_impl,
FUZZ_TARGET(txdownloadman_impl, .init = initialize) FUZZ_TARGET(txdownloadman_impl, .init = initialize)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
// Initialize a TxDownloadManagerImpl // Initialize a TxDownloadManagerImpl

View file

@ -3,6 +3,7 @@
# file COPYING or https://opensource.org/license/mit/. # file COPYING or https://opensource.org/license/mit/.
add_library(test_fuzz STATIC EXCLUDE_FROM_ALL add_library(test_fuzz STATIC EXCLUDE_FROM_ALL
check_globals.cpp
descriptor.cpp descriptor.cpp
mempool.cpp mempool.cpp
net.cpp net.cpp

View file

@ -0,0 +1,41 @@
// Copyright (c) 2024-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 <test/fuzz/util/check_globals.h>
#include <test/util/random.h>
#include <iostream>
#include <memory>
#include <optional>
#include <string>
struct CheckGlobalsImpl {
CheckGlobalsImpl()
{
g_used_g_prng = false;
g_seeded_g_prng_zero = false;
}
~CheckGlobalsImpl()
{
if (g_used_g_prng && !g_seeded_g_prng_zero) {
std::cerr << "\n\n"
"The current fuzz target used the global random state.\n\n"
"This is acceptable, but requires the fuzz target to call \n"
"SeedRandomStateForTest(SeedRand::ZEROS) at the beginning \n"
"of processing the fuzz input.\n\n"
"An alternative solution would be to avoid any use of globals.\n\n"
"Without a solution, fuzz stability and determinism can lead \n"
"to non-reproducible bugs or inefficient fuzzing.\n\n"
<< std::endl;
std::abort(); // Abort, because AFL may try to recover from a std::exit
}
}
};
CheckGlobals::CheckGlobals() : m_impl(std::make_unique<CheckGlobalsImpl>()) {}
CheckGlobals::~CheckGlobals() = default;

View file

@ -0,0 +1,19 @@
// Copyright (c) 2024-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.
#ifndef BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H
#define BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H
#include <memory>
#include <optional>
#include <string>
struct CheckGlobalsImpl;
struct CheckGlobals {
CheckGlobals();
~CheckGlobals();
std::unique_ptr<CheckGlobalsImpl> m_impl;
};
#endif // BITCOIN_TEST_FUZZ_UTIL_CHECK_GLOBALS_H

View file

@ -70,6 +70,7 @@ void initialize_chain()
template <bool INVALID> template <bool INVALID>
void utxo_snapshot_fuzz(FuzzBufferType buffer) void utxo_snapshot_fuzz(FuzzBufferType buffer)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
auto& setup{*g_setup}; auto& setup{*g_setup};
bool dirty_chainman{false}; // Re-use the global chainman, but reset it when it is dirty bool dirty_chainman{false}; // Re-use the global chainman, but reset it when it is dirty

View file

@ -28,6 +28,7 @@ FUZZ_TARGET(utxo_total_supply)
.extra_args = {"-testactivationheight=bip34@2"}, .extra_args = {"-testactivationheight=bip34@2"},
}, },
}; };
SeedRandomStateForTest(SeedRand::ZEROS); // Can not be done before test_setup
// Create chainstate // Create chainstate
test_setup.LoadVerifyActivateChainstate(); test_setup.LoadVerifyActivateChainstate();
auto& node{test_setup.m_node}; auto& node{test_setup.m_node};

View file

@ -38,6 +38,7 @@ void initialize_validation_load_mempool()
FUZZ_TARGET(validation_load_mempool, .init = initialize_validation_load_mempool) FUZZ_TARGET(validation_load_mempool, .init = initialize_validation_load_mempool)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider)); SetMockTime(ConsumeTime(fuzzed_data_provider));
FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider}; FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider};

View file

@ -12,6 +12,8 @@
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
std::atomic<bool> g_seeded_g_prng_zero{false};
extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept; extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept;
void SeedRandomStateForTest(SeedRand seedtype) void SeedRandomStateForTest(SeedRand seedtype)
@ -36,6 +38,10 @@ void SeedRandomStateForTest(SeedRand seedtype)
return GetRandHash(); return GetRandHash();
}(); }();
g_seeded_g_prng_zero = seedtype == SeedRand::ZEROS;
if constexpr (G_FUZZING) {
Assert(g_seeded_g_prng_zero); // Only SeedRandomStateForTest(SeedRand::ZEROS) is allowed in fuzz tests
}
const uint256& seed{seedtype == SeedRand::FIXED_SEED ? ctx_seed : uint256::ZERO}; const uint256& seed{seedtype == SeedRand::FIXED_SEED ? ctx_seed : uint256::ZERO};
LogInfo("Setting random seed for current tests to %s=%s\n", RANDOM_CTX_SEED, seed.GetHex()); LogInfo("Setting random seed for current tests to %s=%s\n", RANDOM_CTX_SEED, seed.GetHex());
MakeRandDeterministicDANGEROUS(seed); MakeRandDeterministicDANGEROUS(seed);

View file

@ -9,6 +9,7 @@
#include <random.h> #include <random.h>
#include <uint256.h> #include <uint256.h>
#include <atomic>
#include <cstdint> #include <cstdint>
enum class SeedRand { enum class SeedRand {
@ -27,6 +28,9 @@ enum class SeedRand {
/** Seed the global RNG state for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */ /** Seed the global RNG state for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */
void SeedRandomStateForTest(SeedRand seed); void SeedRandomStateForTest(SeedRand seed);
extern std::atomic<bool> g_seeded_g_prng_zero;
extern std::atomic<bool> g_used_g_prng;
template <RandomNumberGenerator Rng> template <RandomNumberGenerator Rng>
inline CAmount RandMoney(Rng&& rng) inline CAmount RandMoney(Rng&& rng)
{ {

View file

@ -108,6 +108,9 @@ static void ExitFailure(std::string_view str_err)
BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts) BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts)
: m_args{} : m_args{}
{ {
if constexpr (!G_FUZZING) {
SeedRandomForTest(SeedRand::FIXED_SEED);
}
m_node.shutdown_signal = &m_interrupt; m_node.shutdown_signal = &m_interrupt;
m_node.shutdown_request = [this]{ return m_interrupt(); }; m_node.shutdown_request = [this]{ return m_interrupt(); };
m_node.args = &gArgs; m_node.args = &gArgs;
@ -139,8 +142,6 @@ BasicTestingSetup::BasicTestingSetup(const ChainType chainType, TestOpts opts)
} }
} }
SeedRandomForTest(SeedRand::FIXED_SEED);
const std::string test_name{G_TEST_GET_FULL_NAME ? G_TEST_GET_FULL_NAME() : ""}; const std::string test_name{G_TEST_GET_FULL_NAME ? G_TEST_GET_FULL_NAME() : ""};
if (!m_node.args->IsArgSet("-testdatadir")) { if (!m_node.args->IsArgSet("-testdatadir")) {
// To avoid colliding with a leftover prior datadir, and to allow // To avoid colliding with a leftover prior datadir, and to allow

View file

@ -218,6 +218,7 @@ FUZZ_TARGET(coin_grinder_is_optimal)
FUZZ_TARGET(coinselection) FUZZ_TARGET(coinselection)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
std::vector<COutput> utxo_pool; std::vector<COutput> utxo_pool;

View file

@ -56,6 +56,7 @@ void initialize_setup()
FUZZ_TARGET(wallet_notifications, .init = initialize_setup) FUZZ_TARGET(wallet_notifications, .init = initialize_setup)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
// The total amount, to be distributed to the wallets a and b in txs // The total amount, to be distributed to the wallets a and b in txs
// without fee. Thus, the balance of the wallets should always equal the // without fee. Thus, the balance of the wallets should always equal the

View file

@ -85,6 +85,7 @@ static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc
FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm) FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm)
{ {
SeedRandomStateForTest(SeedRand::ZEROS);
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
const auto& node{g_setup->m_node}; const auto& node{g_setup->m_node};
Chainstate& chainstate{node.chainman->ActiveChainstate()}; Chainstate& chainstate{node.chainman->ActiveChainstate()};