Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: timestamp validation #4887

Merged
merged 5 commits into from
Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use super::LOG_TARGET;
use crate::{
blocks::{Block, BlockHeader},
chain_storage::{async_db::AsyncBlockchainDb, BlockchainBackend, PrunedOutput},
consensus::ConsensusManager,
consensus::{ConsensusConstants, ConsensusManager},
iterators::NonOverlappingIntegerPairIter,
transactions::{
aggregated_body::AggregateBody,
Expand All @@ -50,7 +50,7 @@ use crate::{
},
validation::{
block_validators::abort_on_drop::AbortOnDropJoinHandle,
helpers,
helpers::{self, check_header_timestamp_greater_than_median},
BlockSyncBodyValidation,
ValidationError,
},
Expand Down Expand Up @@ -85,6 +85,32 @@ impl<B: BlockchainBackend + 'static> BlockValidator<B> {
}
}

pub async fn check_median_timestamp(
&self,
constants: &ConsensusConstants,
block_header: &BlockHeader,
) -> Result<(), ValidationError> {
if block_header.height == 0 {
return Ok(()); // Its the genesis block, so we dont have to check median
}

let height = block_header.height - 1;
let min_height = block_header
.height
.saturating_sub(constants.get_median_timestamp_count() as u64);
let timestamps = self
.db
.fetch_headers(min_height..=height)
.await?
.iter()
.map(|h| h.timestamp)
.collect::<Vec<_>>();

check_header_timestamp_greater_than_median(block_header, &timestamps)?;

Ok(())
}

async fn check_mmr_roots(&self, block: Block) -> Result<Block, ValidationError> {
let (block, mmr_roots) = self.db.calculate_mmr_roots(block).await?;
helpers::check_mmr_roots(&block.header, &mmr_roots)?;
Expand Down Expand Up @@ -489,6 +515,7 @@ impl<B: BlockchainBackend + 'static> BlockSyncBodyValidation for BlockValidator<
);

let constants = self.rules.consensus_constants(block.header.height);
self.check_median_timestamp(constants, &block.header).await?;
helpers::check_block_weight(&block, constants)?;
trace!(target: LOG_TARGET, "SV - Block weight is ok for {} ", &block_id);
let block = self.validate_block_body(block).await?;
Expand Down
41 changes: 37 additions & 4 deletions base_layer/core/src/validation/block_validators/body_only.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@ use tari_utilities::hex::Hex;

use super::LOG_TARGET;
use crate::{
blocks::ChainBlock,
blocks::{BlockHeader, ChainBlock},
chain_storage,
chain_storage::BlockchainBackend,
consensus::ConsensusManager,
validation::{helpers, PostOrphanBodyValidation, ValidationError},
chain_storage::{fetch_headers, BlockchainBackend},
consensus::{ConsensusConstants, ConsensusManager},
validation::{
helpers::{self, check_header_timestamp_greater_than_median},
PostOrphanBodyValidation,
ValidationError,
},
};

/// This validator tests whether a candidate block is internally consistent.
Expand All @@ -46,6 +50,31 @@ impl BodyOnlyValidator {
pub fn new(rules: ConsensusManager) -> Self {
Self { rules }
}

/// This function tests that the block timestamp is greater than the median timestamp at the specified height.
fn check_median_timestamp<B: BlockchainBackend>(
&self,
db: &B,
constants: &ConsensusConstants,
block_header: &BlockHeader,
) -> Result<(), ValidationError> {
if block_header.height == 0 {
return Ok(()); // Its the genesis block, so we dont have to check median
}

let height = block_header.height - 1;
let min_height = block_header
.height
.saturating_sub(constants.get_median_timestamp_count() as u64);
let timestamps = fetch_headers(db, min_height, height)?
.iter()
.map(|h| h.timestamp)
.collect::<Vec<_>>();

check_header_timestamp_greater_than_median(block_header, &timestamps)?;

Ok(())
}
}

