Skip to content

Commit

Permalink
- Remove the unused is_at_chain_tip, total_kernel_excess, total_kerne…
Browse files Browse the repository at this point in the history
…l_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. (#1681)

Merge pull request #1681

- 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.

* pull/1681/head:
  - 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.
  • Loading branch information
sdbondi committed Apr 7, 2020
2 parents 6f543cf + e6e9d25 commit 97cba8f
Show file tree
Hide file tree
Showing 8 changed files with 8 additions and 202 deletions.
2 changes: 1 addition & 1 deletion applications/tari_base_node/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand Down
36 changes: 0 additions & 36 deletions base_layer/core/src/base_node/states/error.rs

This file was deleted.

1 change: 0 additions & 1 deletion base_layer/core/src/base_node/states/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
//! required, and then shutdown.
mod block_sync;
mod error;
mod events_and_states;
mod forward_block_sync;
mod listening;
Expand Down
14 changes: 2 additions & 12 deletions base_layer/core/src/base_node/states/starting_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
//
use crate::{
base_node::{
states::{error::BaseNodeError, listening::ListeningInfo, StateEvent},
states::{listening::ListeningInfo, StateEvent},
BaseNodeStateMachine,
},
chain_storage::BlockchainBackend,
Expand All @@ -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<B: BlockchainBackend + 'static>(
&mut self,
_shared: &BaseNodeStateMachine<B>,
) -> 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
}
}
Expand Down
1 change: 0 additions & 1 deletion base_layer/core/src/chain_storage/async_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ make_async!(calculate_mmr_root(tree: MmrTree,additions: Vec<HashOutput>,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<HistoricalBlock>, "fetch_block_with_hash");
make_async!(rewind_to_height(height: u64) -> Vec<Block>, "rewind_to_height");
Expand Down
83 changes: 4 additions & 79 deletions base_layer/core/src/chain_storage/blockchain_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
};
Expand All @@ -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";
Expand Down Expand Up @@ -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<bool, ChainStorageError> {
let db = self.db_read_access()?;
is_at_chain_tip(&*db, block)
}

/// Fetch a block from the blockchain database.
///
/// # Returns
Expand Down Expand Up @@ -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<Commitment, ChainStorageError> {
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<BlindingFactor, ChainStorageError> {
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<Commitment, ChainStorageError> {
let db = self.db_read_access()?;
total_utxo_commitment(&*db)
}
}

fn unexpected_result<T>(req: DbKey, res: DbValue) -> Result<T, ChainStorageError> {
Expand Down Expand Up @@ -608,21 +575,6 @@ fn store_new_block<T: BlockchainBackend>(db: &mut RwLockWriteGuard<T>, block: Bl
Ok(())
}

fn is_at_chain_tip<T: BlockchainBackend>(db: &T, block: &Block) -> Result<bool, ChainStorageError> {
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<T: BlockchainBackend>(db: &T, height: u64) -> Result<HistoricalBlock, ChainStorageError> {
let tip_height = check_for_valid_height(&*db, height)?;
let header = fetch_header(db, height)?;
Expand Down Expand Up @@ -657,7 +609,7 @@ fn fetch_block_with_hash<T: BlockchainBackend>(
}

fn check_for_valid_height<T: BlockchainBackend>(db: &T, height: u64) -> Result<u64, ChainStorageError> {
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 {}",
Expand Down Expand Up @@ -726,7 +678,7 @@ fn fetch_checkpoint<T: BlockchainBackend>(
}

pub fn commit<T: BlockchainBackend>(db: &mut RwLockWriteGuard<T>, txn: DbTransaction) -> Result<(), ChainStorageError> {
db.deref_mut().write(txn)
db.write(txn)
}

fn rewind_to_height<T: BlockchainBackend>(
Expand Down Expand Up @@ -989,33 +941,6 @@ fn remove_orphan<T: BlockchainBackend>(
commit(db, txn)
}

fn total_kernel_excess<T: BlockchainBackend>(db: &T) -> Result<Commitment, ChainStorageError> {
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<T: BlockchainBackend>(db: &T) -> Result<BlindingFactor, ChainStorageError> {
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<T: BlockchainBackend>(db: &T) -> Result<Commitment, ChainStorageError> {
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
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/src/mempool/service/local_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand Down
71 changes: 0 additions & 71 deletions base_layer/core/tests/chain_storage_tests/chain_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 97cba8f

Please sign in to comment.