Skip to content

refactor: avoid redundant input lookup in CheckTxInputs - #35657

Closed
arejula27 wants to merge 3 commits into
bitcoin:masterfrom
arejula27:checktxinputs-dedup-haveinputs
Closed

arejula27 wants to merge 3 commits into
bitcoin:masterfrom
arejula27:checktxinputs-dedup-haveinputs

Conversation

@arejula27

@arejula27 arejula27 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Consensus::CheckTxInputs currently makes two UTXO lookups per input: first through a HaveInputs() pre-pass (which internally calls HaveCoin() for every input), and then through AccessCoin() on the same outpoints in the main validation loop.

HaveInputs() has only a single caller (CheckTxInputs), and AccessCoin() already returns a reference to a spent sentinel Coin for any missing outpoint. This means the presence check can be folded into the existing loop without changing behavior.

This PR removes the initial HaveInputs() pre-pass and instead checks coin.IsSpent() immediately after AccessCoin() returns. As a result, CheckTxInputs performs one lookup per input instead of two (2N → N, where N is the number of inputs) in the validation path shared by both ConnectBlock and mempool acceptance.

HaveInputs() itself is not removed. It is still used by the coins-view fuzz harness, although this change leaves it with no callers in the validation hot path. Removing it would be a trivial follow-up.

The only observable behavioral difference is which validation error is reported if one input is missing while another input in the same transaction fails for some unrelated reason (for example, coinbase immaturity).

  • In ConnectBlock, all such failures are ultimately reported as BLOCK_CONSENSUS, so the specific failure reason or ordering has no consensus impact.
  • In the mempool (MemPoolAccept::PreChecks), every input has already been checked with m_view.HaveCoin() before CheckTxInputs() is called. Missing inputs are handled there as orphan transactions, making the "missing input" path inside CheckTxInputs() unreachable during mempool validation.
Benchmark (bench_bitcoin -filter=CheckTxInputs)

The benchmark below is intentionally designed to measure the cost of the redundant lookup itself, rather than end-to-end block validation.

A fresh CCoinsViewCache wrapping CoinsTip is constructed for each measured batch (coins are added to CoinsTip itself, not to the benchmarked view), so each pass actually crosses the view/base boundary instead of hitting an already-warmed local cache. This closely matches how a fresh per-block view behaves in production.

BEFORE="d31c26fd1a53300a704bccbf12aae5b050c67ec3"
AFTER="5021cd02fa503f0ea0dc741f7200eba8275a885d"

RESULTS_FILE="$HOME/checktxinputs_bench_results.txt"
: > "$RESULTS_FILE"

echo "machine | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) cores | $(free -h | awk '/^Mem:/{print $2}') RAM" | tee -a "$RESULTS_FILE"

ORIG="$(git rev-parse --abbrev-ref HEAD)"

for hash in $BEFORE $AFTER; do
  echo ">>> $hash"
  git checkout "$hash" >/dev/null 2>&1 &&
  cmake --build build -t bench_bitcoin &&
  (
    echo "--- ${hash:0:7} ---"
    ./build/bin/bench_bitcoin -filter=CheckTxInputs -min-time=3000
  ) 2>&1 | tee -a "$RESULTS_FILE"
done

git switch "$ORIG"
ns/tx tx/s err%
before 1,154.31 866,316 0.4%
after 985.84 1,014,367 0.5%

~14.6% faster. This is smaller than a naive 2N → N lookup-count argument might suggest, because both lookups are FetchCoin calls against the same already-resolved cache entry after the first one resolves it. The second lookup is just a cheap lookup in an already-warm cache, not a second trip to the backing store. The real saving is exactly one redundant cache lookup per input, which is what this benchmark isolates.

As a sanity check, I also compared IBD over the same block range before and after this change and observed no measurable difference in synchronization time, which is expected: CheckTxInputs accounts for only a small fraction of ConnectBlock, where signature verification dominates.

The optimization is therefore real but modest. Its value comes from removing a genuinely redundant lookup without changing consensus behavior, rather than from any meaningful IBD speedup.

Historical context

This pre-pass originally served a real purpose.

Before April 2017, CheckTxInputs() used a per-txid CCoins cache where AccessCoins(txid) returned a raw pointer that could be NULL, and a single CCoins entry could contain both spent and unspent outputs. In that design, HaveInputs() prevented both null-pointer dereferences and spending an already-spent output within an otherwise live entry.

On 2017-04-25, two commits changed this:

  • 0003911326 ("Introduce new per-txout CCoinsViewCache functions") introduced AccessCoin(), which returns a reference to a sentinel empty coin for missing outpoints.
  • f68cdfe92b ("Switch from per-tx to per-txout CCoinsViewCache methods in some places") updated CheckTxInputs() to use the new API.

From that point onward, missing and already-spent outputs were both represented by coin.IsSpent() on the object returned by AccessCoin(), making the HaveInputs() pre-pass redundant. The validation loop has effectively remained unchanged since then, aside from the later scripted rename from IsPruned() to IsSpent() (589827975f).

