use crate::core::consensus;
use crate::core::core::block;
use crate::core::core::feijoada::{is_allowed_policy, PoWType};
use crate::core::core::hash::{Hash, Hashed};
use crate::core::core::Committed;
use crate::core::core::{Block, BlockHeader, BlockSums};
use crate::core::global;
use crate::core::pow;
use crate::error::{Error, ErrorKind};
use crate::store;
use crate::store::BottleIter;
use crate::txhashset;
use crate::types::{CommitPos, Options, Tip};
use chrono::prelude::Utc;
use chrono::Duration;
use epic_store;
pub struct BlockContext<'a> {
pub opts: Options,
pub pow_verifier: fn(&BlockHeader) -> Result<(), pow::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, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
check_known_head(header, ctx)?;
check_known_store(header, 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>, Error> {
debug!(
"pipe: process_block {} at {} [in/out/kern: {}/{}/{}]",
b.hash(),
b.header.height,
b.inputs().len(),
b.outputs().len(),
b.kernels().len(),
);
check_known(&b.header, ctx)?;
validate_pow_only(&b.header, ctx)?;
let head = ctx.batch.head()?;
let prev = prev_header_store(&b.header, &mut ctx.batch)?;
{
let is_next = b.header.prev_hash == head.last_block_h;
if !is_next && !ctx.batch.block_exists(&prev.hash())? {
return Err(ErrorKind::Orphan.into());
}
}
process_block_header(&b.header, ctx)?;
validate_block(b, ctx)?;
let ref mut header_pmmr = &mut ctx.header_pmmr;
let ref mut txhashset = &mut ctx.txhashset;
let ref mut batch = &mut ctx.batch;
let (block_sums, spent) = txhashset::extending(header_pmmr, txhashset, batch, |ext, batch| {
rewind_and_apply_fork(&prev, ext, batch)?;
verify_coinbase_maturity(b, ext, batch)?;
validate_utxo(b, ext, batch)?;
let block_sums = verify_block_sums(b, batch)?;
let spent = apply_block_to_txhashset(b, ext, batch)?;
let head = batch.head()?;
if !has_more_work(&b.header, &head) {
ext.extension.force_rollback();
}
Ok((block_sums, spent))
})?;
add_block(b, &block_sums, &spent, &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))
} else {
Ok(None)
}
}
pub fn sync_block_headers(
headers: &[BlockHeader],
ctx: &mut BlockContext<'_>,
) -> Result<(), Error> {
if headers.is_empty() {
return Ok(());
}
let last_header = headers.last().expect("last header");
let sync_head = ctx.batch.get_sync_head()?;
if let Ok(existing) = ctx.batch.get_block_header(&last_header.hash()) {
if !has_more_work(&existing, &sync_head) {
return Ok(());
}
}
for header in headers {
validate_header(header, ctx)?;
add_block_header(header, &ctx.batch)?;
}
txhashset::header_extending(
&mut ctx.header_pmmr,
&sync_head,
&mut ctx.batch,
|ext, batch| {
rewind_and_apply_header_fork(&last_header, ext, batch)?;
Ok(())
},
)?;
if has_more_work(&last_header, &sync_head) {
update_sync_head(&Tip::from_header(&last_header), &mut ctx.batch)?;
}
Ok(())
}
pub fn process_block_header(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
let prev_header = ctx.batch.get_previous_header(&header)?;
if check_known(header, ctx).is_err() {
return Ok(());
}
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(());
}
}
txhashset::header_extending(
&mut ctx.header_pmmr,
&header_head,
&mut ctx.batch,
|ext, batch| {
rewind_and_apply_header_fork(&prev_header, ext, batch)?;
ext.validate_root(header)?;
ext.apply_header(header)?;
if !has_more_work(&header, &header_head) {
ext.force_rollback();
}
Ok(())
},
)?;
validate_header(header, ctx)?;
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, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
let head = ctx.batch.head()?;
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, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
match ctx.batch.block_exists(&header.hash()) {
Ok(true) => {
let head = ctx.batch.head()?;
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).map_err(|e| match e {
epic_store::Error::NotFoundErr(_) => ErrorKind::Orphan,
_ => ErrorKind::StoreErr(e, "check prev header".into()),
})?;
Ok(prev)
}
fn seed_header_store(seed: &[u8; 32], batch: &mut store::Batch<'_>) -> Result<BlockHeader, Error> {
let prev = batch.get_block_header(&Hash::from_vec(seed))?;
Ok(prev)
}
fn validate_header(header: &BlockHeader, ctx: &mut BlockContext<'_>) -> Result<(), Error> {
if !consensus::valid_header_version(header.height, header.version) {
error!(
"Invalid block header version received ({:?}), maybe update Epic?",
header.version
);
return Err(ErrorKind::InvalidBlockVersion(header.version).into());
}
if header.timestamp > Utc::now() + Duration::seconds(12 * (consensus::BLOCK_TIME_SEC as i64))
&& !global::is_automated_testing_mode()
{
return Err(ErrorKind::InvalidBlockTime.into());
}
check_bad_header(header)?;
if !ctx.opts.contains(Options::SKIP_POW) {
if !header.pow.is_primary() && !header.pow.is_secondary() {
return Err(ErrorKind::LowEdgebits.into());
}
let edge_bits = header.pow.edge_bits();
if !(ctx.pow_verifier)(header).is_ok() {
match header.pow.proof {
pow::Proof::RandomXProof { ref hash } => {
error!("pipe: error validating header with randomx hash {:?}", hash);
}
pow::Proof::ProgPowProof { ref mix } => {
error!(
"pipe: error validating header with progpow mix hash {:?}",
mix
);
}
_ => {
error!(
"pipe: error validating header with cuckoo edge_bits {}",
edge_bits
);
}
};
return Err(ErrorKind::InvalidPow.into());
}
}
let prev = prev_header_store(header, &mut ctx.batch)?;
let header_seed =
seed_header_store(&header.pow.seed, &mut ctx.batch).map_err(|_| ErrorKind::InvalidSeed)?;
if header_seed.height != pow::randomx::rx_current_seed_height(header.height) {
return Err(ErrorKind::InvalidSeed.into());
}
if !is_allowed_policy(global::get_allowed_policies(), header.height, header.policy) {
return Err(ErrorKind::PolicyIsNotAllowed.into());
}
if let Some(_p) = global::get_policies(header.policy) {
let cursor = BottleIter::from_batch(prev.hash(), &ctx.batch, header.policy);
let (algo, _) = consensus::next_policy(header.policy, cursor);
let is_correct = match header.pow.proof {
pow::Proof::CuckooProof { edge_bits, .. } => {
if edge_bits == 29 {
algo == PoWType::Cuckaroo
} else {
algo == PoWType::Cuckatoo
}
}
pow::Proof::RandomXProof { .. } => algo == PoWType::RandomX,
pow::Proof::ProgPowProof { .. } => algo == PoWType::ProgPow,
pow::Proof::MD5Proof { .. } => false,
};
if !is_correct {
debug!(
"Block rejected: Expected {:?} got {:?}",
algo, header.pow.proof
);
return Err(ErrorKind::InvalidSortAlgo.into());
}
} else {
return Err(ErrorKind::ThereIsNotPolicy.into());
}
if header.height != prev.height + 1 {
return Err(ErrorKind::InvalidBlockHeight.into());
}
if header.timestamp <= prev.timestamp && !global::is_automated_testing_mode() {
return Err(ErrorKind::InvalidBlockTime.into());
}
if !ctx.opts.contains(Options::SKIP_POW) {
let target_difficulty = header.total_difficulty() - prev.total_difficulty();
let target_difficulty_proof = target_difficulty.to_num((&header.pow.proof).into());
let diff = header
.pow
.to_difficulty(&header.pre_pow(), header.height, header.pow.nonce);
let diff_proof = diff.to_num((&header.pow.proof).into());
if diff_proof < target_difficulty_proof {
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 = if header.height < consensus::difficultyfix_height() {
consensus::next_difficulty(header.height, (&prev.pow.proof).into(), diff_iter)
} else {
consensus::next_difficulty_era1(header.height, (&prev.pow.proof).into(), diff_iter)
};
if target_difficulty != next_header_info.difficulty {
info!(
"validate_header: header target difficulty {:?} != {:?}",
target_difficulty.num, next_header_info.difficulty.num
);
return Err(ErrorKind::WrongTotalDifficulty.into());
}
if let pow::Proof::CuckooProof { .. } = header.pow.proof {
if 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 ref extension = ext.extension;
let ref 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<BlockSums, 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)?;
Ok(BlockSums {
utxo_sum,
kernel_sum,
})
}
fn apply_block_to_txhashset(
block: &Block,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<Vec<CommitPos>, Error> {
let spent = ext.extension.apply_block(block, batch)?;
ext.extension.validate_roots(&block.header)?;
ext.extension.validate_sizes(&block.header)?;
Ok(spent)
}
fn add_block(
b: &Block,
block_sums: &BlockSums,
spent: &Vec<CommitPos>,
batch: &store::Batch<'_>,
) -> Result<(), Error> {
batch.save_block(b)?;
batch.save_block_sums(&b.hash(), block_sums)?;
batch.save_spent_index(&b.hash(), spent)?;
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_sync_head(head: &Tip, batch: &mut store::Batch<'_>) -> Result<(), Error> {
batch
.save_sync_head(&head)
.map_err(|e| ErrorKind::StoreErr(e, "pipe save sync head".to_owned()))?;
debug!(
"sync_head updated to {} at {}",
head.last_block_h, head.height
);
Ok(())
}
fn update_header_head(head: &Tip, batch: &mut 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: &mut 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<'_>,
) -> Result<(), Error> {
let mut fork_hashes = vec![];
let mut current = header.clone();
while current.height > 0 && ext.is_on_current_chain(¤t, batch).is_err() {
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()))?;
ext.validate_root(&header)?;
ext.apply_header(&header)?;
}
Ok(())
}
pub fn rewind_and_apply_fork(
header: &BlockHeader,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<(), Error> {
let ref mut extension = ext.extension;
let ref mut header_extension = ext.header_extension;
rewind_and_apply_header_fork(header, header_extension, batch)?;
let mut current = batch.head_header()?;
while current.height > 0
&& header_extension
.is_on_current_chain(¤t, batch)
.is_err()
{
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(())
}
fn validate_utxo(
block: &Block,
ext: &mut txhashset::ExtensionPair<'_>,
batch: &store::Batch<'_>,
) -> Result<(), Error> {
let ref mut extension = ext.extension;
let ref mut header_extension = ext.header_extension;
extension
.utxo_view(header_extension)
.validate_block(block, batch)
}
fn check_bad_header(header: &BlockHeader) -> Result<(), Error> {
let bad_hashes = [
Hash::from_hex("840cdf3ad968bd6895b07e4e3235ee704226f85c3163d2da2e6764c7e2b81ea2").unwrap(),
Hash::from_hex("a98bbc899892d2553c52ef17cab6d708f9eaf7d575b3d62ca49bbf9d50ae55a7").unwrap(),
];
if bad_hashes.contains(&header.hash()) {
Err(ErrorKind::InvalidBlockProof(block::Error::Other("explicit bad header".into())).into())
} else {
Ok(())
}
}