Skip to content

3.x.x: fuzz the Stratum line codec, session state machine and codec parsers, with per-PR property tests (#575) - #591

Merged
djh58 merged 3 commits into
3.x.xfrom
djh58/prism-b575-stratum-fuzz
Sep 29, 2026
Merged

djh58 merged 3 commits into
3.x.xfrom
djh58/prism-b575-stratum-fuzz

Conversation

@djh58

@djh58 djh58 commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Refs #575 (item 4, Stratum fuzzing).

Nothing fuzzed or property-tested the Stratum front door. This adds three cargo-fuzz targets that drive the production per-connection loop and codec, a script that runs them for a fixed time and fails on any finding, and a small proptest suite that runs on every PR.

Seam (please review closely)

stratum::session(TcpStream, …) is split in two. session still calls set_nodelay and into_split, then calls the new #[doc(hidden)] pub async fn serve_connection(reader, writer, …). That function holds the unchanged loop body, generic over impl AsyncRead + Unpin / impl AsyncWrite + Unpin. write_json, result, deliver_job and request take &mut (impl AsyncWrite + Unpin) instead of &mut OwnedWriteHalf. Admission (global, per-source and per-username) and StratumConfig::validate stay in run_listener. Production only ever instantiates it with the TCP halves, so framing, timeouts, buffer bounds, budgets and shutdown behave as before. The targets and property tests call it over tokio::io::duplex, with no socket and no database. The in-crate session tests still pass socket halves (a #[cfg(test)] import keeps OwnedWriteHalf in scope for them).

The existing suites pass unchanged on this branch (private PostgreSQL 16, fsync on, PRISM_TEST_REQUIRE_INTEGRATION=1): stratum_protocol 39 passed (1 manual-only ignored, as before), stratum_codec 7, stratum_admission 5, stratum_admission_postgres 18 with --include-ignored, and the in-crate stratum:: tests 24.

Fuzz targets (crates/qbit-prism-server/fuzz, outside the workspace)

  • stratum_lines: arbitrary bytes in arbitrary fragments into one connection; the message bound (256 B to 16 KiB) and malformed-frame budget come from the input.
  • stratum_session: scripts of subscribe, authorize, configure, suggest_difficulty, submit, extranonce.subscribe and get_health requests with arbitrary params. Live placeholders ($job, $en2, $nonce solved against the job's target, …) let mutated scripts reach deep states. Events: tip refresh, same-parent payout revision, reconnect (resume), pipelining, injected builder/ledger faults, #again (duplicate). A #cfg line varies the listener: bound, extranonce2 size, stale grace, retention, job cap, username limit, the three budgets, vardiff, difficulties, network bits, template transactions, version mask.
  • codec_parsers: the codec's transaction, block, coinbase-split, compact-target, difficulty, hex and template parsers.

The backend is FuzzBackend: real jobs from real payout manifests, credit by the coordinator's gate (not block-only, current tip or stale grace, meets share target, not a duplicate). The existing test fakes are private to their test files, and this one also has to record every job it builds for the oracle.

Invariants, checked on every iteration:

  • no panic;
  • bounded allocation: a counting global allocator bounds per-iteration heap growth, and libFuzzer's malloc and RSS limits apply; no output line exceeds 4 × the bound + 16 KiB;
  • framing: every complete frame within the bound is answered exactly once, in order, with its own id; a frame that is not a JSON object gets a null-id malformed-submit; an oversize frame gets one null-id refusal and a close; no close without a documented cause, and nothing written after one;
  • documented errors only: codes 20/21/22/23 consistent with the reason IDs in docs/prism-rejections.md, or the three reason-less refusals. Submit before subscribe/authorize, short/non-string params, another username, a wrong-size extranonce2/ntime/nonce and a never-built job are each predicted exactly;
  • notify only for work the backend built for that connection's extranonce1, after subscribe and authorize, preceded by the matching set_difficulty;
  • no credit for an invalid share: credits and true answers correspond one to one. Each credited share is re-verified from the built job and the raw wire fields by code independent of assemble_submission: sizes, time ≥ mintime, version bits inside the persisted mask, header hash ≤ share target. The worker must be the one the job was issued to, and there is no credit on work a same-parent payout replacement retired (3.x.x: An own block found 9 s after the previous landing was refused unknown-job and never reached the node #478).

Seeds come from the stratum_protocol / stratum_codec vectors (21 session scripts, 11 line streams, 12 codec inputs). cargo test in fuzz/ regenerates them, replays them through the checks, and asserts that each session seed reaches the state it is named for.

Local runs (≥ 1 h each, shared heavy lock, pinned nightly-2026-09-24, ASan)

Each target ran 65 minutes, single process, from its seeds plus a 60 s smoke corpus. stratum_session and stratum_lines ran twice: once on the first harness, and again after the backend gained retained-difficulty evidence and the script gained vardiff knobs. That second run is on the committed code, and it continued from the first run's corpus.

Target Runs exec/s Edges (libFuzzer cov) start → end Features Corpus Peak RSS Findings
stratum_session (final) 1,034,891 265 7,987 → 8,307 44,272 3,401 618 MB none
stratum_session (first) 954,337 244 7,459 → 7,968 42,221 3,264 597 MB none
stratum_lines (final) 2,597,403 665 6,489 → 7,007 35,231 3,165 654 MB none
stratum_lines (first) 3,048,315 781 6,074 → 6,763 33,048 2,809 607 MB none
codec_parsers 96,018,955 24,613 2,241 → 2,700 9,916 2,075 708 MB none

Seeds alone reach 6,636 / 5,347 / 1,128 edges. Source line coverage (llvm-cov) from the seeds alone: stratum_session covers 62.8% of stratum.rs (the uncovered rest is mostly from_env, highdiff_config, run_listener admission and the TCP probe, none of which the seam reaches), 86.5% of retained_jobs.rs, 98.6% of stale_grace.rs and 77.3% of codec.rs. The final codec_parsers corpus covers 72.1% of codec.rs. No crash, leak, timeout, OOM or invariant violation in about 5.4 CPU-hours across the five runs, so there was nothing to fix.

Mutants (each must fail)

Mutant Caught by
difficulty_target floor + 1 difficulty_target_is_the_exact_clamped_floor_quotient, …_monotone_and_exact_on_integers
frame bound > → >= the_message_bound_is_exact_and_an_oversize_frame_closes; stratum_lines from an empty corpus in 206 s
string ids answered as null frames_round_trip_their_ids_under_any_fragmentation
share_pass against the network target a_submission_round_trips_its_fields
compact decoder accepts the sign bit compact_targets_round_trip
no block-only retirement (#478 regression) stratum_session: "credited job-0 after job-1 superseded it"; the nightly script exits 1 with the crash uploaded
submit username check removed stratum_session: predicted unauthorized-worker, got true
share_pass = true stratum_session: credited share hashes above its target

Per-PR CI delta

tests/stratum_properties.rs: 8 properties (24–256 cases), ungated because they read no environment input, run by rust-tests (cargo test --workspace --all-targets) and by the database job's workspace run. Cost per job: about 3 s to compile proptest 1.11 and its six new small dependencies (rand 0.9 family, rand_xorshift, unarray, getrandom 0.3), about 1 s to build and link the test binary, and 0.05 s to run. The fuzz crate is not a workspace member, so CI does not build it. cargo deny check passes. libfuzzer-sys is (MIT OR Apache-2.0) AND NCSA; it appears only in the fuzz crate's own lock, which cargo-deny does not check.

Nightly (separate workflow change)

.github/scripts/prism-stratum-fuzz.sh <corpus> <out> [seconds] installs the pinned nightly and cargo-fuzz 0.13.2 (sha256-checked release binary), builds the targets, runs all three at once for the given time, merges each corpus down, writes a summary table, and exits 1 on any crash, leak, timeout or OOM. The stratum-fuzz job in prism-load-nightly.yml (8 vCPU, 20 min per target, 45 min timeout) restores and saves the corpus through the Actions cache and uploads logs and findings. That workflow edit is pushed separately (the dev host's token cannot push workflow files) and keeps the file identical on main and 3.x.x. It needs this PR on 3.x.x first, because the schedule checks out 3.x.x. The script was run end to end locally: 30 s per target passes, and a planted #478 regression fails it with the crash saved.

Not an e2e scenario or load preset, so #560's manifest needs no entry.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

…arsers, with per-PR property tests (#575)

Issue #575 item 4: nothing fuzzed or property-tested the Stratum front
door. This adds three cargo-fuzz targets, a nightly script that runs them
for a fixed time and gates on no crash, and a small proptest suite that
runs in every PR.

- Seam: the per-connection loop is now `stratum::serve_connection`, generic
  over the read and write halves. `run_listener` still accepts, applies
  admission, calls `set_nodelay` and passes the TCP halves, so timeouts,
  buffer bounds, budgets and shutdown are unchanged; the helpers that wrote
  to `OwnedWriteHalf` take any `AsyncWrite`. It is `#[doc(hidden)]` and
  exists so the targets and tests can drive the production loop over an
  in-memory pipe, with no socket or database.
- `crates/qbit-prism-server/fuzz`, outside the workspace (own lock file,
  nightly toolchain): `stratum_lines` (arbitrary bytes in arbitrary
  fragments), `stratum_session` (scripts of subscribe, authorize,
  configure, suggest_difficulty, submit and extranonce requests, with live
  placeholders, tip and payout-revision refreshes, reconnects, pipelining
  and injected backend faults, over a configurable listener) and
  `codec_parsers` (transaction, block, coinbase-split, compact, difficulty,
  hex and template parsers). A `MiningBackend` with no database builds real
  jobs and credits by the coordinator's gate.
- Invariants checked on every iteration: no panic; heap growth bounded per
  iteration by a counting allocator, plus libFuzzer's malloc and RSS
  limits; every frame answered once, in order, with its own id, and an
  oversize frame refused with one null-id answer and a close; only
  documented codes and reason IDs, with the determinable submit refusals
  predicted exactly; notifications only for work built for that connection;
  and no credit for a share that fails validation, re-verified from the
  built job and the raw wire fields by code independent of
  `assemble_submission`, including #478's no credit for superseded
  same-parent work.
- Seeds from the stratum_protocol and stratum_codec vectors, generated and
  replayed by `cargo test` in `fuzz/`, which also checks that each session
  seed reaches the state it is named for; a libFuzzer dictionary.
- `tests/stratum_properties.rs` (proptest, 8 properties, 24 to 256 cases):
  frame id round trip under any fragmentation, the exact message bound,
  submission field round trip, and difficulty/target conversions (exact
  clamped floor quotient, monotonicity, round trip, compact encoding,
  scaled difficulty). Ungated: they read no environment input.
- `.github/scripts/prism-stratum-fuzz.sh` pins nightly-2026-09-24 and
  cargo-fuzz 0.13.2 (sha256), runs the three targets at once for a given
  time, merges each corpus down, writes a summary and exits 1 on any
  finding. The nightly job that calls it is a separate workflow change.
- docs/prism-stratum-fuzzing.md: targets, seam, invariants, local runs,
  nightly job.

Refs #575

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@djh58
djh58 requested a review from kiwidream September 29, 2026 18:54
@djh58

djh58 commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

@cursor review

@blacksmith-sh

This comment has been minimized.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread .github/scripts/prism-stratum-fuzz.sh Resolved
djh58 and others added 2 commits September 29, 2026 15:16
A libFuzzer -merge=1 that failed still deleted the grown corpus and moved
the partial merge output into its place, and the summary never named the
failure. The corpus is now replaced only when the merge exits 0; a failed
merge keeps the whole corpus, fails the run and prints an error naming the
merge log and its merge-* artifacts.

Refs #575

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@djh58

djh58 commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

@cursor review

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit b2ecc80. Configure here.

@djh58

djh58 commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

Deep-review ledger (head b2ecc80, CI green)

Stakes: high. The PR touches the Stratum per-connection session loop through the serve_connection seam, so Bugbot was summoned.

Lanes. The /code-review correctness, thermo code-quality and adversarial passes ran inline in the authoring session. This lane's contract allows no nested workers and no non-Claude providers, so there was no independent Opus or Codex adversarial lane: treat these passes as author review, not cross-agent review. Bugbot ran twice, on 0dd862d and b2ecc80.

ID Source Claim Disposition
bugbot-4137233035 + adversarial-1 Bugbot (medium) and the inline adversarial pass, found independently prism-stratum-fuzz.sh replaced the kept corpus with a failed -merge=1's partial output and never reported the merge failure fixed in b2ecc80 (reply); stub-tested. Bugbot's re-review on b2ecc80 found no new issues
adversarial-2 inline adversarial pass serve_connection is pub and does not validate its StratumConfig (e.g. max_message_bytes near usize::MAX overflows max + 1) rejected: #[doc(hidden)], with a documented precondition that the caller validates. run_listener validates once at start and the fuzz harness validates its own config. A per-connection validate would change the production loop this PR keeps behaviour-identical, and would guard only against callers that already break the contract

Checks. All CI jobs pass on b2ecc80, including Python shard 1: the earlier failure there was the pre-existing e2e-manifest gap, fixed by #584/#592 and merged into this branch as 0dd862d. The code-review and thermo passes raised nothing beyond the two rows above. The seam is a type generalization of the helpers' writer argument plus a split of session, and no file crosses 1k lines except stratum.rs, which was already 1,835.

Evidence recap. The existing Stratum suites pass unchanged, and a ≥ 1 h fuzz run per target found nothing. Every planted mutant is caught: five by the property tests and three by the session target, and the line target finds a message-bound off-by-one from an empty corpus. See the PR body for the numbers.

Owed. The nightly stratum-fuzz job is a separate workflow patch, which the coordinator applies after merge to 3.x.x and main.

@djh58
djh58 merged commit f4d1d79 into 3.x.x Sep 29, 2026
22 checks passed
djh58 added a commit that referenced this pull request Sep 29, 2026
Adds the stratum-fuzz job to the PRISM load-harness nightly workflow, as
prepared in #591: the three cargo-fuzz targets from #591 run at once for
20 minutes on the 17 2 * * * schedule, from the checked-in seeds plus the
corpus the previous night kept, gated on no crash, leak, timeout or OOM
input; the corpus is saved either way and any finding is uploaded. A
`fuzz` dispatch input runs it by hand; it defaults to off so preset
dispatches (for example a soak calibration) don't also pay for fuzzing.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
djh58 added a commit that referenced this pull request Sep 29, 2026
Brings in #590's real-node mode and resolves where it meets the soak:

- run.rs execute_with_preset: #590's node_mode and args rebinding first,
  then the soak plan over the rebound args.
- run.rs side report: #590's node_block, plus the soak entry.
- run.rs block scheduling: #590's rule (the tips plan lands its scheduled
  blocks in warm_up, every other plan in steady_state) is kept, on the
  phase's kind rather than its name, as holds_scheduled_blocks. A soak's
  c<cycle>.<preset>.<kind> phases therefore land their looped preset's
  blocks where that preset would, and each segment refreshes its block
  budget on the same rule. soak_plan asserts the weekly soak's 26 landings.
- launch_environment's map is bound mut for the soak's
  PRISM_SHARE_PARTITION_ENSURE_INTERVAL_SECONDS, inserted only when a soak
  runs; the fake-node frontend environment golden is unchanged.
- The soak presets pin --node fake, as #590 requires of every preset.
  --node qbitd refuses --plan soak by name: the looped segments are parsed
  from fake-node presets.
- The fake-node side report key golden gains the soak key.
- README preset table and test/prism-gated-tests.txt keep both sides,
  the gated list sorted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant