mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:20:38 +00:00
kernel: Block validation without a complete UTXO set #35187
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!35187
Loading…
Reference in a new issue
No description provided.
Delete branch "external_coins_block_validation"
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 adds a kernel C header API endpoint for validating a block without having access to the full UTXO set. The introduced block validation function is intended to be called after having instantiated a chainstate manager and processing the block's header. Following this contract, the block is internally validated by the
CheckBlock,ContextualCheckBlockHeader,ContextualCheckBlock, and finallyConnectBlockfunctions.The
CoinsViewBlockclass is introduced to validate user-provided coins passed through a callback. It inherits fromCCoinsViewCacheand is eventually passed toConnectBlock. This allows validating the block's scripts and spends against user-provided UTXOs instead of using the chainstate's own internal UTXO set.This also includes some more API endpoints to populate the coins and OutPoints and retrieve relevant data.
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.
The goal of this endeavor is to retire
btck_block_spent_outputs_readfrom the kernel?No, I think that is unrelated. Read deserializes data, while the creation function introduced here takes an existing shape of coins.
Approach ACK
If we are going through this route, won't it be more straightforward to just pass the spent coins and add them to the coins cache as demonstrated in
github.com/ismaelsadeeq/bitcoin@9b9db18353?Not sure why it is necessary to have the caller pass the block undo? Is it because we expect the client to have block undo, if not then it's an unnecessary round trip. Clients will map spent coins to block undo, and then we map the block undo to spent coins.
What format do we expect the block undo to be in? If we say they have to be well-constructed, i.e. be in the right index as the transaction that consumes them, etc., we have to verify that contract no? I don't think we do here. So, if we go ahead and do this and the proposed refactor in #32317 gets done, will passing an undo that violates that contract break things?
I find it less footgun-y for this approach to just receive a list of spent coins instead of block undo, because of the edge cases of empty undo ordering, in the coinsview map of undo to coins you have to skip block undo entries whose coins are created in the same block etc.
After #32317, we can skip the validation of the block undo ordering and contract by us mapping the spent coins and the block into the desired format, i.e., block undo vector.
I agree that the current approach here is not good and should be changed to not use the undo data structure. As you correctly lay out, it does rely on some internal coins cache behavior, and this was part of the motivation for opening #32317. I think passing the correctly shaped contiguous coins vector is a bit annoying to deal with for the calling developer. Maybe it's best to just rewire
FetchCoinFromBaseto take a callback that the developer passes to the validation function and then deals with it in their own space?🐙 This pull request conflicts with the target branch and needs rebase.
Not sure I truly understand the implications, but the callback passed to the validate method makes sense to me. From a client perspective, I believe the following would be most intuitive:
Which would translate to a signature of:
Approach ACK
🚧 At least one of the CI tasks failed.
Task
ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/29262195354/job/86858105991LLM reason (✨ experimental): CI failed because
test_kernelhit an UndefinedBehaviorSanitizer error (invalid-null-argument) when creating chainstate manager options (null/emptydirpassed).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.
``
Opening this up for review again. Basically went with @ismaelsadeeq's suggestion of passing in two arrays encoding pairs of outpoints and coins.
This looks much simpler now. I will review the changes thoroughly 👍🏾 .
🐙 This pull request conflicts with the target branch and needs rebase.
Code review ACK a77602ed7d4b4dda7cb4ef67148e004102a93be1
I did not find any issue, these are just minor comments.
I rebased this on https://github.com/bitcoin/bitcoin/pull/35000 and tested this path in the unit tests, I did not get any failure https://github.com/ismaelsadeeq/bitcoin/tree/pr-35187.
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 "kernel: Add sans utxo set block validation"
The omitting seems like an overkill and limiting, just remove it and document that we can't do full bip30 checks, it is done relative to the coins passed.
When the user indeed has all the UTXOs, this prevents that (hypothetical but still being flexible is better?).
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 "kernel: Add sans utxo set block validation"
Removing this does not trigger any failure fwiw. If we are going to enforce, maybe add a test.
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 "kernel: Add sans utxo set block validation"
This is important to prevent child spend before parent consensus bug, so perhaps document.
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 "kernel: Add sans utxo set block validation"
I think we can relax the requirement a bit, such that the header of the block that we are validating does not need to be processed before calling this, we can process the header internally here, which will reduce the round trip.
In 5c9189d48ec3194aed6c9d4a7b52f6e381cf2ba6 "kernel: Add coin creation to C header"
nit: be specific
s/height/confirmation_heightor block height? same in the comments as well.In 5c9189d48ec3194aed6c9d4a7b52f6e381cf2ba6 "kernel: Add coin creation to C header"
btck_coin_create()accepts auint32_t height, but the value is stored in internalCoin::nHeight, which is only 31 bitsThis test fails ( Creating a custom type for this seems like an overkill, so atleast document it explicitly ?)
In d48fe4a4a7ef8993e3d2c504cea91e26096f7b2d "kernel: Add outpoint creation to C header"
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 kernel: Add sans utxo set block validation
This is confusing we log that header is not processed but then returned cached invalid result and duplicate-invalid?
In a77602ed7d4b4dda7cb4ef67148e004102a93be1 kernel: Add sans utxo set block validation
nit: add a brief description?
The Validation blog post explains that there are essentially three different "levels" to validate a block with more or less consensus evidence:
The titles of the PR and the commit ("non-utxo set block validation", "sans utxo set block validation") seem to imply that this is adding a validation function for either level one or two. But looking at the signature of the added function, I get the impression that this is about level three instead: The
block_tree_entryargument provides the ancestry whilespent_out_points,spent_coins, andspent_outputs_lentogether provides access to the coins.The way the spent coins are provided to the function (two arrays) requires the whole utxo-set to be converted twice:
std::mapfrom the two arrays.While this approach may serve as a proof-of-concept, it will not scale to a production application.
As @alexanderwiederin pointed out, a better approach would be to abstract the lookup function. This way, the library is given direct, zero-copy lookup access to the clients dictionary structure.
Yeah, I agree that, depending on the script size, the coin copy may not be cheap. Your suggestion allows the lookup function to be passed to the
CoinsViewBlockclass, and the lookup will be direct and zero-copy, as u mention. But note the current approach does have the advantage of preventing footguns like child spend before parent, which is a consensus bug. A naive client might shoot themselves in the foot easily by allowing access to the child utxo in the db before it is created.Currently this just filters out all intra-block spends. The current implementation is wasteful however: It does a fairly large allocation for something that isn't actually required if the user doesn't include such coins. This is just really annoying to deal with. Do you think it were preferable if we'd just say that the passed in array of coins must not contain intra-block spends?
It's tricky, I think it can be important to prevent users from shooting themselves in the foot, as I laid out here https://github.com/bitcoin/bitcoin/pull/35187#issuecomment-5033330747
But definitely, removing this will simplify the flow.
It is not about the copy of a coin. It is about two copies of the complete utxo set, no? One copy to flatten it into two arrays and another copy to convert the two arrays into a map.
How so? Inserting the block's utxos into the utxo set before the block is validated would indeed not be very smart. But how does this design prevent it?
Because we have the block and the user provided utxo's the
CoinsViewBlockchecks during insertion into the map that it is not a block utxo.Can you elaborate? I want to make sure I follow. If you mean forward references in intra-block spends:
FetchCoinFromBasealready guards those withm_block_txids.contains(outpoint.hash)on every base fetch, before it consults the coin source. It could protect a callback source the same way it protects the two arrays.@alexanderwiederin yeah sorry, my comment wasn't elaborate enough. Currently, we prevent forward references in intra block spends twice, both keyed on
m_block_txids.contains(outpoint.hash).CoinsViewBlockconstructor, we don't add a supplied coin to the map if its outpoint belongs to a transaction created in this block.FetchCoinFromBase, we returnnulloptfor any in-block outpoint before even consulting the map:These two guards enforce the same invariant, so either one alone is sufficient. With only the constructor filter,
m_coinscan never hold an outpoint whose hash is an in block txid.This holds for the
BIP30edge case too? But with only theFetchCoinFromBaseguard, an in-block coin could sit inm_coinsbut would never be served.So the IMO
FetchCoinFromBasecheck is the redundant one, and it's on the hot path evaluated on everyFetchCoinFromBasecall, whereas the constructor check runs once per supplied coin at setup.That's why I suggested removing it here https://github.com/bitcoin/bitcoin/pull/35187#discussion_r3615051298, and why keeping approach 2 instead is the less efficient choice, as I noted here https://github.com/bitcoin/bitcoin/pull/35187#discussion_r3652089515, but if you go with the approach you suggested, then we may need approach 2.
Please correct me if I am wrong here.
Concept ACK
Are you suggesting here to allow a null
block_tree_entryand then process the header separately if it is null?Kept it for now.
Updated a77602ed7d4b4dda7cb4ef67148e004102a93be1 ->
5c65fc94a3(external_coins_block_validation_0 -> external_coins_block_validation_1, compare)ConceptACK, approach = nearly, but not quite? (err, this was looking at a77602ed7d4b4dda7cb4ef67148e004102a93be1 but still mostly applies after the update, I think)
I think it should be possible to design this in a way that doesn't require copying the utxo set (from the caller's representation into two vectors and from two vectors into
CoinsViewBlock::m_coins).Relatedly, I don't think
ValidateBlockhas quite the right API -- returning aBlockValidationStateis fine, but that throws away the "here's how the utxo set ends up" info that theCoinsViewshould be able to provide.I think a better approach would be:
btck_Coinandbtck_TxOutPoint, provide abtck_CoinsDbtype, which would be an in-memory container for utxos, essentiallymap<OutPoint,Coin>CoinsViewBlock(btck_CoinsViewCoinsDb?) be able to be no-copy constructed frombtck_CoinsDbValidateBlockwithout needing an additional copybtck_CoinsViewCoinsDb's delta to kernel users so you can easily query what changedHaving
btck_CoinsDbbe constructable directly from deserializing a block's rev.dat data should be plausible, I think, and would make the "I have the blk.dat and rev.dat info for this block, I want to validate it in isolation" work sensibly.I think we should control the container ourselves, rather than using a
lookup(outpoint) -> coincallback that the caller provides so that we can be sure the lookups are consistent across calls. I think we should probably only expose two sorts of views: in-memory and full leveldb-based-utxo-set, to avoid adding more code paths versus what we use in the node.btck_CoinsDbmight just beCCoinsViewCache{CoinsViewEmpty::Get()}?Probably don't need to provide too many accessors/modifiers (
btck_coinsdb_lookup,_add,_remove,_iterate(callback),_update(coinsviewcoinsbd), andbtck_coinsview_iterate(added_cb, removed_cb)) ?Allowing two concrete types means having two separate code paths, where one code path is the one that is used in production and the other one is basically dead. An abstraction, on the other hand, means having a single code path all while being able to use any compatible type for testing. Please elaborate what you mean with consistency here.
The leveldb approach is precisely what we use in production; the in memory approach could probably just be a
CCoinsViewCacheon top ofCoinsViewEmpty::Get(), which we already use in tests, and just re-exercises mempool code.A
lookup(outpoint)function can return(randbool() ? coin1 : coin2)to break our logic, or do something equivalent by accident.Is that a "yes"? If one code path is used exclusively for tests and never exercised in production, then this code path is dead. Plus the risk that the code path that is exercised in production may be not tested properly.
That does not answer my question about consistency. Is your concern that the client may provide a non-deterministic lookup function? What about making it a requirement that the lookup function must be deterministic?
Nit: would an
unordered_mapbe better? It would need a hasher over txid + index. Understand that it's just test code, but it would be valuable for demonstration purposes.Concept ACK
I wrote a test against these bindings that exercises the current API the way I would expect a caller to: sync all headers, then walk the blocks, validating each against a UTXO set the test maintains itself. No blocks are ever connected, so every coin comes from the callback.
Test is here if useful.
The design holds up well in my opinion.
Edit: opened a draft PR on rust-bitcoinkernel for feedback
I specifically implemented it this way, which admittedly reads a bit bizarre, to avoid having to implement a hasher for the tests here.
Reviewed. I understand that this is an important need to be solved. The solution looks correct. However, I have no strong opinion on whether this is the right approach, and I have limited kernel experience, so I give no formal opinion for or against.
I have no strong opinion on whether the
ValidateBlocksolution (invalidation.cpp) is the right generic approach in the validation layer.I think there should be a direct (non-kernel) test for the new
ValidateBlock(invalidation.cpp).Left some minor comments.
Nit: class documentation would be nice here.
Passing exactly those coins that are spent by this block looks like a neat trick here. However, it assumes the undo data for the block is already available. This would probably be not the case for a scenario where a fresh block is being checked.
Maybe a test where the whole UTXO set is supplied (via the coin fetcher) would be more realistic for such a use case.
A note-only (orthogonal to this PR): With #36066, there would be no longer need for a mutable
CBlockIndex(TestConnectBlock).To be more precise,
TestBlockValidity/ConnectBlock(.../*fJustCheck=*/true)does some state updates through side effects.5c65fc94a3kernel: Add sans utxo set block validation:When we call
ConnectBlockon a main chain block that is an ancestor of theassumevalidblock (and satisfies some other straightforward criteria), we inheritassumevalidlogic and omit script checks.Should there instead be some logic that forces a
script_check_reasonwhenValidateBlockcallsConnectBlockor is the current logic the desired behavior?🐙 This pull request conflicts with the target branch and needs rebase.
Rebased and updated:
5c65fc94a3->f816f17f54(external_coins_block_validation_1 -> external_coins_block_validation_2, compare)ValidateBlock()can make the node connect an invalid block.It caches successful script checks in
m_script_execution_cache, whose key is the wtxid and the script flags. It doesn't include the coins being spent. That's safe for coins from the UTXO set, since an outpoint always refers to the same output. WithValidateBlock(), though, the caller supplies the coins and can return anything.For example, a
CoinFetcherthat returns anOP_TRUEscript instead of the real one gets the transaction cached as valid. A laterProcessBlock()on the same chainman then reuses that result and connects the block, even though it fails against the real UTXO set. LaterValidateBlock()calls with wrong coins also pass.This only happens with 0 script check worker threads, which is the kernel default. When the checks run on worker threads, nothing gets cached.
The tests below reproduce both cases, along with a suggested fix: don't cache results in
ConnectBlock()when it's called fromValidateBlock().diff
ValidateBlock()can crash on a coin with an impossible confirmation height.Validation assumes every spent coin was created in an earlier block. The UTXO set guarantees that, but coins from the callback don't. For example, say a block at height 1 spends a coin the callback reports as confirmed at height 100. If the spending transaction uses a time-based relative lock (BIP68), the lock check looks up block 99 among the block's ancestors. That block doesn't exist, so the lookup returns null and an assertion stops the process, even in release builds.
The suggested fix below treats a fetched coin as missing if its height isn't below the block's height, so validation returns
INVALIDinstead of crashing. That includes coins at the block's own height: the block's own outputs are never fetched, so a coin claiming that height can't be genuine.The test checks that a coin from an earlier height is still accepted, and that coins at the block's height or far in the future are rejected.
diff
Thanks for flagging @w0xlt, my own LLM scans also came up with the same two issues yesterday :). I think both revolve around the question whether we can provide a function that is robust against adversary-provided, or otherwise incorrectly constructed coins. My current impression is that we cannot. For your second suggestion, how about just amending the documentation with "coins must be unspent and their height below the blocks height"?
The first one is a bit annoying to deal with. We could just assume that "these coins are required to be genuine", but the caches are just annoying in general and don't really serve a purpose in the context of validating a single block. Maybe we can clear them every time we call the function? I really don't want to add more code to the existing validation functions.
These issues surfaced indirectly through mutation tests generated by an LLM. The scans themselves didn’t report them.
I’m unsure about their practical severity. It depends on the intended API trust model. With incorrectly supplied coins, the current implementation can crash or poison cached results used by subsequent block processing on the same chainstate manager. If callers must supply trusted coins, this needs to be explicit
Just documenting the height requirement still leaves an avoidable crash. It’s an inexpensive check that prevents a known crash without changing the existing consensus validation functions
Yes, the solution suggested above also needs refinement: it prevents new entries from being stored, but still allows hits from an already populated cache. Perhaps a separate script-execution cache for each call, or bypassing that cache for this operation, would be cleaner.
Just to clarify, I don’t necessarily see these as blockers. If callers are expected to provide genuine coins, clearly documenting that requirement and the risks of incorrect inputs may be enough
If clearing the full-script cache is acceptable, we could bypass it for this call instead. That avoids clearing shared entries and keeps signature caching. The changes to validation are small.
As suggestion, the branch below adds explicit control over full-script validation cache, including a mode that bypasses it completely. This prepares validation for caller-supplied spent outputs while preserving signature caching and current behavior.
https://github.com/w0xlt/bitcoin/tree/validation-script-cache-policy
Great to see these issues identified, @w0xlt & @sedited !
In general, I think these are symptoms of the difficulty of separating out parts of a codebase with internal dependencies, many of which are implicit.
The trust model: I assume a single node implementation, composed of the core kernel library and other implementation, in a single unit, but different organizational source.
The script cache issue is not a vulnerabilty (due to the trust model), and while it could be intentionally misused in case of potential vulnerability, it is very unlikely to occur due to programming error, so I think it's acceptable.
I like the suggestion to offer a flag, to use the script cache (read&write) or not (with default no). Another alternative would be to expose the script cache functionality and place it behind a callback, to make the dependency and responsibility more explicit. However, this would be rather complex.
For the assert-due-to-invalid-coin: I think an assert due to programming error can be defended, but I would prefer to be handled gracefully. So far the assert could trigger only if core code is buggy. Now it can assert if external code is buggy, which is different. For caller-triggered error a graceful error return would be correct, so I would argue for a change here (fail the validation instead of aborting).
Base:
4bacf21a13c2ed25ef9362ca38f26bf0a67d22c9Head:
ed76d293770961547dab6875d434e99ab02b445bFindings
Major
Assumevalid can skip script checks against supplied coins (src/validation.cpp:4504, head)
When the configured assumevalid block is an ancestor of both this block and the best-header chain, minimum chainwork is met, and the block is sufficiently deep,
ConnectBlocksetsfScriptChecksto false and skipsCheckInputScripts. The endpoint can therefore return success without checking input scripts against its supplied coins. Force script checks here or document that the result follows assumevalid. No in-repository production embedding caller was identified, so external production use of this conditional path remains unconfirmed.Suggestions
Clarify the trust required for supplied coin data (src/kernel/bitcoinkernel.h:1348, head)
ConnectBlockuses the supplied coin’s output, height, and coinbase status for script, value, maturity, and sequence-lock checks, and this API does not authenticate those fields against chainstate. Document that callers must provide accurate coin data and that aVALIDresult is relative to that supplied view.Design and approach
Document or avoid callback work under
cs_main(src/kernel/bitcoinkernel.cpp:664, head)FetchCoinFromBaseinvokes caller code synchronously duringConnectBlock, whileChainstateManager::ValidateBlockholdscs_main. A slow per-outpoint lookup can delay other chain-manager operations. Document that callbacks must be prompt, or fetch the required coins before entering the locked validation path. No in-repository production embedding callback was identified, so the impact depends on host implementations.Review coverage was incomplete. adversarial: ConnectBlock after line 2443 was not inspected, including script execution and cache handling. Kernel chainstate initialization of assumevalid was also not inspected. These could determine whether the new API always checks caller-supplied scripts. adversarial_glm: src/coins.cpp FetchCoin/FetchCoinFromBase internals (line 54-62) were located but not read, so the exact negative-result caching semantics — and therefore whether the user callback is invoked once or multiple times per missing outpoint across HaveInputs/GetValueIn/SpendCoin/CheckBIP30 queries — are unverified. adversarial_glm: src/validation.cpp ContextualCheckBlock (line 4137) was located but not read, so whether it dereferences a null pindexPrev (genesis entry) unguarded is unconfirmed. adversarial_glm: ConnectBlock's full body, the base TestBlockValidity, and the bitcoinkernel.cpp Handle templates (btck_Coin::create/get, btck_TransactionOutPoint::ref) were not re-read at head; the BIP30-check behavior of the head ConnectBlock that motivates the m_block_txids filter is inferred from the PR comment and header doc, not verified line-by-line.
Full review report
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased
f816f17f54->ed76d29377(external_coins_block_validation_2 -> external_coins_block_validation_3, compare)Tested
ed76d29on signet.Could this say the coins must match what the block spends, not just be unspent? A coinbase coin one block old is accepted if passed with
is_coinbaseset to 0, and w0xlt's height check wouldn't catch it.Could the coins be fetched before taking cs_main? The block already lists its prevouts as such
ValidateBlockcould call the callback for each one, then lock and connect. As it is, a callback that does disk or network I/O blocks every other kernel call that needs cs_main.My opinion is to have
ValidateBlockalways check scripts. After a full headers sync, blocks below the default assumevalid (~321k, chainparams.cpp#L479) skip script checks. Adding 1 sat to a native segwit input's amount was accepted in all ~2k signet blocks I triedand callers have no way to turn this off (validation.cpp#L6183).