From e6e9d251e3c43f841cc46dfd15649188cbe0e531 Mon Sep 17 00:00:00 2001 From: Yuko Roodt Date: Tue, 7 Apr 2020 09:00:51 +0200 Subject: [PATCH] - Remove the unused is_at_chain_tip, total_kernel_excess, total_kernel_offset and total_utxo_commitment functions from blockchain db. - Modified the is_at_chain_tip function to use the faster backend chain metadata, instead of querying the last header. - Remove applying config from the base node starting state and removed the unused BaseNodeError. - Remove the unused tests: total_kernel_excess, total_kernel_offset and total_utxo_commitment. --- applications/tari_base_node/src/parser.rs | 2 +- base_layer/core/src/base_node/states/error.rs | 36 -------- base_layer/core/src/base_node/states/mod.rs | 1 - .../src/base_node/states/starting_state.rs | 14 +--- base_layer/core/src/chain_storage/async_db.rs | 1 - .../src/chain_storage/blockchain_database.rs | 83 +------------------ .../core/src/mempool/service/local_service.rs | 2 +- .../chain_storage_tests/chain_storage.rs | 71 ---------------- 8 files changed, 8 insertions(+), 202 deletions(-) delete mode 100644 base_layer/core/src/base_node/states/error.rs diff --git a/applications/tari_base_node/src/parser.rs b/applications/tari_base_node/src/parser.rs index 5f82208917..02ba9754eb 100644 --- a/applications/tari_base_node/src/parser.rs +++ b/applications/tari_base_node/src/parser.rs @@ -356,7 +356,7 @@ impl Parser { warn!(target: LOG_TARGET, "Error communicating with wallet: {:?}", e); return; }, - Ok(mut unspent_outputs) => { + Ok(unspent_outputs) => { if unspent_outputs.len() > 0 { println!( "\nYou have {} UTXOs: (value, spending key, mature in ? blocks, flags)", diff --git a/base_layer/core/src/base_node/states/error.rs b/base_layer/core/src/base_node/states/error.rs deleted file mode 100644 index b35a4b4cc5..0000000000 --- a/base_layer/core/src/base_node/states/error.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2019. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::base_node::states::StateEvent; -use derive_error::Error; - -#[derive(Clone, Debug, Error)] -pub enum BaseNodeError { - #[error(msg_embedded, non_std, no_from)] - ConfigurationError(String), -} - -impl BaseNodeError { - pub fn as_fatal(&self, preface: &str) -> StateEvent { - StateEvent::FatalError(format!("{} {}", preface, self.to_string())) - } -} diff --git a/base_layer/core/src/base_node/states/mod.rs b/base_layer/core/src/base_node/states/mod.rs index b18f73c4c9..596ab33961 100644 --- a/base_layer/core/src/base_node/states/mod.rs +++ b/base_layer/core/src/base_node/states/mod.rs @@ -57,7 +57,6 @@ //! required, and then shutdown. mod block_sync; -mod error; mod events_and_states; mod forward_block_sync; mod listening; diff --git a/base_layer/core/src/base_node/states/starting_state.rs b/base_layer/core/src/base_node/states/starting_state.rs index fbcc8e0a30..262786062a 100644 --- a/base_layer/core/src/base_node/states/starting_state.rs +++ b/base_layer/core/src/base_node/states/starting_state.rs @@ -22,7 +22,7 @@ // use crate::{ base_node::{ - states::{error::BaseNodeError, listening::ListeningInfo, StateEvent}, + states::{listening::ListeningInfo, StateEvent}, BaseNodeStateMachine, }, chain_storage::BlockchainBackend, @@ -36,22 +36,12 @@ const LOG_TARGET: &str = "c::bn::states::starting_state"; pub struct Starting; impl Starting { - /// Apply the configuration settings for this node. - fn apply_config(&mut self) -> Result<(), BaseNodeError> { - // TODO apply configuration - Ok(()) - } - pub async fn next_event( &mut self, _shared: &BaseNodeStateMachine, ) -> StateEvent { - info!(target: LOG_TARGET, "Configuring node."); - if let Err(err) = self.apply_config() { - return err.as_fatal("There was an error with the base node configuration."); - } - info!(target: LOG_TARGET, "Node configuration complete."); + info!(target: LOG_TARGET, "Starting node."); StateEvent::Initialized } } diff --git a/base_layer/core/src/chain_storage/async_db.rs b/base_layer/core/src/chain_storage/async_db.rs index 97fe89d982..59cab4b6d8 100644 --- a/base_layer/core/src/chain_storage/async_db.rs +++ b/base_layer/core/src/chain_storage/async_db.rs @@ -106,7 +106,6 @@ make_async!(calculate_mmr_root(tree: MmrTree,additions: Vec,deletion make_async!(add_block(block: Block) -> BlockAddResult, "add_block"); make_async!(calculate_mmr_roots(template: NewBlockTemplate) -> Block, "calculate_mmr_roots"); -// make_async!(is_new_best_block(block: &Block) -> bool); make_async!(fetch_block(height: u64) -> HistoricalBlock, "fetch_block"); make_async!(fetch_block_with_hash(hash: HashOutput) -> Option, "fetch_block_with_hash"); make_async!(rewind_to_height(height: u64) -> Vec, "rewind_to_height"); diff --git a/base_layer/core/src/chain_storage/blockchain_database.rs b/base_layer/core/src/chain_storage/blockchain_database.rs index 444b0ae383..6acbcc0fd9 100644 --- a/base_layer/core/src/chain_storage/blockchain_database.rs +++ b/base_layer/core/src/chain_storage/blockchain_database.rs @@ -32,7 +32,7 @@ use crate::{ proof_of_work::{Difficulty, ProofOfWork}, transactions::{ transaction::{TransactionInput, TransactionKernel, TransactionOutput}, - types::{BlindingFactor, Commitment, CommitmentFactory, HashOutput}, + types::{Commitment, HashOutput}, }, validation::{StatelessValidation, StatelessValidator, Validation, ValidationError, Validator}, }; @@ -41,14 +41,10 @@ use log::*; use serde::{Deserialize, Serialize}; use std::{ collections::VecDeque, - ops::DerefMut, sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}, }; use strum_macros::Display; -use tari_crypto::{ - commitment::HomomorphicCommitmentFactory, - tari_utilities::{hex::Hex, Hashable}, -}; +use tari_crypto::tari_utilities::{hex::Hex, Hashable}; use tari_mmr::{Hash, MerkleCheckPoint, MerkleProof, MutableMmrLeafNodes}; const LOG_TARGET: &str = "c::cs::database"; @@ -405,17 +401,6 @@ where T: BlockchainBackend store_new_block(&mut db, block) } - /// Returns true if the given block -- assuming everything else is valid -- would be added to the tip of the - /// longest chain; i.e. the following conditions are met: - /// * The blockchain is empty, - /// * or ALL of: - /// * the block's parent hash is the hash of the block at the current chain tip, - /// * the block height is one greater than the parent block - pub fn is_at_chain_tip(&self, block: &Block) -> Result { - let db = self.db_read_access()?; - is_at_chain_tip(&*db, block) - } - /// Fetch a block from the blockchain database. /// /// # Returns @@ -455,24 +440,6 @@ where T: BlockchainBackend let mut db = self.db_write_access()?; rewind_to_height(&mut db, height) } - - /// Calculate the total kernel excess for all kernels in the chain. - pub fn total_kernel_excess(&self) -> Result { - let db = self.db_read_access()?; - total_kernel_excess(&*db) - } - - /// Calculate the total kernel offset for all the kernel offsets recorded in the headers of the chain. - pub fn total_kernel_offset(&self) -> Result { - let db = self.db_read_access()?; - total_kernel_offset(&*db) - } - - /// Calculate the total sum of all the UTXO commitments in the chain. - pub fn total_utxo_commitment(&self) -> Result { - let db = self.db_read_access()?; - total_utxo_commitment(&*db) - } } fn unexpected_result(req: DbKey, res: DbValue) -> Result { @@ -608,21 +575,6 @@ fn store_new_block(db: &mut RwLockWriteGuard, block: Bl Ok(()) } -fn is_at_chain_tip(db: &T, block: &Block) -> Result { - let (parent_height, parent_hash) = { - // If the database is empty, the best block must be the genesis block - let metadata = db.fetch_metadata()?; - if metadata.height_of_longest_chain.is_none() { - return Ok(block.header.height == 0); - } - ( - metadata.height_of_longest_chain.clone().unwrap(), - metadata.best_block.clone().unwrap(), - ) - }; - Ok(block.header.prev_hash == parent_hash && block.header.height == parent_height + 1) -} - fn fetch_block(db: &T, height: u64) -> Result { let tip_height = check_for_valid_height(&*db, height)?; let header = fetch_header(db, height)?; @@ -657,7 +609,7 @@ fn fetch_block_with_hash( } fn check_for_valid_height(db: &T, height: u64) -> Result { - let db_height = db.fetch_last_header()?.map(|tip| tip.height).unwrap_or(0); + let db_height = db.fetch_metadata()?.height_of_longest_chain.unwrap_or(0); if height > db_height { return Err(ChainStorageError::InvalidQuery(format!( "Cannot get block at height {}. Chain tip is at {}", @@ -726,7 +678,7 @@ fn fetch_checkpoint( } pub fn commit(db: &mut RwLockWriteGuard, txn: DbTransaction) -> Result<(), ChainStorageError> { - db.deref_mut().write(txn) + db.write(txn) } fn rewind_to_height( @@ -989,33 +941,6 @@ fn remove_orphan( commit(db, txn) } -fn total_kernel_excess(db: &T) -> Result { - let mut excess = CommitmentFactory::default().zero(); - db.for_each_kernel(|pair| { - let (_, kernel) = pair.unwrap(); - excess = &excess + &kernel.excess; - })?; - Ok(excess) -} - -fn total_kernel_offset(db: &T) -> Result { - let mut offset = BlindingFactor::default(); - db.for_each_header(|pair| { - let (_, header) = pair.unwrap(); - offset = &offset + &header.total_kernel_offset; - })?; - Ok(offset) -} - -fn total_utxo_commitment(db: &T) -> Result { - let mut total_commitment = CommitmentFactory::default().zero(); - db.for_each_utxo(|pair| { - let (_, utxo) = pair.unwrap(); - total_commitment = &total_commitment + &utxo.commitment; - })?; - Ok(total_commitment) -} - /// We try and build a chain from this block to the main chain. If we can't do that we can stop. /// We start with the current, newly received block, and look for a blockchain sequence (via `prev_hash`). /// Each successful link is pushed to the front of the queue. An empty queue is returned if the fork chain did not diff --git a/base_layer/core/src/mempool/service/local_service.rs b/base_layer/core/src/mempool/service/local_service.rs index 88a178529e..07c213f40f 100644 --- a/base_layer/core/src/mempool/service/local_service.rs +++ b/base_layer/core/src/mempool/service/local_service.rs @@ -103,7 +103,7 @@ mod test { MempoolRequest::GetStats => Ok(MempoolResponse::Stats(request_stats())), _ => Err(MempoolServiceError::UnexpectedApiResponse), }; - reply_channel.send(res); + reply_channel.send(res).unwrap(); } } diff --git a/base_layer/core/tests/chain_storage_tests/chain_storage.rs b/base_layer/core/tests/chain_storage_tests/chain_storage.rs index 07427a44e6..2078342be5 100644 --- a/base_layer/core/tests/chain_storage_tests/chain_storage.rs +++ b/base_layer/core/tests/chain_storage_tests/chain_storage.rs @@ -797,77 +797,6 @@ fn store_and_retrieve_chain_and_orphan_blocks_with_hashes() { assert_eq!(*store.fetch_block_with_hash(hash2).unwrap().unwrap().block(), orphan); } -#[test] -fn total_kernel_excess() { - let network = Network::LocalNet; - let consensus_manager = ConsensusManagerBuilder::new(network).build(); - let store = create_mem_db(&consensus_manager); - let block0 = store.fetch_block(0).unwrap().block().clone(); - - let kernel1 = create_test_kernel(100.into(), 0); - let kernel2 = create_test_kernel(200.into(), 0); - let kernel3 = create_test_kernel(300.into(), 0); - - let mut txn = DbTransaction::new(); - txn.insert_kernel(kernel1.clone(), false); - txn.insert_kernel(kernel2.clone(), false); - txn.insert_kernel(kernel3.clone(), false); - assert!(store.commit(txn).is_ok()); - - let total_kernel_excess = store.total_kernel_excess().unwrap(); - assert_eq!( - total_kernel_excess, - &(&(block0.body.kernels()[0].excess) + &kernel1.excess) + &(&kernel2.excess + &kernel3.excess) - ); -} - -#[test] -fn total_kernel_offset() { - let network = Network::LocalNet; - let consensus_manager = ConsensusManagerBuilder::new(network).build(); - let store = create_mem_db(&consensus_manager); - let block0 = store.fetch_block(0).unwrap().block().clone(); - - let header2 = BlockHeader::from_previous(&block0.header); - let header3 = BlockHeader::from_previous(&header2); - let mut txn = DbTransaction::new(); - txn.insert_header(header2.clone()); - txn.insert_header(header3.clone()); - assert!(store.commit(txn).is_ok()); - - let total_kernel_offset = store.total_kernel_offset().unwrap(); - assert_eq!( - total_kernel_offset, - &(&block0.header.total_kernel_offset + &header2.total_kernel_offset) + &header3.total_kernel_offset - ); -} - -#[test] -fn total_utxo_commitment() { - let factories = CryptoFactories::default(); - let network = Network::LocalNet; - let gen_block = genesis_block::get_rincewind_genesis_block_raw(); - let consensus_manager = ConsensusManagerBuilder::new(network).with_block(gen_block).build(); - let store = create_mem_db(&consensus_manager); - let block0 = store.fetch_block(0).unwrap().block().clone(); - - let (utxo1, _) = create_utxo(MicroTari(10_000), &factories, None); - let (utxo2, _) = create_utxo(MicroTari(15_000), &factories, None); - let (utxo3, _) = create_utxo(MicroTari(20_000), &factories, None); - - let mut txn = DbTransaction::new(); - txn.insert_utxo(utxo1.clone(), true); - txn.insert_utxo(utxo2.clone(), true); - txn.insert_utxo(utxo3.clone(), true); - assert!(store.commit(txn).is_ok()); - - let total_utxo_commitment = store.total_utxo_commitment().unwrap(); - assert_eq!( - total_utxo_commitment, - &(&(block0.body.outputs()[0].commitment) + &utxo1.commitment) + &(&utxo2.commitment + &utxo3.commitment) - ); -} - #[test] fn restore_metadata() { let path = create_temporary_data_path();