From 0630e9d7eedd78d3cef89a493f1da16db39b8c41 Mon Sep 17 00:00:00 2001 From: "M. ASWADI" Date: Thu, 26 Nov 2026 21:35:08 +0700 Subject: [PATCH] fix(core): prevent serving uncommitted horizon-staged outputs and reorged wallet RPC reads --- base_layer/core/src/base_node/rpc/service.rs | 639 +++++++++++++++--- .../base_node/rpc/sync_utxos_by_block_task.rs | 96 +-- base_layer/core/src/base_node/sync/rpc/mod.rs | 3 + .../core/src/base_node/sync/rpc/service.rs | 9 +- base_layer/core/src/chain_storage/async_db.rs | 59 +- .../src/chain_storage/blockchain_database.rs | 404 +++++++++-- base_layer/core/src/chain_storage/mod.rs | 1 + 7 files changed, 998 insertions(+), 213 deletions(-) diff --git a/base_layer/core/src/base_node/rpc/service.rs b/base_layer/core/src/base_node/rpc/service.rs index 89fcf97598..ee825593c5 100644 --- a/base_layer/core/src/base_node/rpc/service.rs +++ b/base_layer/core/src/base_node/rpc/service.rs @@ -7,11 +7,15 @@ use std::{ }; use log::*; -use tari_common_types::types::{CompressedSignature, FixedHash}; +use tari_common_types::{ + chain_metadata::ChainMetadata, + types::{CompressedSignature, FixedHash}, +}; use tari_comms::{ peer_manager::NodeId, protocol::rpc::{Request, Response, RpcStatus, RpcStatusResultExt, Streaming}, }; +use tari_node_components::blocks::BlockHeader; use tari_transaction_components::transaction_components::Transaction; use tari_utilities::hex::Hex; use tokio::sync::{Mutex, mpsc}; @@ -30,8 +34,9 @@ use crate::{ sync_utxos_by_block_task::SyncUtxosByBlockTask, }, state_machine_service::states::StateInfo, + sync::rpc::OUTPUT_REBUILD_CONFLICT_MSG, }, - chain_storage::{BlockchainBackend, async_db::AsyncBlockchainDb}, + chain_storage::{BlockchainBackend, NotServed, async_db::AsyncBlockchainDb}, mempool::{TxStorageResponse, service::MempoolHandle}, proto, proto::{ @@ -131,7 +136,6 @@ impl BaseNodeWalletRpcService { async fn fetch_kernel(&self, signature: CompressedSignature) -> Result { let db = self.db(); - let chain_metadata = db.get_chain_metadata().await.rpc_status_internal_error(LOG_TARGET)?; let state_machine = self.state_machine(); // Determine if we are synced @@ -140,39 +144,39 @@ impl BaseNodeWalletRpcService { StateInfo::Listening(li) => li.is_synced(), _ => false, }; - match db - .fetch_kernel_by_excess_sig(signature.clone()) + let (chain_metadata, mut mined_kernels) = db + .fetch_committed_kernels_info(vec![signature.clone()]) .await - .rpc_status_internal_error(LOG_TARGET)? - { - None => (), - Some((_, block_hash)) => { - match db - .fetch_header_by_block_hash(block_hash) - .await - .rpc_status_internal_error(LOG_TARGET)? - { - None => (), - Some(header) => { - let confirmations = chain_metadata.best_block_height().saturating_sub(header.height); - let response = TxQueryResponse { - location: TxLocation::Mined as i32, - best_block_hash: block_hash.to_vec(), - confirmations, - is_synced, - best_block_height: chain_metadata.best_block_height(), - mined_timestamp: header.timestamp.as_u64(), - }; - return Ok(response); - }, - } - }, - }; + .rpc_status_internal_error(LOG_TARGET)?; + let mined = mined_kernels.pop().flatten(); + self.resolve_kernel_query(signature, &chain_metadata, mined, is_synced) + .await + } + + async fn resolve_kernel_query( + &self, + signature: CompressedSignature, + chain_metadata: &ChainMetadata, + mined: Option<(FixedHash, BlockHeader)>, + is_synced: bool, + ) -> Result { + if let Some((block_hash, header)) = mined { + let confirmations = chain_metadata.best_block_height().saturating_sub(header.height); + let response = TxQueryResponse { + location: TxLocation::Mined as i32, + best_block_hash: block_hash.to_vec(), + confirmations, + is_synced, + best_block_height: chain_metadata.best_block_height(), + mined_timestamp: header.timestamp.as_u64(), + }; + return Ok(response); + } // If not in a block then check the mempool let mut mempool = self.mempool(); let mempool_response = match mempool - .get_tx_state_by_excess_sig(signature.clone()) + .get_tx_state_by_excess_sig(signature) .await .rpc_status_internal_error(LOG_TARGET)? { @@ -333,18 +337,24 @@ impl BaseNodeWalletService for BaseNodeWalletRpc ))); } - let mut responses: Vec = Vec::with_capacity(message.sigs.len()); + let signatures: Vec = message + .sigs + .into_iter() + .map(CompressedSignature::try_from) + .collect::>() + .map_err(|_| RpcStatus::bad_request("Signature was invalid"))?; - let metadata = self + let (metadata, mined_kernels) = self .db - .get_chain_metadata() + .fetch_committed_kernels_info(signatures.clone()) .await .rpc_status_internal_error(LOG_TARGET)?; - for sig in message.sigs { - let signature = - CompressedSignature::try_from(sig).map_err(|_| RpcStatus::bad_request("Signature was invalid"))?; - let response: TxQueryResponse = self.fetch_kernel(signature.clone()).await?; + let mut responses: Vec = Vec::with_capacity(signatures.len()); + for (signature, mined) in signatures.into_iter().zip(mined_kernels) { + let response = self + .resolve_kernel_query(signature.clone(), &metadata, mined, is_synced) + .await?; responses.push(TxQueryBatchResponse { signature: Some(SignatureProto::from(&signature)), location: response.location, @@ -386,24 +396,17 @@ impl BaseNodeWalletService for BaseNodeWalletRpc }; let db = self.db(); - let mut res = Vec::with_capacity(message.output_hashes.len()); let hashes: Vec = message .output_hashes .into_iter() .map(|hash| hash.try_into().map_err(|_| "Malformed pruned hash".to_string())) .collect::>() .map_err(|_| RpcStatus::bad_request(&"Malformed block hash received".to_string()))?; - let utxos = db - .fetch_outputs_with_spend_status_at_tip(hashes) + let res = db + .fetch_committed_unspent_outputs(hashes) .await .rpc_status_internal_error(LOG_TARGET)? - .into_iter() - .flatten(); - for (output, spent) in utxos { - if !spent { - res.push(output); - } - } + .ok_or_else(|| RpcStatus::conflict(OUTPUT_REBUILD_CONFLICT_MSG))?; Ok(Response::new(FetchUtxosResponse { outputs: res @@ -445,10 +448,11 @@ impl BaseNodeWalletService for BaseNodeWalletRpc hashes.iter().map(|h| h.to_hex()).collect::>() ); - let mined_info_resp = db - .fetch_outputs_mined_info(hashes) + let (metadata, mined_info_resp) = db + .fetch_committed_outputs_mined_info(hashes) .await - .rpc_status_internal_error(LOG_TARGET)?; + .rpc_status_internal_error(LOG_TARGET)? + .ok_or_else(|| RpcStatus::conflict(OUTPUT_REBUILD_CONFLICT_MSG))?; let num_mined = mined_info_resp.iter().filter(|opt| opt.is_some()).count(); debug!( @@ -457,11 +461,6 @@ impl BaseNodeWalletService for BaseNodeWalletRpc num_mined, mined_info_resp.len().saturating_sub(num_mined) ); - let metadata = self - .db - .get_chain_metadata() - .await - .rpc_status_internal_error(LOG_TARGET)?; Ok(Response::new(UtxoQueryResponses { best_block_height: metadata.best_block_height(), @@ -502,22 +501,15 @@ impl BaseNodeWalletService for BaseNodeWalletRpc ))); } let chain_include_header = message.chain_must_include_header; - if !chain_include_header.is_empty() { - let hash = chain_include_header - .try_into() - .map_err(|_| RpcStatus::bad_request(&"Malformed block hash received".to_string()))?; - if self - .db - .fetch_header_by_block_hash(hash) - .await - .rpc_status_internal_error(LOG_TARGET)? - .is_none() - { - return Err(RpcStatus::not_found( - "Chain does not include header. It might have been reorged out", - )); - } - } + let must_include_header = if chain_include_header.is_empty() { + None + } else { + Some( + chain_include_header + .try_into() + .map_err(|_| RpcStatus::bad_request(&"Malformed block hash received".to_string()))?, + ) + }; let hashes: Vec = message .hashes .into_iter() @@ -526,11 +518,20 @@ impl BaseNodeWalletService for BaseNodeWalletRpc .map_err(|_| RpcStatus::bad_request(&"Malformed utxo hash received".to_string()))?; let mut return_data = Vec::with_capacity(hashes.len()); // One read for all hashes; each entry's mined and spent halves describe the same lifecycle. - let infos = self + let (metadata, infos) = match self .db - .fetch_latest_mined_infos(hashes) + .fetch_committed_latest_mined_infos(hashes, must_include_header) .await - .rpc_status_internal_error(LOG_TARGET)?; + .rpc_status_internal_error(LOG_TARGET)? + { + Ok(res) => res, + Err(NotServed::OutputRebuild) => return Err(RpcStatus::conflict(OUTPUT_REBUILD_CONFLICT_MSG)), + Err(NotServed::NotOnChain | NotServed::BodyNotStored) => { + return Err(RpcStatus::not_found( + "Chain does not include header. It might have been reorged out", + )); + }, + }; for info in infos { let mut data = match &info.output { None => QueryDeletedData { @@ -552,11 +553,6 @@ impl BaseNodeWalletService for BaseNodeWalletRpc }; return_data.push(data); } - let metadata = self - .db - .get_chain_metadata() - .await - .rpc_status_internal_error(LOG_TARGET)?; Ok(Response::new(QueryDeletedResponse { best_block_height: metadata.best_block_height(), @@ -589,7 +585,7 @@ impl BaseNodeWalletService for BaseNodeWalletRpc let height = request.into_message(); let header = self .db() - .fetch_header(height) + .fetch_committed_header(height) .await .rpc_status_internal_error(LOG_TARGET)? .ok_or_else(|| RpcStatus::not_found(&format!("Header not found at height {height}")))?; @@ -604,7 +600,7 @@ impl BaseNodeWalletService for BaseNodeWalletRpc let height = request.into_message(); let header = self .db() - .fetch_header(height) + .fetch_committed_header(height) .await .rpc_status_internal_error(LOG_TARGET)? .ok_or_else(|| RpcStatus::not_found(&format!("Header not found at height {height}")))?; @@ -697,17 +693,24 @@ mod test { use tari_common::configuration::Network; use tari_comms::protocol::rpc::RpcStatusCode; use tari_shutdown::Shutdown; + use tari_utilities::ByteArray; use tokio::sync::{broadcast, watch}; use super::*; use crate::{ base_node::state_machine_service::states::StatusInfo, + chain_storage::{DbTransaction, HorizonStateTreeUpdate}, mempool::test_utils::{ covenant_over_token_limit, mock::create_mempool_service_mock, transaction_proto_with_covenant, }, - test_helpers::blockchain::create_new_blockchain_with_network, + test_helpers::blockchain::{ + create_chained_blocks, + create_main_chain, + create_new_blockchain, + create_new_blockchain_with_network, + }, }; /// The service has no connectivity handle, so it cannot ban: a rejection here is only ever a bad request @@ -765,6 +768,359 @@ mod test { assert!(data.block_deleted_in.is_empty()); } + #[tokio::test] + async fn get_header_rejects_synced_ahead_headers_until_block_is_committed() { + let db = create_new_blockchain(); + let (_, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"])); + let b = chain.get("B").unwrap().clone(); + let (_, future) = create_chained_blocks(&db, block_specs!(["C->GB"]), b); + let c = future.get("C").unwrap().clone(); + db.insert_valid_headers(vec![c.to_chain_header()]).unwrap(); + + let (mempool, _) = create_mempool_service_mock(); + let (state_tx, _state_rx) = broadcast::channel(10); + let (_status_tx, status_rx) = watch::channel(StatusInfo::new()); + let state_machine = StateMachineHandle::new(state_tx, status_rx, Shutdown::new().to_signal()); + let service = BaseNodeWalletRpcService::new(db.clone().into(), mempool, state_machine, None); + + assert_eq!( + service + .get_header(Request::new(0.into(), 2)) + .await + .unwrap() + .into_message() + .height, + 2 + ); + assert_eq!( + service + .get_header_by_height(Request::new(0.into(), 2)) + .await + .unwrap() + .into_message() + .height, + 2 + ); + assert_eq!( + service + .get_header(Request::new(0.into(), 3)) + .await + .unwrap_err() + .as_status_code(), + RpcStatusCode::NotFound + ); + assert_eq!( + service + .get_header_by_height(Request::new(0.into(), 3)) + .await + .unwrap_err() + .as_status_code(), + RpcStatusCode::NotFound + ); + + db.add_block(c.to_arc_block()).unwrap(); + assert_eq!( + service + .get_header(Request::new(0.into(), 3)) + .await + .unwrap() + .into_message() + .height, + 3 + ); + assert_eq!( + service + .get_header_by_height(Request::new(0.into(), 3)) + .await + .unwrap() + .into_message() + .height, + 3 + ); + } + + fn setup_staged_horizon_fixture() -> ( + BaseNodeWalletRpcService, + Arc, + Arc, + Arc, + ) { + let db = create_new_blockchain(); + let (_, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"])); + let a = chain.get("A").unwrap().clone(); + let b = chain.get("B").unwrap().clone(); + let b_output = b.block().body.outputs().first().unwrap().clone(); + let spend_b_input = tari_transaction_components::transaction_components::TransactionInput::new_current_version( + tari_transaction_components::transaction_components::SpentOutput::create_from_output(b_output.clone()), + Default::default(), + Default::default(), + ); + let spend_b_tx = Transaction::new( + vec![spend_b_input], + vec![], + vec![], + Default::default(), + Default::default(), + ); + let (_, future) = + create_chained_blocks(&db, block_specs!(["C->GB", transactions: vec![spend_b_tx]]), b.clone()); + let c = future.get("C").unwrap().clone(); + + // Simulate synced-ahead header C (#3) with an uncommitted staged input (spending B's output), output, and + // kernel while committed tip and JMT state remain at B (#2). + db.insert_valid_headers(vec![c.to_chain_header()]).unwrap(); + let staged_output = c.block().body.outputs().first().unwrap().clone(); + let b_key: [u8; 32] = b_output.commitment.as_bytes().try_into().unwrap(); + let c_key: [u8; 32] = staged_output.commitment.as_bytes().try_into().unwrap(); + let mut txn = DbTransaction::new(); + txn.insert_tip_block_body(c.clone()); + txn.apply_horizon_state_tree_updates(vec![ + HorizonStateTreeUpdate { + key: FixedHash::from(b_key), + value: Some(b_output.smt_hash(b.height())), + replaces_value: false, + }, + HorizonStateTreeUpdate { + key: FixedHash::from(c_key), + value: None, + replaces_value: false, + }, + ]); + db.write(txn).unwrap(); + + let (mempool, _) = create_mempool_service_mock(); + let (state_tx, _state_rx) = broadcast::channel(10); + let (_status_tx, status_rx) = watch::channel(StatusInfo::new()); + let state_machine = StateMachineHandle::new(state_tx, status_rx, Shutdown::new().to_signal()); + let service = BaseNodeWalletRpcService::new(db.into(), mempool, state_machine, None); + (service, a, b, c) + } + + async fn assert_wallet_output_queries_conflict( + service: &BaseNodeWalletRpcService, + output_hashes: &[Vec], + header_hash: FixedHash, + ) { + let err = service + .utxo_query(Request::new(0.into(), UtxoQueryRequest { + output_hashes: output_hashes.to_vec(), + })) + .await + .unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + + let err = service + .fetch_matching_utxos(Request::new(0.into(), FetchMatchingUtxos { + output_hashes: output_hashes.to_vec(), + })) + .await + .unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + + let err = service + .query_deleted(Request::new(0.into(), QueryDeletedRequest { + hashes: vec![output_hashes.first().unwrap().clone()], + chain_must_include_header: header_hash.to_vec(), + })) + .await + .unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + } + + #[tokio::test] + async fn wallet_output_queries_reject_reads_during_horizon_sync_output_rebuild() { + use crate::chain_storage::HorizonSyncOutputCheckpoint; + + let db = create_new_blockchain(); + let (_, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"])); + let gb = chain.get("GB").unwrap().clone(); + let a = chain.get("A").unwrap().clone(); + let b = chain.get("B").unwrap().clone(); + let output_a = a.block().body.outputs().first().unwrap().clone(); + let output_b = b.block().body.outputs().first().unwrap().clone(); + let hashes = vec![output_a.hash().to_vec(), output_b.hash().to_vec()]; + + let (mempool, _) = create_mempool_service_mock(); + let (state_tx, _state_rx) = broadcast::channel(10); + let (_status_tx, status_rx) = watch::channel(StatusInfo::new()); + let state_machine = StateMachineHandle::new(state_tx, status_rx, Shutdown::new().to_signal()); + let service = BaseNodeWalletRpcService::new(db.clone().into(), mempool, state_machine, None); + + // Simulate HorizonStateSynchronization::reset_output_state_to_genesis on a node with nonzero committed tip + // (#2): output tables and JMT are cleared and restored to genesis without lowering best_block_height. + let mut clear_txn = DbTransaction::new(); + clear_txn.clear_horizon_sync_output_state(); + db.write(clear_txn).unwrap(); + + let mut genesis_txn = DbTransaction::new(); + let mut genesis_updates = Vec::new(); + for output in gb.block().body.outputs() { + genesis_txn.insert_utxo(output.clone(), *gb.hash(), 0, gb.header().timestamp.as_u64()); + if !output.is_burned() { + genesis_updates.push(HorizonStateTreeUpdate { + key: FixedHash::try_from(output.commitment.as_bytes()).unwrap(), + value: Some(output.smt_hash(0)), + replaces_value: false, + }); + } + } + if !genesis_updates.is_empty() { + genesis_txn.apply_horizon_state_tree_updates(genesis_updates); + } + db.write(genesis_txn).unwrap(); + assert_eq!(db.get_chain_metadata().unwrap().best_block_height(), 2); + + // Phase 0: outputs wiped back to genesis while tip stays at #2 -> rejected with Conflict. + assert_wallet_output_queries_conflict(&service, &hashes, *b.hash()).await; + + // Phase 1: restore outputs/JMT up to B (#2), yet keep an active HorizonSyncOutputCheckpoint -> still rejected + // until finalize_horizon_sync clears the checkpoint! + let mut rebuild_txn = DbTransaction::new(); + let mut updates = Vec::new(); + for blk in [&a, &b] { + for output in blk.block().body.outputs() { + rebuild_txn.insert_utxo( + output.clone(), + *blk.hash(), + blk.height(), + blk.header().timestamp.as_u64(), + ); + updates.push(HorizonStateTreeUpdate { + key: FixedHash::try_from(output.commitment.as_bytes()).unwrap(), + value: Some(output.smt_hash(blk.height())), + replaces_value: false, + }); + } + for input in blk.block().body.inputs() { + updates.push(HorizonStateTreeUpdate { + key: FixedHash::try_from(input.commitment().unwrap().as_bytes()).unwrap(), + value: None, + replaces_value: false, + }); + } + } + rebuild_txn.apply_horizon_state_tree_updates(updates); + rebuild_txn.set_horizon_sync_output_checkpoint(HorizonSyncOutputCheckpoint { + checkpoint_height: b.height(), + checkpoint_hash: *b.hash(), + sync_target_height: b.height() + 5, + sync_target_hash: FixedHash::zero(), + }); + db.write(rebuild_txn).unwrap(); + assert_wallet_output_queries_conflict(&service, &hashes, *b.hash()).await; + + // Clearing the checkpoint once the JMT root matches best_block_hash (#2) restores normal reads. + let mut finalize_txn = DbTransaction::new(); + finalize_txn.clear_horizon_sync_output_checkpoint(); + db.write(finalize_txn).unwrap(); + + let utxo_resp = service + .utxo_query(Request::new(0.into(), UtxoQueryRequest { + output_hashes: vec![output_b.hash().to_vec()], + })) + .await + .unwrap() + .into_message(); + assert_eq!(utxo_resp.responses.len(), 1); + } + + #[tokio::test] + async fn wallet_utxo_queries_ignore_uncommitted_horizon_staged_outputs() { + let (service, _a, b, c) = setup_staged_horizon_fixture(); + let committed_output = b.block().body.outputs().first().unwrap().clone(); + let staged_output = c.block().body.outputs().first().unwrap().clone(); + + let utxo_resp = service + .utxo_query(Request::new(0.into(), UtxoQueryRequest { + output_hashes: vec![committed_output.hash().to_vec(), staged_output.hash().to_vec()], + })) + .await + .unwrap() + .into_message(); + assert_eq!(utxo_resp.best_block_height, 2); + assert_eq!(utxo_resp.responses.len(), 1); + assert_eq!( + utxo_resp.responses.first().unwrap().output_hash, + committed_output.hash().to_vec() + ); + + let matching_resp = service + .fetch_matching_utxos(Request::new(0.into(), FetchMatchingUtxos { + output_hashes: vec![committed_output.hash().to_vec(), staged_output.hash().to_vec()], + })) + .await + .unwrap() + .into_message(); + assert_eq!(matching_resp.outputs.len(), 1); + + let deleted_err = service + .query_deleted(Request::new(0.into(), QueryDeletedRequest { + hashes: vec![committed_output.hash().to_vec()], + chain_must_include_header: c.hash().to_vec(), + })) + .await + .unwrap_err(); + assert_eq!(deleted_err.as_status_code(), RpcStatusCode::NotFound); + + let deleted_resp = service + .query_deleted(Request::new(0.into(), QueryDeletedRequest { + hashes: vec![committed_output.hash().to_vec(), staged_output.hash().to_vec()], + chain_must_include_header: b.hash().to_vec(), + })) + .await + .unwrap() + .into_message(); + assert_eq!(deleted_resp.best_block_height, 2); + let committed_deleted = deleted_resp.data.first().unwrap(); + assert_eq!(committed_deleted.mined_at_height, 2); + assert_eq!(committed_deleted.block_mined_in, b.hash().to_vec()); + assert_eq!(committed_deleted.height_deleted_at, 0); + assert!(committed_deleted.block_deleted_in.is_empty()); + assert_eq!(deleted_resp.data.get(1).unwrap().mined_at_height, 0); + } + + #[tokio::test] + async fn wallet_tx_queries_ignore_uncommitted_horizon_staged_kernels() { + let (service, a, b, c) = setup_staged_horizon_fixture(); + let staged_kernel = c.block().body.kernels().first().unwrap(); + + let tx_resp = service + .transaction_query(Request::new(0.into(), SignatureProto::from(&staged_kernel.excess_sig))) + .await + .unwrap() + .into_message(); + assert_eq!(tx_resp.location, TxLocation::NotStored as i32); + assert_eq!(tx_resp.best_block_height, 2); + + let kernel_a = a.block().body.kernels().first().unwrap(); + let kernel_b = b.block().body.kernels().first().unwrap(); + let batch_resp = service + .transaction_batch_query(Request::new(0.into(), SignaturesProto { + sigs: vec![ + SignatureProto::from(&kernel_a.excess_sig), + SignatureProto::from(&kernel_b.excess_sig), + SignatureProto::from(&staged_kernel.excess_sig), + ], + })) + .await + .unwrap() + .into_message(); + assert_eq!(batch_resp.best_block_height, 2); + assert_eq!(batch_resp.best_block_hash, b.hash().to_vec()); + let first = batch_resp.responses.first().unwrap(); + assert_eq!(first.location, TxLocation::Mined as i32); + assert_eq!(first.confirmations, 1); + assert_eq!(first.best_block_height, 1); + let second = batch_resp.responses.get(1).unwrap(); + assert_eq!(second.location, TxLocation::Mined as i32); + assert_eq!(second.confirmations, 0); + assert_eq!(second.best_block_height, 2); + let third = batch_resp.responses.get(2).unwrap(); + assert_eq!(third.location, TxLocation::NotStored as i32); + assert_eq!(third.confirmations, 0); + assert_eq!(third.best_block_height, 2); + } + mod sync_utxos_by_block { use std::{collections::HashMap, time::Duration}; @@ -777,6 +1133,7 @@ mod test { use super::*; use crate::{ + base_node::sync::rpc::END_BODY_NOT_STORED, chain_storage::BlockchainDatabase, test_helpers::{ blockchain::{TempDatabase, create_chained_blocks, create_main_chain, create_new_blockchain}, @@ -1007,10 +1364,124 @@ mod test { for response in responses { let response = response.unwrap(); let name = ["A", "B", "C", "D"] - .get(usize::try_from(response.height - 1).unwrap()) + .get(usize::try_from(response.height.saturating_sub(1)).unwrap()) .unwrap(); assert_eq!(response.header_hash, chain.get(*name).unwrap().hash().to_vec()); } } + + #[tokio::test] + async fn it_rejects_synced_ahead_headers_with_body_not_stored_without_leaking_session() { + let (service, db, chain, mock) = setup(); + let a = chain.get("A").unwrap(); + let e = chain.get("E").unwrap(); + let (_, future) = create_chained_blocks(&db, block_specs!(["F->GB"]), e.clone()); + let f = future.get("F").unwrap(); + db.insert_valid_headers(vec![f.to_chain_header()]).unwrap(); + + let peer = new_peer(); + let err = open_stream(&service, &mock, peer.clone(), a, f).await.unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + assert_eq!(err.details(), END_BODY_NOT_STORED); + let err = open_stream(&service, &mock, peer.clone(), f, f).await.unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + assert_eq!(err.details(), END_BODY_NOT_STORED); + + // Peer session slot was never consumed by the rejected requests + let mut responses = open_stream(&service, &mock, peer, a, e).await.unwrap(); + assert_eq!(drain(&mut responses).await.len(), 5); + } + + #[tokio::test] + async fn it_sends_conflict_when_blocks_rewind_and_same_headers_resync_mid_stream() { + let (service, db, chain, mock) = setup(); + let service = service.with_max_buffered_bytes(1); + let a = chain.get("A").unwrap(); + let e = chain.get("E").unwrap(); + let peer = new_peer(); + let mut responses = open_stream(&service, &mock, peer.clone(), a, e).await.unwrap(); + wait_for_queued(&responses, 1).await; + + // Rewind committed blocks back to A (#1), then re-insert headers B..E as pending headers without bodies. + db.rewind_to_height(1).unwrap(); + let resynced_headers = ["B", "C", "D", "E"] + .iter() + .map(|name| chain.get(*name).unwrap().to_chain_header()) + .collect(); + db.insert_valid_headers(resynced_headers).unwrap(); + assert_eq!(db.get_chain_metadata().unwrap().best_block_height(), 1); + assert_eq!(db.fetch_header(5).unwrap().unwrap().hash(), *e.hash()); + + let mut drained = drain(&mut responses).await; + let err = drained.pop().unwrap().unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + assert_eq!(err.details(), END_BODY_NOT_STORED); + // Only blocks already fetched before the rewind (at most queued #1 and in-flight #2) were sent, all with + // real outputs — never empty uncommitted blocks C..E. + assert!(!drained.is_empty() && drained.len() <= 2, "{drained:?}"); + for (expected_height, response) in (1u64..).zip(drained) { + let response = response.unwrap(); + let name = ["A", "B"] + .get(usize::try_from(expected_height.saturating_sub(1)).unwrap()) + .unwrap(); + assert_eq!(response.height, expected_height); + assert_eq!(response.header_hash, chain.get(*name).unwrap().hash().to_vec()); + assert!(!response.outputs.is_empty()); + } + + // Session is released cleanly after the conflict. + let mut next = open_stream_when_released(&service, &mock, &peer, a, a).await; + assert_eq!(drain(&mut next).await.len(), 1); + } + + #[tokio::test] + async fn it_rejects_and_aborts_stream_during_horizon_sync_output_rebuild() { + let (service, db, chain, mock) = setup(); + let service = service.with_max_buffered_bytes(1); + let a = chain.get("A").unwrap(); + let e = chain.get("E").unwrap(); + let peer = new_peer(); + + // Open stream from A (#1) to E (#5) while outputs are consistent, and pause after queuing the first block. + let mut responses = open_stream(&service, &mock, peer.clone(), a, e).await.unwrap(); + wait_for_queued(&responses, 1).await; + + // Simulate horizon sync calling reset_output_state_to_genesis while best_block_height remains 5. + let mut txn = DbTransaction::new(); + txn.clear_horizon_sync_output_state(); + db.write(txn).unwrap(); + assert_eq!(db.get_chain_metadata().unwrap().best_block_height(), 5); + + // Active stream aborts with Conflict before sending any wiped empty blocks from the remaining range. + let mut drained = drain(&mut responses).await; + let err = drained.pop().unwrap().unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + assert_eq!(err.details(), OUTPUT_REBUILD_CONFLICT_MSG); + assert!(!drained.is_empty() && drained.len() <= 2, "{drained:?}"); + for response in drained { + assert!(!response.unwrap().outputs.is_empty()); + } + + // Wait for the closed stream's session token to drop, then verify new requests also reject in validate() + // without leaking the peer's session slot. + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let err = open_stream(&service, &mock, peer.clone(), a, e).await.unwrap_err(); + if err.as_status_code() == RpcStatusCode::Conflict { + assert_eq!(err.details(), OUTPUT_REBUILD_CONFLICT_MSG); + break; + } + assert_eq!(err.as_status_code(), RpcStatusCode::Forbidden); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + + // A second call from the same peer still gets Conflict (not Forbidden), proving validate() did not leak a + // session token. + let err = open_stream(&service, &mock, peer, a, e).await.unwrap_err(); + assert_eq!(err.as_status_code(), RpcStatusCode::Conflict); + } } } diff --git a/base_layer/core/src/base_node/rpc/sync_utxos_by_block_task.rs b/base_layer/core/src/base_node/rpc/sync_utxos_by_block_task.rs index ce538023a9..6099b4f764 100644 --- a/base_layer/core/src/base_node/rpc/sync_utxos_by_block_task.rs +++ b/base_layer/core/src/base_node/rpc/sync_utxos_by_block_task.rs @@ -5,19 +5,18 @@ use std::{convert::TryInto, sync::Arc, time::Instant}; use log::*; use prost::Message; -use tari_common_types::types::FixedHash; use tari_comms::{ peer_manager::NodeId, protocol::rpc::{RpcStatus, RpcStatusResultExt}, utils::mpsc::ChannelByteBudget, }; use tari_node_components::blocks::BlockHeader; -use tari_transaction_components::transaction_components::TransactionOutput; use tari_utilities::hex::Hex; use tokio::{sync::mpsc, task}; use crate::{ - chain_storage::{BlockchainBackend, ChainStorageError, async_db::AsyncBlockchainDb, is_on_requested_chain}, + base_node::sync::rpc::not_served_status, + chain_storage::{BlockchainBackend, ChainStorageError, NotServed, async_db::AsyncBlockchainDb}, proto, proto::base_node::{SyncUtxosByBlockRequest, SyncUtxosByBlockResponse}, }; @@ -41,28 +40,26 @@ where B: BlockchainBackend + 'static &self, request: &SyncUtxosByBlockRequest, ) -> Result<(BlockHeader, BlockHeader), RpcStatus> { - let hash = request + let start_hash = request .start_header_hash .clone() .try_into() .map_err(|_| RpcStatus::bad_request("Malformed start header hash received"))?; - let start_header = self - .db - .fetch_header_by_block_hash(hash) - .await - .rpc_status_internal_error(LOG_TARGET)? - .ok_or_else(|| RpcStatus::not_found("Start header hash was not found"))?; - let hash = request + let end_hash = request .end_header_hash .clone() .try_into() .map_err(|_| RpcStatus::bad_request("Malformed end header hash received"))?; - let end_header = self + + let (start_header, end_header) = self .db - .fetch_header_by_block_hash(hash) + .validate_sync_utxos_by_block_range(start_hash, end_hash) .await .rpc_status_internal_error(LOG_TARGET)? - .ok_or_else(|| RpcStatus::not_found("End header hash was not found"))?; + .map_err(not_served_status)?; + + let start_header = start_header.ok_or_else(|| RpcStatus::not_found("Start header hash was not found"))?; + let end_header = end_header.ok_or_else(|| RpcStatus::not_found("End header hash was not found"))?; if start_header.height > end_header.height { return Err(RpcStatus::bad_request(&format!( @@ -112,20 +109,38 @@ where B: BlockchainBackend + 'static return Ok(()); } - let (header, outputs) = match self - .fetch_block_on_requested_chain(height, &start_header, end_header.height, &end_hash) + let header = self.fetch_header_at(height, &start_header).await?; + let header_hash = header.hash(); + let outputs = match self + .db + .fetch_outputs_in_block_on_chain(height, header_hash, end_header.height, end_hash) .await { - Ok(Some(block)) => block, - // Every height was at or below the end block when the stream started, so a missing value means the - // chain was rewound - Ok(None) => return Err(reorg_conflict(height)), + Ok(Ok(outputs)) => outputs, + Ok(Err(reason)) => { + match reason { + NotServed::NotOnChain => return Err(reorg_conflict(height)), + NotServed::BodyNotStored => { + debug!( + target: LOG_TARGET, + "Ending UTXO sync by block at #{height}: requested end block body is not stored" + ); + }, + NotServed::OutputRebuild => { + debug!( + target: LOG_TARGET, + "Aborting UTXO sync by block at #{height}: committed output state is being rebuilt by \ + horizon sync" + ); + }, + } + return Err(not_served_status(reason)); + }, Err(err) if err.is_value_not_found() || matches!(err, ChainStorageError::InvalidQuery(_)) => { return Err(reorg_conflict(height)); }, Err(err) => return Err(RpcStatus::log_internal_error(LOG_TARGET)(err)), }; - let header_hash = header.hash(); let outputs = outputs .into_iter() .map(TryInto::try_into) @@ -180,33 +195,18 @@ where B: BlockchainBackend + 'static Ok(()) } - /// Returns the header and outputs of the block at `height`, or None if it is no longer an ancestor of the requested - /// end block. The outputs and the headers at `height` and `end_height` are read under one read lock, so the check - /// holds for the chain state the outputs were read from, whatever reorgs happened before. - async fn fetch_block_on_requested_chain( - &self, - height: u64, - start_header: &BlockHeader, - end_height: u64, - end_hash: &FixedHash, - ) -> Result)>, ChainStorageError> { - let header = if height == start_header.height { - start_header.clone() - } else { - match self.db.fetch_header(height).await? { - Some(header) => header, - None => return Ok(None), - } - }; - let hash = header.hash(); - let (outputs, header_at_height, end_header, _) = self - .db - .fetch_outputs_in_block_and_header_pair(hash, height, end_height) - .await?; - if !is_on_requested_chain(&hash, header_at_height.as_ref(), end_header.as_ref(), end_hash) { - return Ok(None); + async fn fetch_header_at(&self, height: u64, start_header: &BlockHeader) -> Result { + if height == start_header.height { + return Ok(start_header.clone()); + } + match self.db.fetch_header(height).await { + Ok(Some(header)) => Ok(header), + Ok(None) => Err(reorg_conflict(height)), + Err(err) if err.is_value_not_found() || matches!(err, ChainStorageError::InvalidQuery(_)) => { + Err(reorg_conflict(height)) + }, + Err(err) => Err(RpcStatus::log_internal_error(LOG_TARGET)(err)), } - Ok(Some((header, outputs))) } } @@ -215,5 +215,5 @@ fn reorg_conflict(height: u64) -> RpcStatus { target: LOG_TARGET, "Block #{height} is no longer an ancestor of the requested end block during UTXO sync by block" ); - RpcStatus::conflict("Reorg detected: the requested end block is no longer on the chain") + not_served_status(NotServed::NotOnChain) } diff --git a/base_layer/core/src/base_node/sync/rpc/mod.rs b/base_layer/core/src/base_node/sync/rpc/mod.rs index 386433658b..621e85e9bf 100644 --- a/base_layer/core/src/base_node/sync/rpc/mod.rs +++ b/base_layer/core/src/base_node/sync/rpc/mod.rs @@ -25,6 +25,9 @@ mod service; mod sync_utxos_task; pub use service::BaseNodeSyncRpcService; #[cfg(test)] +pub(crate) use service::END_BODY_NOT_STORED; +pub(crate) use service::{OUTPUT_REBUILD_CONFLICT_MSG, not_served_status}; +#[cfg(test)] pub(crate) use sync_utxos_task::SyncUtxosTask; #[cfg(test)] diff --git a/base_layer/core/src/base_node/sync/rpc/service.rs b/base_layer/core/src/base_node/sync/rpc/service.rs index 51a833ab84..5735ac2e29 100644 --- a/base_layer/core/src/base_node/sync/rpc/service.rs +++ b/base_layer/core/src/base_node/sync/rpc/service.rs @@ -280,15 +280,18 @@ impl BaseNodeSyncRpcService { } } -pub(super) const REORG_DETECTED: &str = "Reorg detected: the requested end block is no longer on the chain"; +pub(crate) const REORG_DETECTED: &str = "Reorg detected: the requested end block is no longer on the chain"; pub(super) const HEADER_REORG_DETECTED: &str = "Reorg detected: header chain changed during header sync"; -pub(super) const END_BODY_NOT_STORED: &str = "The requested end block's body is not stored on this node"; +pub(crate) const END_BODY_NOT_STORED: &str = "The requested end block's body is not stored on this node"; +pub(crate) const OUTPUT_REBUILD_CONFLICT_MSG: &str = + "Committed output state is unavailable while horizon sync rebuilds outputs"; /// The Conflict sent when a block's data is not served -pub(super) fn not_served_status(reason: NotServed) -> RpcStatus { +pub(crate) fn not_served_status(reason: NotServed) -> RpcStatus { match reason { NotServed::NotOnChain => RpcStatus::conflict(REORG_DETECTED), NotServed::BodyNotStored => RpcStatus::conflict(END_BODY_NOT_STORED), + NotServed::OutputRebuild => RpcStatus::conflict(OUTPUT_REBUILD_CONFLICT_MSG), } } diff --git a/base_layer/core/src/chain_storage/async_db.rs b/base_layer/core/src/chain_storage/async_db.rs index d91896c0c5..966d35f0a9 100644 --- a/base_layer/core/src/chain_storage/async_db.rs +++ b/base_layer/core/src/chain_storage/async_db.rs @@ -63,6 +63,9 @@ use crate::{ BlockchainDatabase, CandidateVmKey, ChainStorageError, + CommittedKernelsInfo, + CommittedOutputsMinedInfo, + CommittedQueryDeletedResult, DbBasicStats, DbTotalSizeStats, DbTransaction, @@ -206,16 +209,6 @@ impl AsyncBlockchainDb { "fetch_outputs_with_spend_status_at_tip" ); - make_async_fn!( - fetch_outputs_mined_info(hashes: Vec) -> Vec>, - "fetch_outputs_mined_info" - ); - - make_async_fn!( - fetch_latest_mined_infos(hashes: Vec) -> Vec, - "fetch_latest_mined_infos" - ); - make_async_fn!( fetch_txos_in_block_on_chain(height: u64, hash: HashOutput, end_height: u64, end_hash: HashOutput) -> Result, "fetch_txos_in_block_on_chain" @@ -293,6 +286,52 @@ impl AsyncBlockchainDb { "fetch_outputs_in_block_and_header_pair" ); + make_async_fn!( + fetch_outputs_in_block_on_chain( + height: u64, + hash: HashOutput, + end_height: u64, + end_hash: HashOutput, + ) -> Result, NotServed>, + "fetch_outputs_in_block_on_chain" + ); + + make_async_fn!( + validate_sync_utxos_by_block_range( + start_hash: HashOutput, + end_hash: HashOutput, + ) -> Result<(Option, Option), NotServed>, + "validate_sync_utxos_by_block_range" + ); + + make_async_fn!( + fetch_committed_header(height: u64) -> Option, + "fetch_committed_header" + ); + + make_async_fn!( + fetch_committed_kernels_info(excess_sigs: Vec) -> CommittedKernelsInfo, + "fetch_committed_kernels_info" + ); + + make_async_fn!( + fetch_committed_unspent_outputs(hashes: Vec) -> Option>, + "fetch_committed_unspent_outputs" + ); + + make_async_fn!( + fetch_committed_outputs_mined_info(hashes: Vec) -> Option, + "fetch_committed_outputs_mined_info" + ); + + make_async_fn!( + fetch_committed_latest_mined_infos( + hashes: Vec, + must_include_header: Option, + ) -> Result, + "fetch_committed_latest_mined_infos" + ); + make_async_fn!(fetch_chain_header(height: u64) -> ChainHeader, "fetch_chain_header"); make_async_fn!(fetch_chain_headers>(bounds: T) -> Vec, "fetch_chain_headers"); diff --git a/base_layer/core/src/chain_storage/blockchain_database.rs b/base_layer/core/src/chain_storage/blockchain_database.rs index 3ebe7ea7c5..1a0f75d1d3 100644 --- a/base_layer/core/src/chain_storage/blockchain_database.rs +++ b/base_layer/core/src/chain_storage/blockchain_database.rs @@ -1504,74 +1504,7 @@ where B: BlockchainBackend hashes: Vec, ) -> Result>, ChainStorageError> { let db = self.db_read_access()?; - - let (smt_reader, current_version) = db.create_smt_reader()?; - - let smt = JellyfishMerkleTree::<_, SmtHasher>::new(&smt_reader); - let mut result = Vec::with_capacity(hashes.len()); - for hash in hashes { - // Take the last-mined entry if the hash is indexed under several headers. - let mut outputs = db.fetch_outputs(&hash)?; - outputs.sort_by_key(|o| o.mined_height); - let output = outputs.into_iter().next_back(); - - trace!( - target: LOG_TARGET, - "fetch_outputs_with_spend_status_at_tip: hash: {}, output: {:?}", - hash.to_hex(), - output - ); - if let Some(mined_info) = output { - let smt_key = KeyHash( - mined_info - .output - .commitment - .as_bytes() - .try_into() - .expect("must be 32 bytes"), - ); - - let spent = smt - .get(smt_key, current_version) - .map_err(ChainStorageError::JellyfishMerkleTreeError)? - .is_none(); - trace!( - target: LOG_TARGET, - "fetch_outputs_with_spend_status_at_tip: smt_key: {smt_key:?}, spent: {spent}" - ); - result.push(Some((mined_info.output, spent))); - } else { - result.push(None); - } - } - Ok(result) - } - - pub fn fetch_outputs_mined_info( - &self, - hashes: Vec, - ) -> Result>, ChainStorageError> { - let db = self.db_read_access()?; - - let mut result = Vec::with_capacity(hashes.len()); - for hash in hashes { - // Take the last-mined entry if the hash is indexed under several headers. - let mut outputs = db.fetch_outputs(&hash)?; - outputs.sort_by_key(|o| o.mined_height); - result.push(outputs.into_iter().next_back()); - } - Ok(result) - } - - /// For each output hash, the latest lifecycle (see [`MinedInfo::latest`]), all read under one lock. - pub fn fetch_latest_mined_infos(&self, hashes: Vec) -> Result, ChainStorageError> { - let db = self.db_read_access()?; - - let mut result = Vec::with_capacity(hashes.len()); - for hash in hashes { - result.push(MinedInfo::latest(db.fetch_mined_info_by_output_hash(&hash)?)); - } - Ok(result) + fetch_outputs_with_spend_status_up_to(&*db, hashes, u64::MAX) } /// The TXOs of block `hash` at `height`: its outputs with their spend state at `end_hash`, its inputs, and for @@ -1698,6 +1631,154 @@ where B: BlockchainBackend Ok((outputs, first, second, best_block_height)) } + /// The outputs of block `hash` at `height`, or why they are not served (see [`read_on_requested_chain`]). + pub(crate) fn fetch_outputs_in_block_on_chain( + &self, + height: u64, + hash: HashOutput, + end_height: u64, + end_hash: HashOutput, + ) -> Result, NotServed>, ChainStorageError> { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + if !committed_outputs_are_consistent(&*db, &metadata)? { + return Ok(Err(NotServed::OutputRebuild)); + } + read_on_requested_chain(&*db, height, &hash, end_height, &end_hash, |db| { + db.fetch_outputs_in_block(&hash) + }) + } + + /// Validates that `start_hash` and `end_hash` exist, have stored block bodies at or below the committed tip, and + /// that committed outputs are not currently being rebuilt by horizon sync. + pub(crate) fn validate_sync_utxos_by_block_range( + &self, + start_hash: HashOutput, + end_hash: HashOutput, + ) -> Result, Option), NotServed>, ChainStorageError> { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + if !committed_outputs_are_consistent(&*db, &metadata)? { + return Ok(Err(NotServed::OutputRebuild)); + } + let tip_height = metadata.best_block_height(); + let start_header = fetch_header_by_block_hash(&*db, start_hash)?; + let end_header = fetch_header_by_block_hash(&*db, end_hash)?; + if start_header.as_ref().is_some_and(|h| h.height > tip_height) || + end_header.as_ref().is_some_and(|h| h.height > tip_height) + { + return Ok(Err(NotServed::BodyNotStored)); + } + Ok(Ok((start_header, end_header))) + } + + /// Returns the block header at `height` only if `height` is at or below the committed block tip. + pub(crate) fn fetch_committed_header(&self, height: u64) -> Result, ChainStorageError> { + let db = self.db_read_access()?; + let tip_height = db.fetch_chain_metadata()?.best_block_height(); + if height > tip_height { + return Ok(None); + } + match fetch_header(&*db, height) { + Ok(header) => Ok(Some(header)), + Err(err) if err.is_value_not_found() => Ok(None), + Err(err) => Err(err), + } + } + + /// Returns the current chain metadata and, for each signature, the committed block header containing its kernel (if + /// mined at or below the committed tip), all read under one read lock. + pub(crate) fn fetch_committed_kernels_info( + &self, + excess_sigs: Vec, + ) -> Result { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + let tip_height = metadata.best_block_height(); + let mut results = Vec::with_capacity(excess_sigs.len()); + for excess_sig in &excess_sigs { + let mined = match db.fetch_kernel_by_excess_sig(excess_sig)? { + Some((_, block_hash)) => { + fetch_committed_header_by_hash(&*db, &block_hash, tip_height)?.map(|header| (block_hash, header)) + }, + None => None, + }; + results.push(mined); + } + Ok((metadata, results)) + } + + /// Returns the unspent outputs at the committed tip for `hashes`, or `Ok(None)` if committed outputs are currently + /// being rebuilt by horizon sync. + pub(crate) fn fetch_committed_unspent_outputs( + &self, + hashes: Vec, + ) -> Result>, ChainStorageError> { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + if !committed_outputs_are_consistent(&*db, &metadata)? { + return Ok(None); + } + let tip_height = metadata.best_block_height(); + let statuses = fetch_outputs_with_spend_status_up_to(&*db, hashes, tip_height)?; + let outputs = statuses + .into_iter() + .flatten() + .filter_map(|(output, spent)| (!spent).then_some(output)) + .collect(); + Ok(Some(outputs)) + } + + /// Returns the chain metadata and latest committed mined info for `hashes`, or `Ok(None)` if committed outputs are + /// currently being rebuilt by horizon sync. + pub(crate) fn fetch_committed_outputs_mined_info( + &self, + hashes: Vec, + ) -> Result, ChainStorageError> { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + if !committed_outputs_are_consistent(&*db, &metadata)? { + return Ok(None); + } + let tip_height = metadata.best_block_height(); + let mut result = Vec::with_capacity(hashes.len()); + for hash in hashes { + result.push(fetch_latest_committed_output(&*db, &hash, tip_height)?); + } + Ok(Some((metadata, result))) + } + + /// Returns the chain metadata and latest committed lifecycle for `hashes`, checking that `must_include_header` (if + /// given) is on the committed chain and that committed outputs are not being rebuilt by horizon sync. + pub(crate) fn fetch_committed_latest_mined_infos( + &self, + hashes: Vec, + must_include_header: Option, + ) -> Result, ChainStorageError> { + let db = self.db_read_access()?; + let metadata = db.fetch_chain_metadata()?; + if !committed_outputs_are_consistent(&*db, &metadata)? { + return Ok(Err(NotServed::OutputRebuild)); + } + let tip_height = metadata.best_block_height(); + if let Some(required_hash) = must_include_header && + fetch_committed_header_by_hash(&*db, &required_hash, tip_height)?.is_none() + { + return Ok(Err(NotServed::NotOnChain)); + } + let mut result = Vec::with_capacity(hashes.len()); + for hash in hashes { + let mut committed_infos = Vec::new(); + for info in db.fetch_mined_info_by_output_hash(&hash)? { + if let Some(clean) = sanitize_committed_mined_info(&*db, info, tip_height)? { + committed_infos.push(clean); + } + } + result.push(MinedInfo::latest(committed_infos)); + } + Ok(Ok((metadata, result))) + } + /// Returns the block header at the given block height. pub fn fetch_chain_header(&self, height: u64) -> Result { let db = self.db_read_access()?; @@ -3167,6 +3248,133 @@ pub enum NotServed { NotOnChain, /// The requested end block is above the best block, so the bodies up to it are not all stored BodyNotStored, + /// Committed output tables are currently being rebuilt by horizon sync + OutputRebuild, +} + +pub(crate) type CommittedKernelsInfo = (ChainMetadata, Vec>); +pub(crate) type CommittedOutputsMinedInfo = (ChainMetadata, Vec>); +pub(crate) type CommittedQueryDeletedResult = (ChainMetadata, Vec); + +fn fetch_committed_header_by_hash( + db: &T, + hash: &FixedHash, + tip_height: u64, +) -> Result, ChainStorageError> { + let Some(header) = fetch_header_by_block_hash(db, *hash)? else { + return Ok(None); + }; + if header.height > tip_height { + return Ok(None); + } + Ok(Some(header)) +} + +/// Returns `true` only when the output tables and output JMT match `metadata`'s committed tip and no horizon-sync +/// output rebuild checkpoint is active. +fn committed_outputs_are_consistent( + db: &T, + metadata: &ChainMetadata, +) -> Result { + if db.fetch_horizon_sync_output_checkpoint()?.is_some() { + return Ok(false); + } + let Some(best_header) = + fetch_committed_header_by_hash(db, metadata.best_block_hash(), metadata.best_block_height())? + else { + return Ok(false); + }; + match db.verify_horizon_sync_output_root(best_header.output_mr) { + Ok(()) => Ok(true), + Err(ChainStorageError::InvalidOperation(msg)) => { + debug!( + target: LOG_TARGET, + "Committed output root does not match best block #{} ({}): {msg}", + metadata.best_block_height(), + metadata.best_block_hash().to_hex(), + ); + Ok(false) + }, + Err(err) => Err(err), + } +} + +fn fetch_latest_committed_output( + db: &T, + hash: &FixedHash, + tip_height: u64, +) -> Result, ChainStorageError> { + let mut committed = Vec::new(); + for info in db.fetch_outputs(hash)? { + if tip_height == u64::MAX || fetch_committed_header_by_hash(db, &info.header_hash, tip_height)?.is_some() { + committed.push(info); + } + } + committed.sort_by_key(|o| o.mined_height); + Ok(committed.into_iter().next_back()) +} + +fn fetch_outputs_with_spend_status_up_to( + db: &T, + hashes: Vec, + tip_height: u64, +) -> Result>, ChainStorageError> { + let (smt_reader, current_version) = db.create_smt_reader()?; + let smt = JellyfishMerkleTree::<_, SmtHasher>::new(&smt_reader); + let mut result = Vec::with_capacity(hashes.len()); + for hash in hashes { + let output = fetch_latest_committed_output(db, &hash, tip_height)?; + trace!( + target: LOG_TARGET, + "fetch_outputs_with_spend_status_up_to: hash: {}, output: {:?}", + hash.to_hex(), + output + ); + if let Some(mined_info) = output { + let key_bytes: [u8; 32] = mined_info + .output + .commitment + .as_bytes() + .try_into() + .map_err(|_| ChainStorageError::UnexpectedResult("Commitment must be 32 bytes".to_string()))?; + let smt_key = KeyHash(key_bytes); + let expected_value = mined_info.output.smt_hash(mined_info.mined_height); + let stored_value = smt + .get(smt_key, current_version) + .map_err(ChainStorageError::JellyfishMerkleTreeError)? + .and_then(|bytes| bincode::deserialize::>>(&bytes).ok()) + .flatten(); + let spent = stored_value.as_deref() != Some(expected_value.as_slice()); + trace!( + target: LOG_TARGET, + "fetch_outputs_with_spend_status_up_to: smt_key: {smt_key:?}, spent: {spent}" + ); + result.push(Some((mined_info.output, spent))); + } else { + result.push(None); + } + } + Ok(result) +} + +fn sanitize_committed_mined_info( + db: &T, + info: MinedInfo, + tip_height: u64, +) -> Result, ChainStorageError> { + let output = match info.output { + Some(o) if fetch_committed_header_by_hash(db, &o.header_hash, tip_height)?.is_some() => Some(o), + _ => None, + }; + let input = match info.input { + Some(i) if fetch_committed_header_by_hash(db, &i.header_hash, tip_height)?.is_some() => Some(i), + _ => None, + }; + if output.is_some() || input.is_some() { + Ok(Some(MinedInfo { input, output })) + } else { + Ok(None) + } } /// Runs `read` for block `hash` and checks under the same read lock, so that no write can commit in between, that the @@ -7022,6 +7230,66 @@ mod test { assert_eq!(best_block_height, 3); } + #[test] + fn fetch_outputs_in_block_on_chain_checks_chain_tip_and_output_rebuild() { + let db = create_new_blockchain(); + let (_, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"], ["C->B"])); + let b = chain.get("B").unwrap(); + let c = chain.get("C").unwrap(); + + let outputs = db + .fetch_outputs_in_block_on_chain(2, *b.hash(), 3, *c.hash()) + .unwrap() + .unwrap(); + assert_eq!(outputs, db.fetch_outputs_in_block(*b.hash()).unwrap()); + assert!(!outputs.is_empty()); + + let (_, future) = create_chained_blocks(&db, block_specs!(["D->GB"]), c.clone()); + let d = future.get("D").unwrap(); + db.insert_valid_headers(vec![d.to_chain_header()]).unwrap(); + let res = db.fetch_outputs_in_block_on_chain(2, *b.hash(), 4, *d.hash()).unwrap(); + assert!(matches!(res, Err(NotServed::BodyNotStored))); + + let mut txn = DbTransaction::new(); + txn.clear_horizon_sync_output_state(); + db.write(txn).unwrap(); + let res = db.fetch_outputs_in_block_on_chain(2, *b.hash(), 3, *c.hash()).unwrap(); + assert!(matches!(res, Err(NotServed::OutputRebuild))); + } + + #[test] + fn fetch_outputs_with_spend_status_at_tip_checks_smt_leaf_value_when_commitment_is_reused() { + let db = create_new_blockchain(); + let (_, chain) = create_main_chain(&db, block_specs!(["A->GB"], ["B->A"])); + let a = chain.get("A").unwrap(); + let b = chain.get("B").unwrap(); + let output_x = a.block().body.outputs().first().unwrap().clone(); + let mut output_y = output_x.clone(); + output_y.sender_offset_public_key = CompressedPublicKey::default(); + assert_ne!(output_x.hash(), output_y.hash()); + + let initial = db + .fetch_outputs_with_spend_status_at_tip(vec![output_x.hash()]) + .unwrap(); + assert_eq!(initial, vec![Some((output_x.clone(), false))]); + + let key_bytes: [u8; 32] = output_y.commitment.as_bytes().try_into().unwrap(); + let mut txn = DbTransaction::new(); + txn.delete_utxo_commitment_index_entry(output_x.commitment.clone()); + txn.insert_utxo(output_y.clone(), *b.hash(), b.height(), b.header().timestamp.as_u64()); + txn.apply_horizon_state_tree_updates(vec![HorizonStateTreeUpdate { + key: FixedHash::from(key_bytes), + value: Some(output_y.smt_hash(b.height())), + replaces_value: true, + }]); + db.write(txn).unwrap(); + + let statuses = db + .fetch_outputs_with_spend_status_at_tip(vec![output_x.hash(), output_y.hash()]) + .unwrap(); + assert_eq!(statuses, vec![Some((output_x, true)), Some((output_y, false))]); + } + /// A rewind past a pruned node's horizon keeps none of the blocks it removes, so it must not index an orphan chain /// tip for them either #[tokio::test] diff --git a/base_layer/core/src/chain_storage/mod.rs b/base_layer/core/src/chain_storage/mod.rs index a3315707b4..4f7cb0e369 100644 --- a/base_layer/core/src/chain_storage/mod.rs +++ b/base_layer/core/src/chain_storage/mod.rs @@ -60,6 +60,7 @@ pub use blockchain_database::{ is_on_requested_chain, reorg_reintroduces_pre_ghsa_blocks, }; +pub(crate) use blockchain_database::{CommittedKernelsInfo, CommittedOutputsMinedInfo, CommittedQueryDeletedResult}; mod blockchain_backend; pub use blockchain_backend::BlockchainBackend; mod consts;