impl<B: BlockchainBackend> PostOrphanBodyValidation<B> for BodyOnlyValidator {
Expand All @@ -61,6 +90,8 @@ impl<B: BlockchainBackend> PostOrphanBodyValidation<B> for BodyOnlyValidator {
block: &ChainBlock,
metadata: &ChainMetadata,
) -> Result<(), ValidationError> {
let constants = self.rules.consensus_constants(block.header().height);

if block.header().prev_hash != *metadata.best_block() {
return Err(ValidationError::IncorrectPreviousHash {
expected: metadata.best_block().to_hex(),
Expand All @@ -74,6 +105,8 @@ impl<B: BlockchainBackend> PostOrphanBodyValidation<B> for BodyOnlyValidator {
});
}

self.check_median_timestamp(backend, constants, block.header())?;

let block_id = format!("block #{} ({})", block.header().height, block.hash().to_hex());
helpers::check_inputs_are_utxos(backend, &block.block().body)?;
helpers::check_outputs(
Expand Down
43 changes: 3 additions & 40 deletions base_layer/core/src/validation/header_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,11 @@ use tari_utilities::hex::Hex;

use crate::{
blocks::BlockHeader,
chain_storage::{fetch_headers, BlockchainBackend},
consensus::{ConsensusConstants, ConsensusManager},
chain_storage::BlockchainBackend,
consensus::ConsensusManager,
proof_of_work::AchievedTargetDifficulty,
validation::{
helpers::{
check_blockchain_version,
check_header_timestamp_greater_than_median,
check_not_bad_block,
check_pow_data,
check_timestamp_ftl,
},
helpers::{check_blockchain_version, check_not_bad_block, check_pow_data, check_timestamp_ftl},
DifficultyCalculator,
HeaderValidation,
ValidationError,
Expand All @@ -33,31 +27,6 @@ impl HeaderValidator {
pub fn new(rules: ConsensusManager) -> Self {
Self { rules }
}

/// This function tests that the block timestamp is greater than the median timestamp at the specified height.
fn check_median_timestamp<B: BlockchainBackend>(
&self,
db: &B,
constants: &ConsensusConstants,
block_header: &BlockHeader,
) -> Result<(), ValidationError> {
if block_header.height == 0 {
return Ok(()); // Its the genesis block, so we dont have to check median
}

let height = block_header.height - 1;
let min_height = block_header
.height
.saturating_sub(constants.get_median_timestamp_count() as u64);
let timestamps = fetch_headers(db, min_height, height)?
.iter()
.map(|h| h.timestamp)
.collect::<Vec<_>>();

check_header_timestamp_greater_than_median(block_header, &timestamps)?;

Ok(())
}
}

impl<TBackend: BlockchainBackend> HeaderValidation<TBackend> for HeaderValidator {
Expand All @@ -82,12 +51,6 @@ impl<TBackend: BlockchainBackend> HeaderValidation<TBackend> for HeaderValidator
"BlockHeader validation: FTL timestamp is ok for {} ",
header_id
);
self.check_median_timestamp(backend, constants, header)?;
trace!(
target: LOG_TARGET,
"BlockHeader validation: Median timestamp is ok for {} ",
header_id
);
check_pow_data(header, &self.rules, backend)?;
let achieved_target = difficulty_calculator.check_achieved_and_target_difficulty(backend, header)?;
check_not_bad_block(backend, header.hash())?;
Expand Down
14 changes: 0 additions & 14 deletions base_layer/core/tests/block_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,20 +612,6 @@ OutputFeatures::default()),
)
.is_err());

// lets break the median rules
let mut new_block = db.prepare_new_block(template.clone()).unwrap();
new_block.header.nonce = OsRng.next_u64();
// we take the max ftl time and give 10 seconds for mining then check it, it should still be more than the ftl
new_block.header.timestamp = genesis.header().timestamp.checked_sub(100.into()).unwrap();
find_header_with_achieved_difficulty(&mut new_block.header, 20.into());
assert!(header_validator
.validate(
&*db.db_read_access().unwrap(),
&new_block.header,
&difficulty_calculator,
)
.is_err());

// lets break difficulty
let mut new_block = db.prepare_new_block(template).unwrap();
new_block.header.nonce = OsRng.next_u64();
Expand Down