This PR simply removes that leftover redundancy.

Edit: :When I opened this PR, I hadn't reviewed PR #35187, which modifies the same lines. While the primary goal of that PR is different, it also avoids the redundant lookup as a side effect.

Although that PR was submitted earlier, it is significantly larger and includes more critical and potentially controversial changes (it has already received one concept NACK), so it may take longer to be merged.

This PR is smaller, focused on a specific issue, and can be evaluated independently. It also doesn't block or conflict with the other PR, since #35187 can still be merged later on top of these changes without any issues. Not anymore

@DrahtBot

DrahtBot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35657.

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

No conflicts as of last run.

LLM Linter (✨ experimental)

Possible typos and grammar issues:

  • AccessCoin returns a spent coinEmpty -> AccessCoin returns a spent coin [“coinEmpty” is not grammatical here and makes the sentence unclear.]

2026-07-04 11:53:50

@arejula27
arejula27 force-pushed the checktxinputs-dedup-haveinputs branch 2 times, most recently from a38f455 to f03a13a Compare July 4, 2026 11:47
arejula27 added 2 commits July 4, 2026 13:53
Exercise the case where a transaction spends an outpoint that is
entirely absent from the coins view. AccessCoin returns a spent
placeholder Coin for it, so it must be rejected the same way as an
already-spent input: bad-txns-inputs-missingorspent.
@DrahtBot

