Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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 |
No, I think that is unrelated. Read deserializes data, while the creation function introduced here takes an existing shape of coins. |
|
Approach ACK 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? 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 |
|
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: let state = chainman.validate_block(
&block,
|outpoint: TxOutPointRef<'_>| -> Option<Coin> {
my_db.get(&outpoint)
},
)?;Which would translate to a signature of: typedef const btck_Coin* (*btck_coin_getter)(
void* context,
const btck_TransactionOutPoint* outpoint
);
BITCOINKERNEL_API int btck_chainstate_manager_validate_block(
btck_ChainstateManager* chainstate_manager,
const btck_Block* block,
btck_coin_getter coin_getter,
void* context,
btck_BlockValidationState* block_validation_state
); |
|
Approach ACK |
b5eabfa to
a44e63b
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
5eed028 to
46b929c
Compare
2c9e5da to
a89b355
Compare
optout21
left a comment
There was a problem hiding this comment.
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 ValidateBlock solution (in validation.cpp) is the right generic approach in the validation layer.
I think there should be a direct (non-kernel) test for the new ValidateBlock (in validation.cpp).
Left some minor comments.
| struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {}; | ||
| struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {}; | ||
|
|
||
| class CoinsViewBlock : public CCoinsViewCache |
There was a problem hiding this comment.
5c65fc9 kernel: Add sans utxo set block validation:
Nit: class documentation would be nice here.
| return state; | ||
| } | ||
|
|
||
| // Needs to be mutable for ConnectBlock, but is not actually mutated with fJustCheck |
| /** | ||
| * Validate a block against the passed in coins without using the | ||
| * chainstate manager's coins. | ||
| * Similarly to TestBlockValidity it does not mutate state. |
There was a problem hiding this comment.
5c65fc9 kernel: Add sans utxo set block validation:
To be more precise, TestBlockValidity/ConnectBlock(.../*fJustCheck=*/true) does some state updates through side effects.
| } | ||
| } | ||
|
|
||
| BlockSpentOutputs block_spent_outputs{chainman->ReadBlockSpentOutputs(block_tree_entry)}; |
There was a problem hiding this comment.
5c65fc9 kernel: Add sans utxo set block validation:
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.
|
|
||
| // Needs to be mutable for ConnectBlock, but is not actually mutated with fJustCheck | ||
| CBlockIndex* index_mut{const_cast<CBlockIndex*>(&index)}; | ||
| if (!ActiveChainstate().ConnectBlock(block, state, index_mut, coins, /*fJustCheck=*/true)) { |
There was a problem hiding this comment.
5c65fc9 kernel: Add sans utxo set block validation:
When we call ConnectBlock on a main chain block that is an ancestor of the assumevalid block (and satisfies some other straightforward criteria), we inherit assumevalid logic and omit script checks.
Should there instead be some logic that forces a script_check_reason when ValidateBlock calls ConnectBlock or is the current logic the desired behavior?
There was a problem hiding this comment.
My opinion is to have ValidateBlock always 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).
5c65fc9 to
f816f17
Compare
|
Rebased and updated: 5c65fc9 -> f816f17 (external_coins_block_validation_1 -> external_coins_block_validation_2, compare) |
|
It caches successful script checks in For example, a 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 diffdiff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index 6b747274f3..9ee0e0cf17 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -1207,6 +1207,8 @@ private:
public:
BlockSpentCoinFetcher() = default;
+ explicit BlockSpentCoinFetcher(std::vector<std::pair<OutPoint, Coin>> coins) : m_coins{std::move(coins)} {}
+
BlockSpentCoinFetcher(const Block& block, const BlockSpentOutputs& block_spent_outputs)
{
size_t undo_index{0};
@@ -1231,6 +1233,33 @@ public:
}
};
+// Returns the coins of the wrapped fetcher with their script pubkey replaced.
+class ScriptPubkeyOverrideCoinFetcher : public CoinFetcher
+{
+private:
+ CoinFetcher& m_fetcher;
+ ScriptPubkey m_script_pubkey;
+
+public:
+ ScriptPubkeyOverrideCoinFetcher(CoinFetcher& fetcher, ScriptPubkey script_pubkey)
+ : m_fetcher{fetcher}, m_script_pubkey{std::move(script_pubkey)} {}
+
+ std::optional<Coin> FetchCoin(OutPointView out_point) override
+ {
+ auto coin{m_fetcher.FetchCoin(out_point)};
+ if (!coin) return std::nullopt;
+ return Coin{TransactionOutput{m_script_pubkey, coin->GetOutput().Amount()}, coin->GetConfirmationHeight(), coin->IsCoinbase()};
+ }
+};
+
+// Block at height 207 building on top of REGTEST_BLOCK_DATA. Its second
+// transaction spends the P2PKH coinbase output of block 3 with an empty
+// scriptSig, so the block is only valid if that coin's script is replaced.
+constexpr std::string_view REGTEST_INVALID_SPEND_BLOCK{
+ "040000004e974c3d83c0a4942454716d75d45a110edc330008283123f87328f86b82eb26847660b436956a2b09ca1903179e40ab5486b537881571282d646d7acbb8c81107110e6affff7f20"
+ "000000000202000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0302cf00feffffff0100f90295000000000151ce00000002000000013543"
+ "52df0f2a5d635ca7d3a52064f9c95f070d2c13c0a6c087acba03dfeeae660000000000ffffffff0100f2052a01000000015100000000"};
+
BOOST_AUTO_TEST_CASE(btck_chainman_regtest_tests)
{
auto test_directory{TestDirectory{"regtest_test_bitcoin_kernel"}};
@@ -1398,6 +1427,45 @@ BOOST_AUTO_TEST_CASE(btck_chainman_regtest_tests)
BOOST_CHECK_EQUAL(state.GetValidationMode(), ValidationMode::INVALID);
BOOST_CHECK_EQUAL(state.GetBlockValidationResult(), BlockValidationResult::CONSENSUS);
}
+
+ {
+ // Validate with coins whose scripts fail. The block was already
+ // validated above with the correct coins, which must not affect
+ // the result.
+ BlockSpentCoinFetcher coin_fetcher{blocks[205].first, blocks[205].second};
+ ScriptPubkeyOverrideCoinFetcher op_false_fetcher{coin_fetcher, ScriptPubkey{hex_string_to_byte_vec("00")}};
+ BlockValidationState state;
+ BlockTreeEntry entry{*chainman2->GetBlockTreeEntry(blocks[205].first.GetHash())};
+ BOOST_CHECK(!chainman2->ValidateBlock(blocks[205].first, entry, op_false_fetcher, state));
+ BOOST_CHECK_EQUAL(state.GetValidationMode(), ValidationMode::INVALID);
+ BOOST_CHECK_EQUAL(state.GetBlockValidationResult(), BlockValidationResult::CONSENSUS);
+ }
+ }
+
+ {
+ // Validating a block against forged coins must not make the
+ // chainstate manager accept it against its own UTXO set.
+ Block invalid_block{hex_string_to_byte_vec(REGTEST_INVALID_SPEND_BLOCK)};
+ BOOST_CHECK_EQUAL(chainman->ProcessBlockHeader(invalid_block.GetHeader()).GetValidationMode(), ValidationMode::VALID);
+ BlockTreeEntry entry{*chainman->GetBlockTreeEntry(invalid_block.GetHash())};
+
+ Block funding_block{*chainman->ReadBlock(chain.GetByHeight(3))};
+ TransactionView funding_tx{funding_block.GetTransaction(0)};
+ BlockSpentCoinFetcher coin_fetcher{{{OutPoint{funding_tx.Txid(), 0}, Coin{TransactionOutput{funding_tx.GetOutput(0)}, /*confirmation_height=*/3, /*is_coinbase=*/true}}}};
+ ScriptPubkeyOverrideCoinFetcher op_true_fetcher{coin_fetcher, ScriptPubkey{hex_string_to_byte_vec("51")}};
+
+ BlockValidationState state;
+ BOOST_CHECK(!chainman->ValidateBlock(invalid_block, entry, coin_fetcher, state));
+ BOOST_CHECK_EQUAL(state.GetBlockValidationResult(), BlockValidationResult::CONSENSUS);
+ BOOST_CHECK(chainman->ValidateBlock(invalid_block, entry, op_true_fetcher, state));
+ BOOST_CHECK_EQUAL(state.GetValidationMode(), ValidationMode::VALID);
+
+ // The block is stored, but must fail to connect.
+ bool new_block{false};
+ BOOST_CHECK(chainman->ProcessBlock(invalid_block, &new_block));
+ BOOST_CHECK(new_block);
+ BOOST_CHECK(!chainman->GetChain().Contains(entry));
+ BOOST_CHECK_EQUAL(chainman->GetChain().Height(), tip.GetHeight());
}
// Read spent outputs for current tip and its previous block
diff --git a/src/validation.cpp b/src/validation.cpp
index cab104548b..b435d4a216 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -2290,9 +2290,10 @@ script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const Ch
/** Apply the effects of this block (with given index) on the UTXO set represented by coins.
* Validity checks that depend on the UTXO set are also done; ConnectBlock()
- * can fail if those validity checks fail (among other reasons). */
+ * can fail if those validity checks fail (among other reasons).
+ * Set external_coins if the coins in view were not taken from a UTXO set. */
bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
- CCoinsViewCache& view, bool fJustCheck)
+ CCoinsViewCache& view, bool fJustCheck, bool external_coins)
{
AssertLockHeld(cs_main);
assert(pindex);
@@ -2571,7 +2572,10 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
if (!tx.IsCoinBase() && fScriptChecks)
{
- bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
+ // Script execution cache entries only commit to the transaction, not
+ // to the coins it spends, so don't cache results computed from
+ // external coins, which may not match the outputs they claim to be.
+ bool fCacheResults = fJustCheck && !external_coins; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
bool tx_ok;
TxValidationState tx_state;
// If CheckInputScripts is called with a pointer to a checks vector, the resulting checks are appended to it. In that case
@@ -4501,7 +4505,7 @@ BlockValidationState ChainstateManager::ValidateBlock(
// Needs to be mutable for ConnectBlock, but is not actually mutated with fJustCheck
CBlockIndex* index_mut{const_cast<CBlockIndex*>(&index)};
- if (!ActiveChainstate().ConnectBlock(block, state, index_mut, coins, /*fJustCheck=*/true)) {
+ if (!ActiveChainstate().ConnectBlock(block, state, index_mut, coins, /*fJustCheck=*/true, /*external_coins=*/true)) {
if (state.IsValid()) NONFATAL_UNREACHABLE();
return state;
}
diff --git a/src/validation.h b/src/validation.h
index 1800f48b6e..33d87b140d 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -787,7 +787,7 @@ public:
DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
- CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
+ CCoinsViewCache& view, bool fJustCheck = false, bool external_coins = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
// Apply the effects of a block disconnection on the UTXO set.
bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); |
|
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 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. diffdiff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index dbbd1cd330..f8128bc3f9 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -519,6 +519,7 @@ class CoinsViewBlock : public CCoinsViewCache
private:
btck_FetchCoin m_coin_fetcher;
void* m_user_data;
+ int m_block_height;
// Omit any queries for the self-spends as done by the BIP30 checks - we don't have enough information for them anyway.
std::unordered_set<Txid, SaltedTxidHasher> m_block_txids;
@@ -529,14 +530,18 @@ private:
if (!coin) return std::nullopt;
std::optional<Coin> result{std::move(btck_Coin::get(coin))};
delete coin;
+ // The block can only spend coins created by its ancestors. Validation
+ // relies on this, e.g. to look up the coin's block for BIP68 checks.
+ if (result->nHeight >= m_block_height) return std::nullopt;
return result;
}
public:
- CoinsViewBlock(const CBlock& block, btck_FetchCoin coin_fetcher, void* user_data)
+ CoinsViewBlock(const CBlock& block, int block_height, btck_FetchCoin coin_fetcher, void* user_data)
: CCoinsViewCache(&CoinsViewEmpty::Get()),
m_coin_fetcher{coin_fetcher},
- m_user_data{user_data}
+ m_user_data{user_data},
+ m_block_height{block_height}
{
SetBestBlock(block.hashPrevBlock);
@@ -1518,7 +1523,7 @@ int btck_chainstate_manager_validate_block(
const CBlock& block{*btck_Block::get(_block)};
try {
- CoinsViewBlock coins{block, coin_fetcher, user_data};
+ CoinsViewBlock coins{block, btck_BlockTreeEntry::get(entry).nHeight, coin_fetcher, user_data};
auto& chainman{*btck_ChainstateManager::get(chainstate_manager).m_chainman};
btck_BlockValidationState::get(state) = chainman.ValidateBlock(block, btck_BlockTreeEntry::get(entry), coins);
} catch (const std::exception& e) {
diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h
index e5e0a35598..f3e70595f9 100644
--- a/src/kernel/bitcoinkernel.h
+++ b/src/kernel/bitcoinkernel.h
@@ -1349,9 +1349,10 @@ BITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT bt
*
* This validates the block against the caller's supplied coins without
* requiring a full UTXO set or mutating the chainstate. The supplied coins
- * must be unspent. Coins created and consumed within the same block are
- * ignored. BIP-30 violating transactions cannot be detected through this
- * function.
+ * must be unspent. Coins with a confirmation height at or above the block's
+ * height are treated as missing. Coins created and consumed within the same
+ * block are ignored. BIP-30 violating transactions cannot be detected through
+ * this function.
*
* @param[in] chainstate_manager Non-null.
* @param[in] block Non-null.
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index 6b747274f3..a39517369a 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -1207,6 +1207,8 @@ private:
public:
BlockSpentCoinFetcher() = default;
+ explicit BlockSpentCoinFetcher(std::vector<std::pair<OutPoint, Coin>> coins) : m_coins{std::move(coins)} {}
+
BlockSpentCoinFetcher(const Block& block, const BlockSpentOutputs& block_spent_outputs)
{
size_t undo_index{0};
@@ -1471,6 +1473,42 @@ BOOST_AUTO_TEST_CASE(btck_chainman_regtest_tests)
BOOST_CHECK_THROW(chainman->ReadBlockSpentOutputs(tip), std::runtime_error);
}
+// Block at height 1 building on the regtest genesis block. Its second
+// transaction spends an unknown output with a time-based BIP68 relative lock.
+constexpr std::string_view REGTEST_RELATIVE_TIME_LOCK_BLOCK{
+ "0400000006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fad357294b85e86305604980667ac20f4a9e49796aa67f6b3415c9235e8c457eadbe5494dffff7f20"
+ "010000000202000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000015100000000020000000115cd5b07"
+ "00000000000000000000000000000000000000000000000000000000000000000000004000010100000000000000015100000000"};
+
+BOOST_AUTO_TEST_CASE(btck_chainman_validate_block_coin_height_tests)
+{
+ auto test_directory{TestDirectory{"validate_block_coin_height_test_bitcoin_kernel"}};
+ auto notifications{std::make_shared<TestKernelNotifications>()};
+ auto context{create_context(notifications, ChainType::REGTEST)};
+ auto chainman{create_chainman(
+ test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
+ /*block_tree_db_in_memory=*/true, /*chainstate_db_in_memory=*/true, context)};
+
+ Block block{hex_string_to_byte_vec(REGTEST_RELATIVE_TIME_LOCK_BLOCK)};
+ BOOST_CHECK_EQUAL(chainman->ProcessBlockHeader(block.GetHeader()).GetValidationMode(), ValidationMode::VALID);
+ BlockTreeEntry entry{*chainman->GetBlockTreeEntry(block.GetHash())};
+ OutPoint spent{block.GetTransaction(1).GetInput(0).OutPoint()};
+
+ auto validate_with_coin_height{[&](uint32_t coin_height) {
+ Coin coin{TransactionOutput{ScriptPubkey{hex_string_to_byte_vec("51")}, 1}, coin_height, /*is_coinbase=*/false};
+ BlockSpentCoinFetcher coin_fetcher{{{spent, coin}}};
+ BlockValidationState state;
+ chainman->ValidateBlock(block, entry, coin_fetcher, state);
+ return state.GetValidationMode();
+ }};
+
+ BOOST_CHECK_EQUAL(validate_with_coin_height(0), ValidationMode::VALID);
+ // Coins must have been created below the block's height. Otherwise, they
+ // are treated as missing instead of breaking assumptions in validation.
+ BOOST_CHECK_EQUAL(validate_with_coin_height(1), ValidationMode::INVALID);
+ BOOST_CHECK_EQUAL(validate_with_coin_height(std::numeric_limits<int32_t>::max()), ValidationMode::INVALID);
+}
+
// -----------------------------------------------------------------------------
// CheckTransaction tests
// |
|
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. |
|
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). |
This adds an API endpoint for validating a block without having the full utxo set present. To validate a block in such a fashion, its block header needs to be processed first. The spent coins are passed to the function with a callback, which is invoked for each output spent by the block (excluding outputs previously created by the block). The introduced block validation function then validates the block through `CheckBlock`, `ContextualCheckBlock`, and `ConnectBlock`.
f816f17 to
ed76d29
Compare
| const CBlockIndex& index, | ||
| CCoinsViewCache& coins) | ||
| { | ||
| LOCK(cs_main); |
There was a problem hiding this comment.
Could the coins be fetched before taking cs_main? The block already lists its prevouts as such ValidateBlock could 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.
| * | ||
| * This validates the block against the caller's supplied coins without | ||
| * requiring a full UTXO set or mutating the chainstate. The supplied coins | ||
| * must be unspent. Coins created and consumed within the same block are |
There was a problem hiding this comment.
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_coinbase set to 0, and w0xlt's height check wouldn't catch it.
|
|
||
| // Needs to be mutable for ConnectBlock, but is not actually mutated with fJustCheck | ||
| CBlockIndex* index_mut{const_cast<CBlockIndex*>(&index)}; | ||
| if (!ActiveChainstate().ConnectBlock(block, state, index_mut, coins, /*fJustCheck=*/true)) { |
There was a problem hiding this comment.
My opinion is to have ValidateBlock always 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).

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.