zebra/zebra-chain/src/block.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

//! Blocks and block-related structures (heights, headers, etc.)
#![allow(clippy::unit_arg)]
mod commitment;
mod hash;
mod header;
2020-08-14 23:51:41 -07:00
mod height;
mod serialize;
pub mod merkle;
#[cfg(any(test, feature = "proptest-impl"))]
mod arbitrary;
#[cfg(test)]
mod tests;
use std::fmt;
pub use commitment::Commitment;
pub use hash::Hash;
pub use header::BlockTimeError;
pub use header::{CountedHeader, Header};
pub use height::Height;
2020-08-15 22:25:30 -07:00
use serde::{Deserialize, Serialize};
use crate::{fmt::DisplayToDebug, parameters::Network, transaction::Transaction, transparent};
2020-08-15 22:25:30 -07:00
2020-08-16 12:08:24 -07:00
/// A Zcash block, containing a header and a list of transactions.
2020-08-15 22:25:30 -07:00
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Block {
/// The block header, containing block metadata.
pub header: Header,
2020-08-15 22:25:30 -07:00
/// The block transactions.
pub transactions: Vec<std::sync::Arc<Transaction>>,
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut fmter = f.debug_struct("Block");
if let Some(height) = self.coinbase_height() {
fmter.field("height", &height);
}
fmter.field("hash", &DisplayToDebug(self.hash())).finish()
}
}
2020-08-15 22:25:30 -07:00
impl Block {
/// Return the block height reported in the coinbase transaction, if any.
pub fn coinbase_height(&self) -> Option<Height> {
2020-08-15 22:25:30 -07:00
self.transactions
.get(0)
.and_then(|tx| tx.inputs().get(0))
.and_then(|input| match input {
transparent::Input::Coinbase { ref height, .. } => Some(*height),
2020-08-15 22:25:30 -07:00
_ => None,
})
}
/// Compute the hash of this block.
pub fn hash(&self) -> Hash {
Hash::from(self)
2020-08-15 22:25:30 -07:00
}
/// Get the parsed root hash for this block.
///
/// The interpretation of the root hash depends on the
/// configured `network`, and this block's height.
///
/// Returns None if this block does not have a block height.
pub fn commitment(&self, network: Network) -> Option<Commitment> {
self.coinbase_height()
.map(|height| Commitment::from_bytes(self.header.commitment_bytes, network, height))
2020-08-15 22:25:30 -07:00
}
}
impl<'a> From<&'a Block> for Hash {
fn from(block: &'a Block) -> Hash {
2020-08-15 22:25:30 -07:00
(&block.header).into()
}
}