mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:38:38 +00:00
fuzz: add corpus reachability checks #36098
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36098
Loading…
Reference in a new issue
No description provided.
Delete branch "fuzz-reachability-goals"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This is a follow-up to #35482.
Add
ReachabilityGoal()to aggregate whether selected conditions are reached across all inputs processed by a fuzz target. Goals are identified by source location and reported at shutdown. SettingFUZZ_ENFORCE_REACHABILITY=1makes the process fail if any registered goal was not reached.Add goals for selected high-value paths, including IBD and non-IBD message processing, completed P2P handshakes and transport messages, successful estimator/mempool/snapshot operations, transaction and package acceptance, and compact block reconstruction.
Testing
Built the fuzz binary and replayed the current qa-assets corpora for all instrumented targets with
FUZZ_ENFORCE_REACHABILITY=1.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/33069008111/job/98506152003LLM reason (✨ experimental): CI failed because the
lint-locale-dependencecheck flagged a locale-dependentstd::fprintfusage insrc/test/fuzz/util/reachability.cpp.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
lgtm. I wonder if reachability goals can be formulated at a higher level. Maybe taking past issues or CVEs into account, to ensure they are covered and remain covered?
Seems fine, but this seems a bit low-level. I am thinking that goals may be best higher level?
Eg.
mempool.size()>=1, which implies non-ibd message?nit: I wonder if this can use
Mutex+ the annotationsnit: Would be nice to use the
///for new doxygen comments, to avoid the formatting inconsistencies around/**comments.I think it'd be great to add a message to this, so failures are more verbose.
It could also make sense to provide multiple reachability functions for different condition types, where the parameters of the comparison are passed directly e.g.
ReachabilityGoalGt(a, b, "sometimes a is greater than b");, this can be used to guide fuzzing in addition to asserting reachability. For example, the assertion feedback in this https://github.com/oss-garage/fuzzamoto/pull/69 PR could make use of the these reachability checks for guidance.Maybe (although this is likely more controversial) we could also place these checks into production code, to get this feedback for all our tests not just fuzzing.
Sure, I'll look into it.
I'd presume that -use_value_profile=1 of libFuzzer takes care of this for e.g.
mempool.size() >= 200, but I haven't really benchmarked any of this. Is there some gist or background on how to best guide a fuzz engine toward a set goal? I know there is libFuzzersfocus_function, but it is experimental and last time I tried it didn't work. Also, I haven't tried other fuzzing engines, so I wonder if others have nice findings here.AFL++ does have IJON annotations which I think can just be added to the harness, though it requires specific macros (maybe there is a way to hide them though?). I tested them but since I did not properly benchmark it compared to not using it, I could not tell whether it actually guided AFL++ to the goal more efficiently.
I was more thinking of custom fuzzers that could make use of this (e.g. that fuzzamoto PR I linked), or AFL++ also has an IJON implementation now, and Antithesis has their Sometimes Assertions, which could both be used under the hood in
ReachabilityGoal*. For Antithesis, this only makes sense if we put these goal annotations in non-test code, as the fuzz tests aren't running there.So overall I think splitting into different functions and explicitly passing the parameters gives us: better error messages, as well as more flexibility for different fuzzers. This can of course also be added later. I think what's in this PR already provides value.
The same argument could also be made for our
AssertandAssumemacros (e.g. havingAssume{Gt,Lt,...})Not sure if the current corpus data can pass this.Tested it, current corpus data fails on it. We have to first construct a valid Tx entry into corpus set first.
Huh, I am pretty sure I generated those manually last week and uploaded the fuzz inputs for that?
Hmm, I'd presume that reachability goals are test-case dependant. Let's say you want to have a "full mempool". For a test that manually fills the mempool with dummy transactions (possibly just as an initial setup for a later test), this goal is mostly meaningless and would be better off not being checked globally. However, if there is a mempool-sepcific test, it could make sense to have a reachability goal toward a "full mempool" for this specific test.
Moreover, even if the goals are similar for different test-cases, the specific goal could still differ: E.g. the connman test could have a goal of 1000 peers, whereas the p2p test could have a goal of 10 peers (or so)...
My bad, forgot to update the data set. But the thing is an input of
add tx + del txinprocess_messagesis also valid. so perhapsend_sequence != initial_sequenceis better?Added.
Beyond my knowledges, I'll take some time to get to know this first.
It is a good follow-up task, thanks.
Right, the assertion was just to trigger/find the input. The goal should obviously be inverted :)
Concept ACK
1e1144a468fed566dddd732886a0a5b78ad9df99: Is this deserialization a good candidate for it? I think the other ones for this target would implicitly catch it.
Just playing with the idea, thought on coinselection:
I meant "compare to use mempool.size() >= 1, end_sequence != initial_sequence may be a better choice?"
I've also uploaded block messages, so marking them as another goal could also make sense?
One problem is we still need a goal to represent at least one input goes the IBD path, while
mempool.size() == 0is not accurate for that. If we keepReachabilityGoal(saw_ibd_message, ...);, then seems keep bothsaw_ibd_messageandsaw_non_ibd_messagewould be more symmetricalJumpOutOfIbdandResetIbdalready have internal assertions (both ways), so now that those function calls are added back, it is unlikely to regress, unless they are removed?If you really want, you can add the redundant goals for it, but I don't think we need to turn every assertion into a goal.
Updated.
Updated.
Updated.
right, but currently the Goal is registered while
ReachabilityGoal()is called at the first time. Thus removing this causes the early return on line 59 escaped. This reminds me about the design, maybe a explicit Goal registration is better, otherwise we have to look out all the early returns? @maflcko any thoughts on this?Well, I'd say this shouldn't be needed, but maybe I am wrong. There could be options:
ReachabilityGoals. The benefit would be that everything here stays as-is and the tool sits somewhere else?No strong opinion. I guess anything is fine here?
Yes, I'm implementing the second way, will push the code soon.
Updated to "two-phase register/observe protocol".
Updated to use a two-phase register/observe protocol: each target explicitly registers its reachability goals during target initialization and records observations while processing inputs. This avoids lazy registration at observation sites, where an early return could leave a goal entirely unknown to the tracker and cause enforcement to pass silently instead of reporting it as unreached.
This was reverted in the last push?
Thanks, fixed.
Instead of a plain "success" (which probably happens on an empty file), it may be better to ensure all features are covered:
I did a mini experiment with different approaches to try and solve the maze AFL includes:
for
use_value_profile=1, I used a simpleif (hashfunc(row, col) == 0) abort();. My idea is that this would count different positions in the maze as unique because of the hash function, but I'm not sure if I understand the feature. It eventually found the solution after ~67M iterations (this varied a bit, one run hit ~1B iterations).compiling with AFL++ IJON (i.e.
IJON_SETmacro is activated in the maze code) quickly found the solution in ~300K iterationsusing clang with
__libfuzzer_extra_counters(incompatible on Darwin, though repurposing__sanitizer_cov_8bit_counters_initis compatible and works similarly) hit it in ~450K iterations:Solving the maze is one type of problem that uses the state area of the IJON region which is limited to 65,535 globally unique states, so it would be a bit limiting if we wanted to track many types of states. Similarly, using
__libfuzzer_extra_countersalso seems to take up a bit of memory if we're using a lot of states (especially if we're using a hash function which we shouldn't do). If anybody has ideas on a bitcoin-specific "maze", I could also benchmark that.I can only get this destructor to run when using libfuzzer by either running a single input or setting
-runs=N. I guess the purpose of the reachability checks (without the fuzzing guidance mentioned in a thread above) is for a CI job running a static corpus + detecting regressions (i.e. not fuzzing)? I wasn't able to get this to work with AFL++ when using-E=N(equivalent to libfuzzer's -runs option).I added a signal handler to catch SIGINT to make the destructor run, but seems like adding one is more trouble than it's worth since I ran into a hang and another weird issue.
Why buffer to
std::cerrif it may have passed?Why
std::_Exitwhich according to https://en.cppreference.com/cpp/utility/program/_Exit does not clean up resources compared tostd::exit? Also could just remove this since if the destructor runs, we shouldn't need to exit?nit: could instead be
Assert(m_goals.try_emplace ...)?Concept ACK
Yes, mostly for a nightly CI job on a static corpora folder with
-runs=1. Nightly, because we don't want master to randomly fail on (silent or otherwise) merge conflicts with the qa-assets repo.Not sure about AFL, but I guess it won't work anyway, due to the use of global memory, which won't be updated (or not propagated back) due to the forkserver mode?
Can you explain this? My intention was to have an exit code that indicates error. A normal exit would return 0, no?
I'll update this soon
Ah, ok. I was assuming that you'd know if it error'd from stderr, but returning non-zero exit code is correct.
I checked AFL++ again and the destructor does run, but a non-zero exit code isn't reported as a crash so it fails silently. Also, with the forkserver, only batches of 100,000 iterations are included in the reachability goal so it won't be accurate.
updated
make sense, how about only printing those FAIL goals?
Seems fine to print both for clarity
I meant that it could go to
std::coutinstead if it passed, but it's pretty minor.crACK
b3e4cdcf02The code changes and the goals here make sense to me. I think it would be really nice if we could get some distance-metric stuff in at some point, I might try to code up a PoC for both libfuzzer + AFL++ and see if any pieces here could be reused.
Just a thought, some of the failure cases could also be reachability goals? It would be nice if we could express each state is a goal without introducing separate goals, but I don't know how to do that.
tACK
b3e4cdcf02Base:
f8c9f2b5377c4a76f668b69ebecb060f100d062aHead:
b3e4cdcf020c6be28e929e6d8b2d29dc372008dfDesign and approach
[Suggestion] Enable reachability enforcement in corpus CI or document the manual workflow
CI corpus replay does not fail when a reachability goal is lost because it never enables enforcement.
Explanation and suggested change
Enforcement runs only when
FUZZ_ENFORCE_REACHABILITY=1, but the CI fuzz step andtest_runner.pydo not set this variable. A failed goal therefore only prints aFAILline in the DEBUG log, and the job still passes. If CI should enforce these goals now, export the variable in theRUN_FUZZ_TESTSstep or add atest_runner.pyoption; targets replayed against an empty corpus with--empty_min_timemay need an exemption. If enforcement is intended to remain manual or come in a follow-up, document that workflow indoc/fuzzing.mdor the PR description.Location:
src/test/fuzz/util/reachability.cpp:40(head).Previously reported concerns remain unresolved: 2 suggestion.
Previous findings
[Suggestion · still present] Track IBD-mode processing or narrow the coverage claim
Both goals can be met after IBD, so they do not detect lost coverage of message processing during IBD.
The observations in this harness, and the matching ones in
process_message.cpp, record only whether the mempool sequence or block-index size changed. Atxreturns early during IBD, so the mempool goal effectively requires non-IBD processing; a block-index change can occur in either mode. Although the harness toggles IBD inside the loop, it does not record whether a state-changing message was processed while IBD was active. A corpus that changes state only afterJumpOutOfIbd()can therefore meet both goals without covering IBD-mode processing. If that coverage matters, add a goal observed when a state-changing message is processed whileIsInitialBlockDownload()is true. Otherwise, revise the description so it does not claim IBD coverage.Location:
src/test/fuzz/process_messages.cpp:143(head).First reported at
b3e4cdcf020c6be28e929e6d8b2d29dc372008df. Last checked atb3e4cdcf020c6be28e929e6d8b2d29dc372008df. Author reply 2026-08-28T13:05:50Z Author reply 2026-08-28T14:31:59Z Author reply 2026-08-28T14:32:23Z Author reply 2026-08-28T14:32:37Z[Suggestion · still present] Account for filtered runs when registering goals
The goals are registered before LIMIT_TO_MESSAGE_TYPE is read. The existing test_runner.py corpus-generation workflow launches filtered process_message variants; with FUZZ_ENFORCE_REACHABILITY=1, a type such as PING cannot satisfy either mutation goal, so that filtered run fails regardless of corpus quality. Register only applicable goals, or explicitly reject/document enforcement for filtered runs.
Location:
src/test/fuzz/process_message.cpp:54(head).First reported at
b3e4cdcf020c6be28e929e6d8b2d29dc372008df. Last checked atb3e4cdcf020c6be28e929e6d8b2d29dc372008df.Review tier: standard
Full review report
193101ba20: I think some goals can't be reached if this target is running withLIMIT_TO_MESSAGE_TYPE(ofc depending on the message).I'd say it is expected that LIMIT_TO_MESSAGE_TYPE=... and FUZZ_ENFORCE_REACHABILITY=1 are mutually exclusive. If there is a need for it, it can be changed in the future.
lgtm, with some nits.
review ACK
b3e4cdcf02🗨Show signature
Signature:
bb09525fee: pretty sure this is wrong, because it includessingle_submit, no?96ab84c13e: same?454f917d02: Also, could make sense to also check that reconstruction works with 0 missing txs and with >0 missing txs. Otherwise, the fuzz target could accidentally decay into a trivial state.nit in
1a1ef162bf: Why not mempool estimator as well?Also, I wonder if there should be some stricter checks for the goal. E.g. require the read was not from a empty file, but a file that contained some values for each field in the class.
I don't think it was. I still see
56a89c4e1d@HowHsu do you want to take the remaining nits here?
Sorry for the delay, I got some life issue to handle these days, so will be back at the end of this month. Feel free to merge it anytime.
Did some tests, looks good, easier to use it than having to generate and check a coverage report for some cases (happy to review the code again when comments are addressed):
I think it is also fine to merge this and then address the nits in Q12027 or so. The approach itself looks good with three acks and the nits only concern the reachability goal of some fuzz targets.
LGTM
Looks like there's a handful of touch-ups / follow-ups here, but I'll merge this now, and someone can pick them up?