DrahtBot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/28705366932/job/85240720272
LLM reason (✨ experimental): CI failed due to a Clang -Wthread-safety-analysis build error (calling chainstate.CoinsTip() without exclusive cs_main lock in bench/connectblock.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.

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not necessarily against this change; we've argued this for years now, but as noted in the description, this changes invalid block reason reporting.
Not sure how critical that would be (in l0rinc#137 I deliberately tried avoiding that), but ultimately the effect is small, and after #35215 it is expected to be even smaller.

@arejula27

arejula27 commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you @l0rinc for your comments!!

we've argued this for years now

Sorry, I wasn't aware, I tried to do some research before doing the pr but it looks like I missed something. I am reading the code, profiling and running benchmarks to find things to optimize, but I am not finding that much. I would be glad if you could point me to any issue or problem that has already been discussed but no one is working on :D

but as noted in the description, this changes invalid block reason reporting.

Personally, I think the impact is minimal. I would say (correct me if I am wrong) the mismatch is only visible locally, in debug.log and in the reject-reason string returned to submitblock/getblocktemplate proposal callers. It also only happens in the specific scenario where a transaction in a block has a missing input and an earlier input with an unrelated failure. In that case, reporting either of the two reasons seems enough to me. There is no behavior change in the node's logic, only which of the two errors is reported changes (one before, another now), so the same amount of information is reported: a single reject reason, just as before.

However im totally open to do any changes or explore a solution to that matter if it is really that relevant!

@l0rinc

l0rinc commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

looks like I missed something

Not necessarily, some similar discussion happened a long time ago e.g. #14837

the algorithm checks more invariants at once and detects them in a different order than before, clients relying on an exact reject reason may be confused. Clients should already not rely on exact reject reasons, so I don't believe this has a ramification.

profiling and running benchmarks to find things to optimize, but I am not finding that much

We're working hard to make sure you don't find that much :p
#35295 may enable new optimizations; you could help by reviewing it.
Just know that consensus refactors are usually ignored if done by relatively new contributors.

However im totally open to do any changes or explore a solution to that matter if it is really that relevant!

As mentioned, I'm not against it, but I'm personally not prioritizing it (especially while #35295 is still open).

@DrahtBot

DrahtBot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Could turn into draft while CI is red?

@arejula27
arejula27 marked this pull request as draft July 9, 2026 19:32
@arejula27

arejula27 commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Changed to draft because DrahtBot requested it.

Based on some previous comments about the behavioral change, I ran an demo on regtest comparing d31c26f (BEFORE, without this change) and 5b02e4b (AFTER, current branch tip) across every RPC channel where a reject reason is observable. For each RPC call I captured both the RPC response and whatever line it produced in debug.log.

Scenarios

  1. scenario_both_errors: vin[0] spends a coinbase with only 1 confirmation (immature), vin[1] spends a non-existent outpoint. This is the scenario from the PR description: two unrelated failures in the same tx.
  2. scenario_missing_first: same two failures as (1), but with the missing input ordered first in vin.
  3. scenario_immature_only: only the immature-coinbase input (single failure, sanity check).
  4. scenario_missing_only: only the missing outpoint (single failure, sanity check).

Results

  1. vin[0]=immature coinbase, vin[1]=missing outpoint (both failures, non-missing first), the scenario from the PR description:
channel d31c26f (BEFORE) 5b02e4b (AFTER)
gbt-proposal rpc bad-txns-inputs-missingorspent bad-txns-premature-spend-of-coinbase
gbt-proposal debug.log bad-txns-inputs-missingorspent bad-txns-premature-spend-of-coinbase
submitblock rpc bad-txns-inputs-missingorspent bad-txns-premature-spend-of-coinbase
submitblock debug.log bad-txns-inputs-missingorspent bad-txns-premature-spend-of-coinbase
testmempoolaccept rpc missing-inputs missing-inputs
testmempoolaccept debug.log (none) (none)
sendrawtransaction rpc bad-txns-inputs-missingorspent (-25) bad-txns-inputs-missingorspent (-25)
sendrawtransaction debug.log (none) (none)
  1. vin[0]=missing outpoint, vin[1]=immature coinbase (order swapped), identical BEFORE/AFTER:
channel d31c26f (BEFORE) 5b02e4b (AFTER)
gbt-proposal rpc bad-txns-inputs-missingorspent bad-txns-inputs-missingorspent
gbt-proposal debug.log bad-txns-inputs-missingorspent bad-txns-inputs-missingorspent
submitblock rpc bad-txns-inputs-missingorspent bad-txns-inputs-missingorspent
submitblock debug.log bad-txns-inputs-missingorspent bad-txns-inputs-missingorspent
testmempoolaccept rpc missing-inputs missing-inputs
testmempoolaccept debug.log (none) (none)
sendrawtransaction rpc bad-txns-inputs-missingorspent (-25) bad-txns-inputs-missingorspent (-25)
sendrawtransaction debug.log (none) (none)

Scenarios 3 and 4 showed the correct/expected error, since each only had a single failure present, no behavior change in either case.

@optout21

Copy link
Copy Markdown
Contributor

Note regarding the last "Edit" section of the description: I have checked the current version of #35187 (7bb468db884c885db5af5ab7abc6580b416f650e), and it does not touch this part (file src/consensus/tx_verify.cpp in not affected), so I think the information is not valid any more.

@arejula27

Copy link
Copy Markdown
Contributor Author

looks like the PR #35187 has been simplified after my edit on this PR description, so now it does not modify the same lines, ty @optout21 for notifying it 🙏

@l0rinc

l0rinc commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

@arejula27, please check if this still makes sense now that #35215 was merged.
And note that we mostly care about mainnet performance, and mostly about the blocks post 7-800k, so only checking it for the first 200k blocks doesn't reveal anything. Also note that a micro-benchmark being a bit faster doesn't usually translate to a real feature getting faster. Given how consensus critical this part is, we likely need a very compelling reason to change it.

@arejula27

Copy link
Copy Markdown
Contributor Author

Note that we mostly care about mainnet performance, especially for blocks after height 700-800k.

I will try to re-run the IBD focused on that section of the chain, but it may take a while. My hardware is modest and struggles with the validation, it's an external SSD, and sometimes the chain gets corrupted, so I have to start from zero again.

That said, I don't expect this PR to show impact in that way. Last time, it only showed gains in the micro-benchmarks. So if this PR needs IBD-level impact to be accepted, I'd say there's a high chance it gets dismissed.

@l0rinc

l0rinc commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

So if this PR needs IBD-level impact to be accepted

Every change is a risk, so we need to be convinced to spend time reviewing this thoroughly to be confident that it's safe to do this. Microbenchmarks are usually enough if the change is trivial otherwise, which arguably isn't the case here.

@arejula27

Copy link
Copy Markdown
Contributor Author

Yes, I totally understand and make sense, will come back with data 🫡

Microbenchmarks are usually enough if the change is trivial otherwise, which arguably isn't the case here.

Btw, found that txospenderindex under-reserves memory: it sizes the vector by tx count, but it actually grows by input count, so it ends up reallocating multiple times per block.
Already got the change implemented, just missing the microbench, worth it to try the PR or is this also critical-path territory?

@l0rinc

l0rinc commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Already got the change implemented, just missing the microbench, worth it to try the PR or is this also critical-path territory?

There's one way to find out!

Though note that we're planning on applying the savings from #35531 there as well (if this one gets in), so a future rewrite is not unlikely.

@arejula27

arejula27 commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Closing this.

Re-measured on current master, after #35215 made CCoinsMap key hashing cheaper. bench_bitcoin -filter=CheckTxInputs, -min-time=3000:

ns/tx tx/s
before 811.51 1,232,268
after 718.96 1,390,892

~10.9%, down from the ~14.6% in the description. The saving is one warm-cache lookup per input, never a read from the backing store, and CheckTxInputs is a small fraction of ConnectBlock: I measured no IBD difference.

Based on the feedback in this thread, I don't think this is worth spending more reviewer time on fr the follwoing reasons:

  • it's a change in consensus-critical code from a new contributor with no merged commits
  • The gain only shows up in the microbenchmark, not in real IBD.

Thanks for the reviews and your time!!

@arejula27 arejula27 closed this Aug 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants