use crate::core::consensus;
use crate::core::core::hash::{Hash, Hashed};
use crate::core::core::Committed;
use crate::core::core::{
block, Block, BlockHeader, BlockSums, HeaderVersion, OutputIdentifier, TransactionBody,
};
use crate::core::global;
use crate::core::pow;
use crate::error::{Error, ErrorKind};
use crate::store;
use crate::txhashset;
use crate::types::{CommitPos, Options, Tip};
pub struct BlockContext<'a> {
pub opts: Options,
pub pow_verifier: fn(&BlockHeader) -> Result<(), pow::Error>,
pub header_allowed: Box<dyn Fn(&BlockHeader) -> Result<(), Error>>,
pub txhashset: &'a mut txhashset::TxHashSet,
pub header_pmmr: &'a mut txhashset::PMMRHandle<BlockHeader>,
pub batch: store::Batch<'a>,
}
fn check_known(header: &BlockHeader, head: &Tip, ctx: &BlockContext<'_>) -> Result<(), Error> {
if header.total_difficulty() <= head.total_difficulty {
check_known_head(header, head)?;
check_known_store(header, head, ctx)?;
}
Ok(())
}
fn validate_pow_only(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
if ctx.opts.contains(Options::SKIP_POW) {
return Ok(());
}
if !header.pow.is_primary() && !header.pow.is_secondary() {
return Err(ErrorKind::LowEdgebits.into());
}
if (ctx.pow_verifier)(header).is_err() {
error!(
"pipe: error validating header with cuckoo edge_bits {}",
header.pow.edge_bits(),
);
return Err(ErrorKind::InvalidPow.into());
}
Ok(())
}
pub fn process_block(
b: &Block,
ctx: &mut BlockContext<'_>,
) -> Result<(Option<Tip>, BlockHeader), Error> {
debug!(
"pipe: process_block {} at {} [in/out/kern: {}/{}/{}] ({})",
b.hash(),
b.header.height,
b.inputs().len(),
b.outputs().len(),
b.kernels().len(),
b.inputs().version_str(),
);
let head = ctx.batch.head()?;
check_known(&b.header, &head, ctx)?;
validate_pow_only(&b.header, ctx)?;
let prev = prev_header_store(&b.header, &mut ctx.batch)?;
process_block_header(&b.header, ctx)?;
validate_block(b, ctx)?;
let header_pmmr = &mut ctx.header_pmmr;
let txhashset = &mut ctx.txhashset;
let batch = &mut ctx.batch;
let ctx_specific_validation = &ctx.header_allowed;
let fork_point = txhashset::extending(header_pmmr, txhashset, batch, |ext, batch| {
let fork_point = rewind_and_apply_fork(&prev, ext, batch, ctx_specific_validation)?;
verify_coinbase_maturity(b, ext, batch)?;
validate_utxo(b, ext, batch)?;
verify_block_sums(b, batch)?;
apply_block_to_txhashset(b, ext, batch)?;
let head = batch.head()?;
if !has_more_work(&b.header, &head) {
ext.extension.force_rollback();
}
Ok(fork_point)
})?;
add_block(b, &ctx.batch)?;
if ctx.batch.tail().is_err() {
update_body_tail(&b.header, &ctx.batch)?;
}
if has_more_work(&b.header, &head) {
let head = Tip::from_header(&b.header);
update_head(&head, &mut ctx.batch)?;
Ok((Some(head), fork_point))
} else {
Ok((None, fork_point))
}
}
pub fn process_block_headers(
headers: &[BlockHeader],
sync_head: Tip,
ctx: &mut BlockContext<'_>,
) -> Result<Option<Tip>, Error> {
if headers.is_empty() {
return Ok(None);
}
let last_header = headers.last().expect("last header");
let head = ctx.batch.header_head()?;
for header in headers {
validate_header(header, ctx)?;
add_block_header(header, &ctx.batch)?;
}
let ctx_specific_validation = &ctx.header_allowed;
txhashset::header_extending(&mut ctx.header_pmmr, &mut ctx.batch, |ext, batch| {
rewind_and_apply_header_fork(&last_header, ext, batch, ctx_specific_validation)?;
let alt_fork = !ext.is_on_current_chain(sync_head, batch)?;
if has_more_work(last_header, &head) {
let header_head = last_header.into();
update_header_head(&header_head, &batch)?;
} else {
ext.force_rollback();
};
if alt_fork || has_more_work(last_header, &sync_head) {
Ok(Some(last_header.into()))
} else {
Ok(None)
}
})
}
pub fn process_block_header(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
{
let head = ctx.batch.head()?;
if check_known(header, &head, ctx).is_err() {
return Ok(());
}
}
let prev_header = ctx.batch.get_previous_header(&header)?;
let header_head = ctx.batch.header_head()?;
if let Ok(existing) = ctx.batch.get_block_header(&header.hash()) {
if !has_more_work(&existing, &header_head) {
return Ok(());
}
}
validate_header(header, ctx)?;
let ctx_specific_validation = &ctx.header_allowed;
txhashset::header_extending(&mut ctx.header_pmmr, &mut ctx.batch, |ext, batch| {
rewind_and_apply_header_fork(&prev_header, ext, batch, ctx_specific_validation)?;
ext.validate_root(header)?;
ext.apply_header(header)?;
if !has_more_work(&header, &header_head) {
ext.force_rollback();
}
Ok(())
})?;
add_block_header(header, &ctx.batch)?;
if has_more_work(header, &header_head) {
update_header_head(&Tip::from_header(header), &mut ctx.batch)?;
}
Ok(())
}
fn check_known_head(header: &BlockHeader, head: &Tip) -> Result<(), Error> {
let bh = header.hash();
if bh == head.last_block_h || bh == head.prev_block_h {
return Err(ErrorKind::Unfit("already known in head".to_string()).into());
}
Ok(())
}
fn check_known_store(
header: &BlockHeader,
head: &Tip,
ctx: &BlockContext<'_>,
) -> Result<(), Error> {
match ctx.batch.block_exists(&header.hash()) {
Ok(true) => {
if header.height < head.height.saturating_sub(50) {
Err(ErrorKind::OldBlock.into())
} else {
Err(ErrorKind::Unfit("already known in store".to_string()).into())
}
}
Ok(false) => {
Ok(())
}
Err(e) => Err(ErrorKind::StoreErr(e, "pipe get this block".to_owned()).into()),
}
}
fn prev_header_store(
header: &BlockHeader,
batch: &mut store::Batch<'_>,
) -> Result<BlockHeader, Error> {
let prev = batch.get_previous_header(&header)?;
Ok(prev)
}
fn validate_header_ctx(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
(ctx.header_allowed)(header)
}
pub fn validate_header_denylist(header: &BlockHeader, denylist: &[Hash]) -> Result<(), Error> {
if denylist.is_empty() {
return Ok(());
}
debug!(
"validate_header_denylist: {} at {}, denylist: {:?}",
header.hash(),
header.height,
denylist
);
if denylist.contains(&header.hash()) {
return Err(ErrorKind::Block(block::Error::Other("header hash denied".into())).into());
} else {
return Ok(());
}
}
fn validate_header(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
validate_header_ctx(header, ctx)?;
let prev = prev_header_store(header, &mut ctx.batch)?;
if header.height != prev.height + 1 {
return Err(ErrorKind::InvalidBlockHeight.into());
}
if !consensus::valid_header_version(header.height, header.version) {
return Err(ErrorKind::InvalidBlockVersion(header.version).into());
}
if header.timestamp <= prev.timestamp {
return Err(ErrorKind::InvalidBlockTime.into());
}
let num_outputs = header
.output_mmr_count()
.saturating_sub(prev.output_mmr_count());
let num_kernels = header
.kernel_mmr_count()
.saturating_sub(prev.kernel_mmr_count());
if num_outputs == 0 || num_kernels == 0 {
return Err(ErrorKind::InvalidMMRSize.into());
}
let weight = TransactionBody::weight_by_iok(0, num_outputs, num_kernels);
if weight > global::max_block_weight() {
return Err(ErrorKind::Block(block::Error::TooHeavy).into());
}
if !ctx.opts.contains(Options::SKIP_POW) {
validate_pow_only(header, ctx)?;
if header.total_difficulty() <= prev.total_difficulty() {
return Err(ErrorKind::DifficultyTooLow.into());
}
let target_difficulty = header.total_difficulty() - prev.total_difficulty();
if header.pow.to_difficulty(header.height) < target_difficulty {
return Err(ErrorKind::DifficultyTooLow.into());
}
let child_batch = ctx.batch.child()?;
let diff_iter = store::DifficultyIter::from_batch(prev.hash(), child_batch);
let next_header_info = consensus::next_difficulty(header.height, diff_iter);
if target_difficulty != next_header_info.difficulty {
info!(
"validate_header: header target difficulty {} != {}",
target_difficulty.to_num(),
next_header_info.difficulty.to_num()
);
return Err(ErrorKind::WrongTotalDifficulty.into());
}
if header.version < HeaderVersion(5)
&& header.pow.secondary_scaling != next_header_info.secondary_scaling
{
info!(
"validate_header: header secondary scaling {} != {}",
header.pow.secondary_scaling, next_header_info.secondary_scaling
);
return Err(ErrorKind::InvalidScaling.into());
}
}
Ok(())
}
fn validate_block(block: &Block, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
let prev = ctx.batch.get_previous_header(&block.header)?;
block
.validate(&prev.total_kernel_offset)
.map_err(ErrorKind::InvalidBlockProof)?;
Ok(())
}
fn verify_coinbase_maturity(
block: &Block,
ext: &txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<(), Error> {
let extension = &ext.extension;
let header_extension = &ext.header_extension;
extension
.utxo_view(header_extension)
.verify_coinbase_maturity(&block.inputs(), block.header.height, batch)
}
fn verify_block_sums(b: &Block, batch: &store::Batch<'_>) -> Result<(), Error> {
let block_sums = batch.get_block_sums(&b.header.prev_hash)?;
let overage = b.header.overage();
let offset = b.header.total_kernel_offset();
let (utxo_sum, kernel_sum) =
(block_sums, b as &dyn Committed).verify_kernel_sums(overage, offset)?;
batch.save_block_sums(
&b.hash(),
BlockSums {
utxo_sum,
kernel_sum,
},
)?;
Ok(())
}
fn apply_block_to_txhashset(
block: &Block,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<(), Error> {
ext.extension
.apply_block(block, ext.header_extension, batch)?;
ext.extension.validate_roots(&block.header)?;
ext.extension.validate_sizes(&block.header)?;
Ok(())
}
fn add_block(b: &Block, batch: &store::Batch<'_>) -> Result<(), Error> {
batch.save_block(b)?;
Ok(())
}
fn update_body_tail(bh: &BlockHeader, batch: &store::Batch<'_>) -> Result<(), Error> {
let tip = Tip::from_header(bh);
batch
.save_body_tail(&tip)
.map_err(|e| ErrorKind::StoreErr(e, "pipe save body tail".to_owned()))?;
debug!("body tail {} @ {}", bh.hash(), bh.height);
Ok(())
}
fn add_block_header(bh: &BlockHeader, batch: &store::Batch<'_>) -> Result<(), Error> {
batch
.save_block_header(bh)
.map_err(|e| ErrorKind::StoreErr(e, "pipe save header".to_owned()))?;
Ok(())
}
fn update_header_head(head: &Tip, batch: &store::Batch<'_>) -> Result<(), Error> {
batch
.save_header_head(&head)
.map_err(|e| ErrorKind::StoreErr(e, "pipe save header head".to_owned()))?;
debug!(
"header head updated to {} at {}",
head.last_block_h, head.height
);
Ok(())
}
fn update_head(head: &Tip, batch: &store::Batch<'_>) -> Result<(), Error> {
batch
.save_body_head(&head)
.map_err(|e| ErrorKind::StoreErr(e, "pipe save body".to_owned()))?;
debug!("head updated to {} at {}", head.last_block_h, head.height);
Ok(())
}
fn has_more_work(header: &BlockHeader, head: &Tip) -> bool {
header.total_difficulty() > head.total_difficulty
}
pub fn rewind_and_apply_header_fork(
header: &BlockHeader,
ext: &mut txhashset::HeaderExtension<'_>,
batch: &store::Batch<'_>,
ctx_specific_validation: &dyn Fn(&BlockHeader) -> Result<(), Error>,
) -> Result<(), Error> {
let mut fork_hashes = vec![];
let mut current = header.clone();
while current.height > 0 && !ext.is_on_current_chain(¤t, batch)? {
fork_hashes.push(current.hash());
current = batch.get_previous_header(¤t)?;
}
fork_hashes.reverse();
let forked_header = current;
ext.rewind(&forked_header)?;
for h in fork_hashes {
let header = batch
.get_block_header(&h)
.map_err(|e| ErrorKind::StoreErr(e, "getting forked headers".to_string()))?;
(ctx_specific_validation)(&header)?;
ext.validate_root(&header)?;
ext.apply_header(&header)?;
}
Ok(())
}
pub fn rewind_and_apply_fork(
header: &BlockHeader,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
ctx_specific_validation: &dyn Fn(&BlockHeader) -> Result<(), Error>,
) -> Result<BlockHeader, Error> {
let extension = &mut ext.extension;
let header_extension = &mut ext.header_extension;
rewind_and_apply_header_fork(header, header_extension, batch, ctx_specific_validation)?;
let mut current = batch.head_header()?;
while current.height > 0 && !header_extension.is_on_current_chain(¤t, batch)? {
current = batch.get_previous_header(¤t)?;
}
let fork_point = current;
extension.rewind(&fork_point, batch)?;
let mut fork_hashes = vec![];
let mut current = header.clone();
while current.height > fork_point.height {
fork_hashes.push(current.hash());
current = batch.get_previous_header(¤t)?;
}
fork_hashes.reverse();
for h in fork_hashes {
let fb = batch
.get_block(&h)
.map_err(|e| ErrorKind::StoreErr(e, "getting forked blocks".to_string()))?;
verify_coinbase_maturity(&fb, ext, batch)?;
validate_utxo(&fb, ext, batch)?;
verify_block_sums(&fb, batch)?;
apply_block_to_txhashset(&fb, ext, batch)?;
}
Ok(fork_point)
}
fn validate_utxo(
block: &Block,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<Vec<(OutputIdentifier, CommitPos)>, Error> {
let extension = &ext.extension;
let header_extension = &ext.header_extension;
extension
.utxo_view(header_extension)
.validate_block(block, batch)
}