Skip to content

fix(spv): compute required proof headers from actual header difficulties#4039

Merged
piotr-roslaniec merged 1 commit into
threshold-network:mainfrom
lionakhnazarov:fix/spv-diff1-proof-headers
Jul 22, 2026
Merged

fix(spv): compute required proof headers from actual header difficulties#4039
piotr-roslaniec merged 1 commit into
threshold-network:mainfrom
lionakhnazarov:fix/spv-diff1-proof-headers

Conversation

@lionakhnazarov

@lionakhnazarov lionakhnazarov commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator

fix(spv): compute required proof headers from actual header difficulties

Problem

The SPV maintainer computed the number of block headers for a proof assuming every header carries the relay epoch difficulty: with txProofDifficultyFactor = 1 it always assembled a single-header proof. On testnet4 (BIP94), sweep transactions are regularly mined in minimum-difficulty (DIFF1) blocks, so the proof contained only a DIFF1 header. The Bridge skips DIFF1 headers when binding to the relay difficulty, finds no decisive header, and reverts with:

execution reverted: Not at current or previous difficulty

Because the error is deterministic, the maintainer crash-looped on the same transaction every cycle (error while maintaining SPV: ... restarting maintainer), and the affected wallet's main UTXO could never be registered on the host chain — blocking all subsequent sweeps for that wallet.

Fix

getProofInfo now mirrors the Bridge's BitcoinTx.determineRequestedDifficulty / evaluateProofDifficulty logic instead of assuming a fixed per-header difficulty:

  • walk headers forward from the proof start block,
  • skip leading minimum-difficulty headers, but only when both relay epoch difficulties are above minimum (so test/dev relays at difficulty 1 keep working),
  • bind the requested difficulty to the first decisive header matching the relay's current or previous epoch difficulty; if it matches neither, skip the transaction (the Bridge would revert),
  • accumulate headers (DIFF1 headers still contribute their work) until total observed difficulty reaches requestedDifficulty × txProofDifficultyFactor,
  • bound the walk by maxProofHeaders = 144 and report "wait for more confirmations" when the chain tip is reached first.

The old epoch-boundary block-count arithmetic is removed; epoch spans are handled implicitly by summing actual header difficulties.

Testing

  • TestGetProofInfo rewritten for the new semantics: current/previous-epoch proofs, epoch-spanning proofs with difficulty drop/raise, leading DIFF1 headers, relay at minimum difficulty, decisive-header mismatch, DIFF1 run exceeding the header bound, and chain tip reached early. Headers are generated with real compact-bits encoding (blockHeaderWithDifficulty).
  • go test ./pkg/maintainer/spv passes.
  • Verified live on the Sepolia/testnet4 stack: a sweep stuck for 10 days (876510fd...62c8, mined in a DIFF1 block at height 137542) was proven on the first cycle after deploying this fix — submitDepositSweepProof tx 0xfeeefad32c7116727949483edfb1e38f8117d923521fd3467886a05226b82577, status 1 — and the maintainer completed its round cleanly.

Notes

  • Requires a Bridge with DIFF1-aware determineRequestedDifficulty (deployed via the DIFF1 library upgrade). This changes maintainer behavior only for transactions whose proof would begin with minimum-difficulty (DIFF1) headers: those are now skipped rather than the maintainer deterministically failing on them, and a leading DIFF1 run exceeding maxProofHeaders is reported with a distinct log and metric. Transactions whose proof begins with a real-difficulty header are handled as before.

getProofInfo assumed every proof header carries the relay epoch difficulty,
so with txProofDifficultyFactor=1 it assembled single-header proofs. On
testnet4 (BIP94), sweeps mined in minimum-difficulty blocks produced proofs
containing only a DIFF1 header, which the Bridge rejects with "Not at
current or previous difficulty".

Mirror the Bridge's BitcoinTx logic instead: skip leading DIFF1 headers
when both relay epochs are above minimum, bind the requested difficulty to
the first decisive header matching the relay's current or previous epoch
difficulty, and accumulate headers until their total observed difficulty
covers requestedDifficulty * txProofDifficultyFactor.
@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@lionakhnazarov, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 17 minutes and 10 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c5ab636e-a35d-4bae-b50d-5cc7ed4baba3

📥 Commits

Reviewing files that changed from the base of the PR and between 4137b34 and 832c116.

📒 Files selected for processing (3)
  • pkg/maintainer/spv/bitcoin_chain_test.go
  • pkg/maintainer/spv/spv.go
  • pkg/maintainer/spv/spv_test.go
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

