use crate::{
blocks::Block,
chain_storage::{BlockHeaderAccumulatedData, ChainBlock, ChainStorageError},
transactions::types::HashOutput,
};
use serde::{Deserialize, Serialize};
use std::{fmt, fmt::Display};
use tari_crypto::tari_utilities::hex::Hex;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct HistoricalBlock {
pub confirmations: u64,
block: Block,
pub accumulated_data: BlockHeaderAccumulatedData,
pruned_outputs: Vec<(HashOutput, HashOutput)>,
pruned_input_count: u64,
}
impl HistoricalBlock {
pub fn new(
block: Block,
confirmations: u64,
accumulated_data: BlockHeaderAccumulatedData,
pruned_outputs: Vec<(HashOutput, HashOutput)>,
pruned_input_count: u64,
) -> Self
{
HistoricalBlock {
block,
confirmations,
accumulated_data,
pruned_outputs,
pruned_input_count,
}
}
pub fn confirmations(&self) -> u64 {
self.confirmations
}
pub fn block(&self) -> &Block {
&self.block
}
pub fn hash(&self) -> &HashOutput {
&self.accumulated_data.hash
}
pub fn is_pruned(&self) -> bool {
!self.pruned_outputs.is_empty() || self.pruned_input_count > 0
}
pub fn try_into_block(self) -> Result<Block, ChainStorageError> {
if self.is_pruned() {
Err(ChainStorageError::BeyondPruningHorizon)
} else {
Ok(self.block)
}
}
pub fn try_into_chain_block(self) -> Result<ChainBlock, ChainStorageError> {
if self.is_pruned() {
Err(ChainStorageError::BeyondPruningHorizon)
} else {
Ok(ChainBlock {
accumulated_data: self.accumulated_data,
block: self.block,
})
}
}
pub fn pruned_outputs(&self) -> &[(HashOutput, HashOutput)] {
self.pruned_outputs.as_slice()
}
pub fn dissolve(self) -> (Block, BlockHeaderAccumulatedData, u64, u64) {
(
self.block,
self.accumulated_data,
self.confirmations,
self.pruned_input_count,
)
}
}
impl Display for HistoricalBlock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}", self.block())?;
if self.is_pruned() {
writeln!(f, "Pruned outputs: ")?;
for (output, proof) in &self.pruned_outputs {
writeln!(f, "Output hash: {} Proof:{}", output.to_hex(), proof.to_hex())?;
}
}
Ok(())
}
}
impl From<HistoricalBlock> for Block {
fn from(block: HistoricalBlock) -> Self {
block.block
}
}