Repository navigation
Conversation
SWvheerden
left a comment
There was a problem hiding this comment.
Thanks for this. The body-tip bound on sync_utxos_by_block is a real gap on development, and so is the horizon-sync output rebuild window. Your follow-up commit does handle the rebuild window Greptile raised: we traced every horizon-sync write phase (the reset to genesis, the mid-tranche batch commits, checkpointed tranches, the final tranche through to finalize_horizon_sync), and committed_outputs_are_consistent fails closed in each of them.
Part of this PR is already on development, though, and the branch no longer merges. We'd like the following changes before we can merge it.
Required
1. Rebase onto development and drop the reorg check that is already there.
Both files now conflict.
- #8352 already reads the outputs and both chain headers under one read lock in
fetch_block_on_requested_chain, so the mid-stream reorg check here duplicates it. - #8400 moved
is_on_requested_chainintochain_storageand addedread_on_requested_chain/NotServedas the shared per-block check for streamed block data. The import frombase_node::sync::rpcno longer exists.
2. Build the sync_utxos_by_block body-tip bound on #8400's helper, not a second copy of it.
sync_utxos_by_block_task.rs:247-290 builds the "end height <= best block height" check and the chain check by hand, inside a spawn_blocking in the RPC layer. Instead:
- Add
BlockchainDatabase::fetch_outputs_in_block_on_chain(height, hash, end_height, end_hash)next tofetch_txos_in_block_on_chain/fetch_kernels_in_block_on_chain, built onread_on_requested_chain. It then gets the same single-guard read and the same body-tip bound. - Map
NotServedthe way the sync RPC does.BodyNotStoredbecomesConflictwith the "end block's body is not stored" text, logged at debug.NotOnChainbecomes the reorgConflict, logged at warn. At the moment a header-only end block is reported as "no longer an ancestor" at warn, so any peer can trigger that warning whenever it likes. - The output-rebuild check (
committed_outputs_are_consistent) can run inside the same guard in that chain_storage function, either as an extraNotServedreason or as a separate check. Your call. fetch_outputs_in_block_and_header_pairhas no callers after this, so please remove it.- In
validate, a start or end header that is stored but above the best block currently returnsnot_found("... was not found")(sync_utxos_by_block_task.rs:124-128). Please return the same body-not-storedConflictthere, so clients can tell "unknown hash" apart from "not served yet".
3. Drop the submit_transaction change and keep development's classify_spent_rejection (#8405) as it is.
service.rs:478-493 now answers DoubleSpend when the mempool says the kernel is already mined, but the kernel's block is above the committed tip. Two things make that a problem:
- The mempool's duplicate-kernel check does not filter by tip (
aggregate_body_chain_validator.rs:234-247). - After a failed horizon sync, a node that has bootstrapped before reports
is_synced = trueagain (listening.rs:660-670) while the staged kernels are still stored.
So a wallet that rebroadcasts a transaction which really was mined gets DoubleSpend with is_synced = true, and transaction_broadcast_protocol.rs:262-312 cancels it. The old answer, AlreadyMined, was the right one here: the kernel exists. There is also no test for this path.
4. Put the committed-snapshot reads in chain_storage, not the RPC service.
with_read_db, fetch_committed_unspent_outputs, fetch_committed_outputs_mined_info, query_committed_deleted and the related helpers reach into db.inner().db_read_access() from service.rs. They also re-implement fetch_outputs_with_spend_status_at_tip (including the JMT lookup) and fetch_latest_mined_infos.
- Please add the tip bound and the rebuild check to
BlockchainDatabasemethods instead, either by changing those existing methods or by adding siblings next to them. - The RPC handlers then keep calling
AsyncBlockchainDb, the same way #8400 handled the sync RPC. - This also lets the HTTP wallet query service (
query_service.rs) reuse the same methods later. The in-tree wallet now scans and validates over HTTP, which reads the same tables without these bounds. That is out of scope for this PR, but it's a reason to keep the logic in one place.
5. Remove changes the fix does not need.
To keep the diff reviewable, please drop the unrelated refactors:
- the
is_synced()helper and thetx_location_from_mempoolsplit; - the
bad_request(&"...".to_string())→bad_request("...")cleanups; - the
utxo.output.try_into()?rewrite inutxo_query.
Each of these is fine as a separate cleanup PR.
Smaller points
fetch_committed_header_by_hashre-hashes the header it just looked up by hash (header.hash() != *hash), once per output inutxo_query/query_deleted. The index is keyed by that hash, so the height check is enough.- In
fetch_latest_committed_outputandsanitize_committed_mined_info,info.mined_height <= tip_heightrepeats the height check thatfetch_committed_header_by_hashalready does.
Checked
cargo +nightly-2026-06-01 fmt --checkis clean. (The current default nightly only flags files this PR doesn't touch.)cargo lints clippy --all-targets --all-features -p tari_coreshows nothing in the touched files.- Decoder parity check passes.
cargo test -p tari_core --lib base_node::rpc -- --test-threads=1passes 30/30. All of these were run at the PR head, because it doesn't merge ontodevelopment.- There is no consensus, DB or proto change.
ConflictandNotFoundalready exist for released clients.
Please keep the new tests after the rebase: the header-above-tip, rewind-then-resync, staged outputs/kernels and rebuild cases are all worth having.
e575517 to
8cfb3c1
Compare
|
Thanks for the detailed review @SWvheerden! I've rebased onto current
|
0032117 to
c644942
Compare
SWvheerden
left a comment
There was a problem hiding this comment.
Thanks for the rework. Round 1 is addressed. The submit_transaction DoubleSpend change and the unrelated refactors are gone. fetch_outputs_in_block_on_chain is now built on read_on_requested_chain, and BodyNotStored maps to END_BODY_NOT_STORED with a debug log. The committed-read helpers live in BlockchainDatabase and each runs under one read lock. The horizon-rebuild gate (committed_outputs_are_consistent) fails closed at every stage. The logic looks right, but the branch does not build, so it cannot go in as it is.
1. tari_core does not compile: the NotServed match is not exhaustive
base_layer/core/src/base_node/sync/rpc/service.rs:144: not_served_status matches only NotOnChain and BodyNotStored. Adding NotServed::OutputRebuild makes this a hard error (E0004). Greptile flagged this on 2026-11-21 and it is still there at 5a7d77c. Confirmed with cargo check -p tari_core --all-features on this head merged onto current development.
Please fix this by putting the mapping in one place instead of adding a fourth hand-written copy:
- Make
not_served_statusand its message constantspub(crate)in one module, for example next toNotServed, and add theOutputRebuild => OUTPUT_REBUILD_CONFLICT_MSGarm there. sync_utxos_by_block_task.rs:24-27re-declaresREORG_DETECTEDandEND_BODY_NOT_STOREDwith the same text.is_reorgcompares the text exactly, so the two copies would drift silently. Delete the copies and call the sharednot_served_statusfromvalidate(:61-67) and the stream loop (:136-153). Keep only the extra debug/warn logging locally.
2. Lib tests still call the removed fetch_outputs_in_block_and_header_pair
base_layer/core/src/chain_storage/blockchain_database.rs:7231 and :7237 (fetch_outputs_in_block_and_header_pair_reads_the_block_and_both_headers) still call the removed method, so the test target does not compile (E0599, also flagged by Greptile). Please replace it with a test of fetch_outputs_in_block_on_chain that covers:
- a block on chain returns its outputs;
- an end height above the tip returns
BodyNotStored; - an active checkpoint or root mismatch returns
OutputRebuild.
3. rustfmt
cargo +nightly-2026-06-01 fmt --all -- --check fails in:
base_node/rpc/service.rs:670(test imports);chain_storage/async_db.rs:62(import order);chain_storage/blockchain_database.rs:1748(match arm infetch_committed_kernel_info).
4. Old output-read functions are now dead and duplicated by the new ones
BlockchainDatabase::fetch_outputs_mined_info(blockchain_database.rs:1550) andfetch_latest_mined_infos(:1567), plus theirasync_db.rs:207-218wrappers, have no callers left. Please delete them.fetch_committed_unspent_outputscopiesfetch_outputs_with_spend_status_at_tip(:1502): the same "latest bymined_height" pick and the same JMT lookup, with a tip filter added.fetch_outputs_with_spend_status_at_tipis still used byquery_service.rs:654andinbound_handlers.rs:416. That leaves two copies of one logic, one guarded and one not. Please have both use one helper that takestip_height(the old function can passu64::MAXor the tip), so a later fix lands in one place.
This is the Round 1 ask to move the reads into chain storage without duplicating the existing readers.
Once 1-3 are fixed, please run cargo lints clippy --all-targets --all-features -p tari_core and the base_node::rpc / chain_storage lib tests. I could not run them here because the crate does not compile.
Non-blocking:
fetch_committed_unspent_outputstreats an output as unspent if its commitment key is in the JMT. It never checks that the leaf belongs to this output. If output H1 (commitment C) is spent and a later H2 reuses C (consensus only rejects duplicates in the unspent set), H1 reads as unspent. This bug predates the PR, but the function is being rewritten. Comparing the stored value withoutput.smt_hash(mined_height)in the shared helper from item 4 would fix it on every path.transaction_batch_querystill reads the batch-level metadata in a separate snapshot from the per-kernelfetch_committed_kernel_infocalls. It is cosmetic, because the wallet uses its own tip, but a batched committed read would finish the job.committed_outputs_are_consistentreturnsfalsesilently when the root does not match and no checkpoint is set. Awarn!in that case would make a stuck node visible instead of a quiet stream ofConflictreplies.- The new
pubtype aliases andfetch_committed_*functions can bepub(crate). - The HTTP
query_service.rspaths are still unguarded. That is fine as a follow-up, but please say in the PR description that only the P2PBaseNodeWalletRpcServiceis covered. - Clash: your #8364 extends
fetch_outputs_in_block_and_header_pairto a 4-tuple, and this PR deletes that function. The two conflict insync_utxos_by_block_task.rsandasync_db.rs. Whichever merges second has to be rebased. If #8364 lands first, its best-height bound should move ontofetch_outputs_in_block_on_chain/read_on_requested_chain, which already bounds the body tip.
5a7d77c to
4ca1c87
Compare
|
Thanks @SWvheerden! Fixed all 4 blocking items and the non-blocking items:
|
b96747e to
d48066d
Compare
5ba047c to
d48066d
Compare
80c8a0f to
d48066d
Compare
SWvheerden
left a comment
There was a problem hiding this comment.
Thanks for working through the last round. Most of the earlier points are fixed: not_served_status now covers every case and the duplicate constants are gone, the stale test is replaced, the dead fetch_outputs_mined_info / fetch_latest_mined_infos are removed, and spend status now shares one helper that compares the JMT leaf value. The design looks right. Each fetch_committed_* reads under one lock, and the rebuild gate fails closed in every horizon-sync phase.
The new head still does not build, though, so this needs another round.
Required
-
It does not compile (
cargo check -p tari_core --all-targets --all-features). There are five errors:chain_storage/mod.rs:46-47: E0365.pub usere-exportsCommittedOutputsMinedInfo/CommittedQueryDeletedResult, but both are declaredpub(crate). Move them to apub(crate) useline.base_node/rpc/service.rs:33,:681andrpc/sync_utxos_by_block_task.rs:18: E0603.base_node::sync::rpc::serviceis a private module (mod service;insync/rpc/mod.rs). Addpub(crate) use service::{not_served_status, END_BODY_NOT_STORED, OUTPUT_REBUILD_CONFLICT_MSG, REORG_DETECTED};insync/rpc/mod.rsand import them fromcrate::base_node::sync::rpc.chain_storage/blockchain_database.rs:3326: E0308.smt.get(..)returnsOption<Vec<u8>>, so.as_ref() != Some(expected_value.as_slice())comparesOption<&Vec<u8>>withOption<&[u8]>. Use.as_deref().
Please run
cargo check --all-targetsand thechain_storage/base_node::rpctests before pushing. Greptile flagged two of these errors on the previous head. -
rustfmt (CI toolchain nightly-2026-06-01) still fails at
base_node/rpc/service.rs:676, in the test-moduleuse crate::{base_node::{...}}block. -
transaction_batch_querystill mixes snapshots (rpc/service.rs:326-351). The batch-levelbest_block_hash/best_block_height/tip_mined_timestampcome from a separateget_chain_metadata(). Each signature then takes its own lock throughfetch_kernel→fetch_committed_kernel_info. A block or reorg between those reads can return an entry mined above the reported tip, or confirmations counted against a different tip. This PR's goal is one committed snapshot per wallet query. Please add one batchedBlockchainDatabasemethod that reads the metadata once and resolves every kernel against that tip under a singledb_read_access(), the same wayfetch_committed_latest_mined_infosdoes. Use its metadata for the batch fields and for each entry's confirmations. -
Test the new spent check.
fetch_outputs_with_spend_status_up_tonow reports spent when the leaf differs fromsmt_hash(mined_height), not only when the key is missing. This is shared code: the HTTPget_utxo(query_service.rs:654) and the inboundFetchMatchingUtxoshandler (inbound_handlers.rs:416) call it too. No test fails if the check is reverted, or if it is broken so that live outputs read as spent. Onechain_storagetest is enough: mine output X, spend it, then mine Y with the same commitment at a higher height. Assert that X reads as spent and Y as unspent.
Should fix
- The root-mismatch
warn!incommitted_outputs_are_consistent(blockchain_database.rs:3270) runs on every wallet RPC call. After a failed horizon-sync attempt,discard_synced_outputs(synchronizer.rs:630-637) clears the checkpoint and resets outputs to genesis while the tip stays put. The mismatch then lasts until the next attempt passes its first tranche, so any peer can looputxo_query/query_deleted/sync_utxos_by_blockand add one WARN line per request. That is my fault, since I asked for the warning last round. Please log it atdebug!on these read paths, or only when the (best hash, root) pair changes. Also movesync_utxos_by_block_task.rs:141todebug!, since the peer already gets the Conflict.
Merge order
This conflicts with #8364 (same author, approved) in sync_utxos_by_block_task.rs, async_db.rs and blockchain_database.rs. #8364 adds a fourth return value to fetch_outputs_in_block_and_header_pair, and two new callers of it in base_node_grpc_server.rs and inbound_handlers.rs. This PR deletes that function. Once #8364 merges, please rebase and keep the function for those callers; only sync_utxos_by_block should move to fetch_outputs_in_block_on_chain. There is also a small textual conflict with #8365 next to the constants in sync/rpc/service.rs.
Follow-up (not for this PR)
The HTTP wallet query service (query_service.rs: fetch_kernel, get_utxos_mined_info, get_utxos_deleted_info, get_utxo, get_header_by_height) still reads without the committed-tip bound or the rebuild gate. The in-tree wallet uses that path, so please open a follow-up that routes it through the new fetch_committed_* helpers.
7b47d68 to
e3526cf
Compare
|
Thanks @SWvheerden! Rebased onto current
|
SWvheerden
left a comment
There was a problem hiding this comment.
Thanks for the update. Every point from the last round is addressed: it compiles now, transaction_batch_query reads one snapshot through fetch_committed_kernels_info, the rebuild log is at debug!, and fetch_outputs_in_block_and_header_pair is kept for #8364. The design is still right.
But the new spent check reports every unspent output as spent, and two of this PR's own tests fail because of it. CI would also fail on clippy and rustfmt.
Required
-
The leaf-value spent check marks every live output as spent (
chain_storage/blockchain_database.rs:3360-3365,fetch_outputs_with_spend_status_up_to).
The JMT value table does not hold the rawsmt_hash.LmdbTreeWriter::write_node_batch(lmdb_db/lmdb_tree_writer.rs:103-105) storesbincode::serialize(value)of theOption<Vec<u8>>, andlmdb_insertserialises that again.get_value_option(lmdb_tree_reader.rs:67) decodes only once. Sosmt.get(..)returns the bincodeOptionenvelope (tag + length + 32 bytes), which never equalsSome(expected_value.as_slice()), andspentis alwaystrue.
Effect:fetch_matching_utxosreturns no outputs, and the sharedfetch_outputs_with_spend_status_at_tipreports every output as spent to its other callers (inboundFetchMatchingUtxos/ gRPC).cargo test -p tari_core --libfails on:chain_storage::blockchain_database::test::fetch_outputs_with_spend_status_at_tip_checks_smt_leaf_value_when_commitment_is_reused(:7289: the unspent X comes backtrue)base_node::rpc::service::test::wallet_utxo_queries_ignore_uncommitted_horizon_staged_outputs(rpc/service.rs:1027: 0 outputs instead of 1)
Please compare against the decoded value: decode the returned bytes as
Option<Vec<u8>>(or compare with the bincode encoding ofSome(smt_hash)), and keep the change on the read side. Do not change the writer, because that changes the on-disk format of existing databases. Do not fall back to.is_none()either, since that brings back the commitment-reuse misreport the new test covers. -
clippy fails (
cargo lints clippy --all-targets --all-features -p tari_core):clippy::too_many_lines(103/100) onSyncUtxosByBlockTask::start_streaming(rpc/sync_utxos_by_block_task.rs:90). The header lookup that used to live infetch_block_on_requested_chainis now inlined. Move it back into a small helper (for examplefetch_header_at(height, &start_header)) rather than adding anallow. -
rustfmt (CI toolchain
nightly-2026-06-01) still fails at:chain_storage/mod.rs:63-67: thepub(crate) use blockchain_database::{...}fits on one line.chain_storage/blockchain_database.rs:7288:let initial = db.fetch_outputs_with_spend_status_at_tip(...)needs to be a method chain.
Please run cargo +nightly-2026-06-01 fmt --all, cargo lints clippy --all-targets --all-features -p tari_core, and cargo test -p tari_core --lib -- base_node::rpc chain_storage::blockchain_database before pushing.
Should fix
- Duplicated kernel lookup.
fetch_committed_kernel_info(blockchain_database.rs:1691-1706) is a line-for-line copy offetch_committed_kernels_infofor one signature, with its own async wrapper (async_db.rs:313-317). Remove it and havefetch_kernelcallfetch_committed_kernels_info(vec![signature]), so the committed-kernel rule lives in one place. - Test the dropped uncommitted spend in
query_deleted.sanitize_committed_mined_info(blockchain_database.rs:3377-3396) now drops an input mined above the tip, but the staged fixture only stages outputs. Please add an input at the synced-ahead block that spends one of B's outputs, and assertquery_deleted(withchain_must_include_header = B) returnsheight_deleted_at == 0and an emptyblock_deleted_in.
Merge order
#8365 is approved and conflicts with this PR in base_node/sync/rpc/service.rs, next to the constants. If it merges first, please rebase on top of it.
|
Thanks @SWvheerden! Pushed
|
04c5bf7 to
71cec6d
Compare
71cec6d to
ff58cd1
Compare
…rged wallet RPC reads
Description
Bounds P2P
BaseNodeWalletRpcServicereads (sync_utxos_by_block,get_header,get_header_by_height,fetch_kernel,fetch_matching_utxos,utxo_query, andquery_deleted) to committed chain snapshots inchain_storageand fails closed withRpcStatus::conflictwhen horizon sync is rebuilding committed output state (Note: only the P2PBaseNodeWalletRpcServiceis covered here; HTTPquery_service.rspaths can follow in a separate PR):NotServedmapping:NotServed::OutputRebuildand makesnot_served_status,REORG_DETECTED,END_BODY_NOT_STORED, andOUTPUT_REBUILD_CONFLICT_MSGpub(crate)inbase_node::sync::rpc::servicesoSyncUtxosByBlockTaskshares the single mapping.chain_storageoutput readers:fetch_outputs_with_spend_status_up_tobetweenfetch_outputs_with_spend_status_at_tipandfetch_committed_unspent_outputs(checkingsmt_hash(mined_height)against the JMT leaf value) and removes the unusedfetch_outputs_mined_infoandfetch_latest_mined_infoswrappers.fetch_outputs_in_block_and_header_pairwithfetch_outputs_in_block_on_chainand its unit testfetch_outputs_in_block_on_chain_checks_chain_tip_and_output_rebuild.

Confidence Score: 5/5
The PR appears safe to merge; both previously reported visibility errors are fixed, and no new blocking issue was found.Summary
Bounds P2P wallet reads to committed chain state.
No new actionable issues were found. Tests were inspected but not run.
Reviews (4) · Last reviewed commit: "fix(core): bound P2P wallet RPC reads to..." · Reviewed by Greptile