piotr-roslaniec added a commit that referenced this pull request Jul 22, 2026
## Summary

- remove the client-only 144-header cap from the SPV proof walk
- keep walking through mined headers until the proof has enough work or
reaches the Bitcoin chain tip
- skip only headers whose decoded target exactly matches the Bridge
DIFF1 target
- reject non-positive header targets before calculating difficulty

## Regression coverage

- 144 DIFF1 headers followed by a decisive difficulty-16 header
- non-DIFF1 bits 0x1d00aaaa, whose integer difficulty rounds to one,
remain decisive
- zero-target compact bits return a proof error instead of panicking

## Testing

- go test -count=1 ./pkg/maintainer/spv
- go test ./pkg/maintainer/...

Stacked on #4039. The temporary base branch mirrors #4039 at
832c116; retarget this PR to main after
#4039 merges.
@piotr-roslaniec
piotr-roslaniec merged commit 5245f66 into threshold-network:main Jul 22, 2026
30 checks passed
@piotr-roslaniec

Copy link
Copy Markdown
Collaborator

Follow-up: a multi-agent review of this change surfaced some edge-case, observability, and test-quality findings. Since this PR is already merged, they are addressed in a separate follow-up PR: #4186 (fix(spv): harden DIFF1 proof-header computation). The core algorithm here is unchanged.

lrsaturnino added a commit to lionakhnazarov/keep-core that referenced this pull request Jul 24, 2026
Resolve conflicts by final behavior, preserving the candidate's OOB
hardening and the no-cap / exact-target SPV semantics while taking main's
threshold-network#4039 work-accumulation model, threshold-network#4165 script-type isolation, threshold-network#4172 sweep
fee floor, and the threshold-network#3998 v1-random-beacon extraction.

SPV conflict resolution:
- pkg/maintainer/spv/spv.go: keep candidate side (no 144-header cap, header
  cache, exact decoded-target DIFF1 comparison + zero-target guard). Removed
  the `const maxProofHeaders = 144` that the 3-way merge silently re-added
  from main (merge-base lacked it, so the candidate's iteration-1 removal was
  invisible to the merge).
- pkg/maintainer/spv/deposit_sweep.go: combine candidate's bounds-checked
  OutputAt accessor with main's bitcoin.GetScriptType classification (threshold-network#4165).
- pkg/maintainer/spv/spv_test.go: keep candidate's superset of cases
  (non-DIFF1 rounding, zero-target, 145- and 201-header long-run cases);
  drop main's removed "minimum difficulty run exceeds header bound" cap test.

Accepted main's deletion of the extracted v1 random beacon and dead Ropsten
infra. NOTE: this drops two candidate-only v1 hardenings that main moved out
of this repo — require(entryCreatedSuccess) in KeepRandomBeaconOperator.sol
and the registry-approval modifier in KeepRandomBeaconServiceImplV1.sol. If
those are in security scope they must be ported to the keep-core-v1 repo.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
lrsaturnino added a commit to lionakhnazarov/keep-core that referenced this pull request Jul 24, 2026
Resolve conflicts by final behavior, preserving the candidate's OOB
hardening and the no-cap / exact-target SPV semantics while taking main's
threshold-network#4039 work-accumulation model, threshold-network#4165 script-type isolation, threshold-network#4172 sweep
fee floor, and the threshold-network#3998 v1-random-beacon extraction.

SPV conflict resolution:
- pkg/maintainer/spv/spv.go: keep candidate side (no 144-header cap, header
  cache, exact decoded-target DIFF1 comparison + zero-target guard). Removed
  the `const maxProofHeaders = 144` that the 3-way merge silently re-added
  from main (merge-base lacked it, so the candidate's iteration-1 removal was
  invisible to the merge).
- pkg/maintainer/spv/deposit_sweep.go: combine candidate's bounds-checked
  OutputAt accessor with main's bitcoin.GetScriptType classification (threshold-network#4165).
- pkg/maintainer/spv/spv_test.go: keep candidate's superset of cases
  (non-DIFF1 rounding, zero-target, 145- and 201-header long-run cases);
  drop main's removed "minimum difficulty run exceeds header bound" cap test.

Accepted main's deletion of the extracted v1 random beacon and dead Ropsten
infra. NOTE: this drops two candidate-only v1 hardenings that main moved out
of this repo — require(entryCreatedSuccess) in KeepRandomBeaconOperator.sol
and the registry-approval modifier in KeepRandomBeaconServiceImplV1.sol. If
those are in security scope they must be ported to the keep-core-v1 repo.
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.

3 participants