2019-09-10 13:27:10 -07:00
|
|
|
|
//! Definitions of block datastructures.
|
2020-05-26 18:00:58 -07:00
|
|
|
|
#![allow(clippy::unit_arg)]
|
2019-09-10 13:27:10 -07:00
|
|
|
|
|
2020-01-31 21:27:51 -08:00
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests;
|
2020-01-31 18:02:02 -08:00
|
|
|
|
|
|
|
|
|
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
|
|
|
|
use chrono::{DateTime, TimeZone, Utc};
|
2020-01-31 20:31:30 -08:00
|
|
|
|
use std::{fmt, io};
|
2019-09-24 22:14:48 -07:00
|
|
|
|
|
2020-01-31 18:09:46 -08:00
|
|
|
|
#[cfg(test)]
|
|
|
|
|
use proptest_derive::Arbitrary;
|
|
|
|
|
|
2020-01-31 20:31:30 -08:00
|
|
|
|
use crate::equihash_solution::EquihashSolution;
|
2019-09-26 19:10:39 -07:00
|
|
|
|
use crate::merkle_tree::MerkleTreeRootHash;
|
2019-09-25 23:23:04 -07:00
|
|
|
|
use crate::note_commitment_tree::SaplingNoteTreeRootHash;
|
2020-01-31 20:31:30 -08:00
|
|
|
|
use crate::serialization::{ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize};
|
2019-09-24 22:14:48 -07:00
|
|
|
|
use crate::sha256d_writer::Sha256dWriter;
|
|
|
|
|
use crate::transaction::Transaction;
|
2020-02-08 13:19:32 -08:00
|
|
|
|
use crate::types::BlockHeight;
|
2019-09-24 22:14:48 -07:00
|
|
|
|
|
|
|
|
|
/// A SHA-256d hash of a BlockHeader.
|
|
|
|
|
///
|
|
|
|
|
/// This is useful when one block header is pointing to its parent
|
|
|
|
|
/// block header in the block chain. ⛓️
|
2019-09-26 19:42:44 -07:00
|
|
|
|
///
|
|
|
|
|
/// This is usually called a 'block hash', as it is frequently used
|
|
|
|
|
/// to identify the entire block, since the hash preimage includes
|
|
|
|
|
/// the merkle root of the transactions in this block. But
|
|
|
|
|
/// _technically_, this is just a hash of the block _header_, not
|
|
|
|
|
/// the direct bytes of the transactions as well as the header. So
|
|
|
|
|
/// for now I want to call it a `BlockHeaderHash` because that's
|
|
|
|
|
/// more explicit.
|
2020-02-07 09:22:33 -08:00
|
|
|
|
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
|
2020-01-31 18:09:46 -08:00
|
|
|
|
#[cfg_attr(test, derive(Arbitrary))]
|
2019-09-27 18:06:22 -07:00
|
|
|
|
pub struct BlockHeaderHash(pub [u8; 32]);
|
2019-09-24 22:14:48 -07:00
|
|
|
|
|
2019-10-15 15:51:53 -07:00
|
|
|
|
impl fmt::Debug for BlockHeaderHash {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
|
f.debug_tuple("BlockHeaderHash")
|
|
|
|
|
.field(&hex::encode(&self.0))
|
|
|
|
|
.finish()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-07 09:21:23 -08:00
|
|
|
|
impl<'a> From<&'a BlockHeader> for BlockHeaderHash {
|
|
|
|
|
fn from(block_header: &'a BlockHeader) -> Self {
|
2019-09-24 22:14:48 -07:00
|
|
|
|
let mut hash_writer = Sha256dWriter::default();
|
|
|
|
|
block_header
|
|
|
|
|
.zcash_serialize(&mut hash_writer)
|
2020-02-05 14:32:10 -08:00
|
|
|
|
.expect("Sha256dWriter is infallible");
|
2019-09-24 22:14:48 -07:00
|
|
|
|
Self(hash_writer.finish())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-08 16:39:35 -07:00
|
|
|
|
impl ZcashSerialize for BlockHeaderHash {
|
2020-02-05 14:32:10 -08:00
|
|
|
|
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
|
2019-10-08 16:39:35 -07:00
|
|
|
|
writer.write_all(&self.0)?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ZcashDeserialize for BlockHeaderHash {
|
|
|
|
|
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
|
2020-02-03 15:55:42 -08:00
|
|
|
|
Ok(BlockHeaderHash(reader.read_32_bytes()?))
|
2019-10-08 16:39:35 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-18 17:00:12 -07:00
|
|
|
|
impl std::str::FromStr for BlockHeaderHash {
|
|
|
|
|
type Err = SerializationError;
|
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
|
|
|
let mut bytes = [0; 32];
|
|
|
|
|
if hex::decode_to_slice(s, &mut bytes[..]).is_err() {
|
|
|
|
|
Err(SerializationError::Parse("hex decoding error"))
|
|
|
|
|
} else {
|
|
|
|
|
Ok(BlockHeaderHash(bytes))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-25 18:25:46 -07:00
|
|
|
|
/// Block header.
|
|
|
|
|
///
|
|
|
|
|
/// How are blocks chained together? They are chained together via the
|
|
|
|
|
/// backwards reference (previous header hash) present in the block
|
|
|
|
|
/// header. Each block points backwards to its parent, all the way
|
|
|
|
|
/// back to the genesis block (the first block in the blockchain).
|
2020-01-31 20:31:30 -08:00
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
2019-09-24 11:16:41 -07:00
|
|
|
|
pub struct BlockHeader {
|
2020-03-18 16:57:49 -07:00
|
|
|
|
/// The block's version field. This is supposed to be `4`:
|
|
|
|
|
///
|
|
|
|
|
/// > The current and only defined block version number for Zcash is 4.
|
|
|
|
|
///
|
|
|
|
|
/// but this was not enforced by the consensus rules, and defective mining
|
|
|
|
|
/// software created blocks with other versions, so instead it's effectively
|
|
|
|
|
/// a free field. The only constraint is that it must be at least `4` when
|
|
|
|
|
/// interpreted as an `i32`.
|
|
|
|
|
pub version: u32,
|
|
|
|
|
|
2019-09-24 11:16:41 -07:00
|
|
|
|
/// A SHA-256d hash in internal byte order of the previous block’s
|
|
|
|
|
/// header. This ensures no previous block can be changed without
|
2019-09-25 16:33:12 -07:00
|
|
|
|
/// also changing this block’s header.
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub previous_block_hash: BlockHeaderHash,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// A SHA-256d hash in internal byte order. The merkle root is
|
2019-09-24 22:14:48 -07:00
|
|
|
|
/// derived from the SHA256d hashes of all transactions included
|
|
|
|
|
/// in this block as assembled in a binary tree, ensuring that
|
|
|
|
|
/// none of those transactions can be modied without modifying the
|
|
|
|
|
/// header.
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub merkle_root_hash: MerkleTreeRootHash,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// [Sapling onward] The root LEBS2OSP256(rt) of the Sapling note
|
2020-06-04 01:18:55 -07:00
|
|
|
|
/// commitment tree corresponding to the final Sapling treestate of
|
2019-09-24 11:16:41 -07:00
|
|
|
|
/// this block.
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub final_sapling_root_hash: SaplingNoteTreeRootHash,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// The block timestamp is a Unix epoch time (UTC) when the miner
|
|
|
|
|
/// started hashing the header (according to the miner).
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub time: DateTime<Utc>,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// An encoded version of the target threshold this block’s header
|
|
|
|
|
/// hash must be less than or equal to, in the same nBits format
|
|
|
|
|
/// used by Bitcoin.
|
|
|
|
|
///
|
|
|
|
|
/// For a block at block height height, bits MUST be equal to
|
|
|
|
|
/// ThresholdBits(height).
|
|
|
|
|
///
|
|
|
|
|
/// [Bitcoin-nBits](https://bitcoin.org/en/developer-reference#target-nbits)
|
|
|
|
|
// pzec has their own wrapper around u32 for this field:
|
|
|
|
|
// https://github.com/ZcashFoundation/zebra/blob/master/zebra-primitives/src/compact.rs
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub bits: u32,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// An arbitrary field that miners can change to modify the header
|
|
|
|
|
/// hash in order to produce a hash less than or equal to the
|
|
|
|
|
/// target threshold.
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub nonce: [u8; 32],
|
2019-09-24 11:16:41 -07:00
|
|
|
|
|
|
|
|
|
/// The Equihash solution.
|
2020-02-07 09:10:08 -08:00
|
|
|
|
pub solution: EquihashSolution,
|
2019-09-24 11:16:41 -07:00
|
|
|
|
}
|
|
|
|
|
|
2019-09-24 22:14:48 -07:00
|
|
|
|
impl ZcashSerialize for BlockHeader {
|
2020-02-05 14:32:10 -08:00
|
|
|
|
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
|
2020-03-18 16:57:49 -07:00
|
|
|
|
writer.write_u32::<LittleEndian>(self.version)?;
|
2020-01-31 18:02:02 -08:00
|
|
|
|
self.previous_block_hash.zcash_serialize(&mut writer)?;
|
|
|
|
|
writer.write_all(&self.merkle_root_hash.0[..])?;
|
|
|
|
|
writer.write_all(&self.final_sapling_root_hash.0[..])?;
|
|
|
|
|
writer.write_u32::<LittleEndian>(self.time.timestamp() as u32)?;
|
2020-01-31 20:31:30 -08:00
|
|
|
|
writer.write_u32::<LittleEndian>(self.bits)?;
|
2020-01-31 18:02:02 -08:00
|
|
|
|
writer.write_all(&self.nonce[..])?;
|
2020-01-31 20:31:30 -08:00
|
|
|
|
self.solution.zcash_serialize(&mut writer)?;
|
2020-01-31 18:02:02 -08:00
|
|
|
|
Ok(())
|
2019-09-24 22:14:48 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ZcashDeserialize for BlockHeader {
|
2020-01-31 18:02:02 -08:00
|
|
|
|
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
|
2020-03-18 16:57:49 -07:00
|
|
|
|
// The Zcash specification says that
|
2020-02-03 17:02:30 -08:00
|
|
|
|
// "The current and only defined block version number for Zcash is 4."
|
2020-03-18 16:57:49 -07:00
|
|
|
|
// but this is not actually part of the consensus rules, and in fact
|
|
|
|
|
// broken mining software created blocks that do not have version 4.
|
|
|
|
|
// There are approximately 4,000 blocks with version 536870912; this
|
|
|
|
|
// is the bit-reversal of the value 4, indicating that that mining pool
|
|
|
|
|
// reversed bit-ordering of the version field. Because the version field
|
|
|
|
|
// was not properly validated, these blocks were added to the chain.
|
|
|
|
|
//
|
|
|
|
|
// The only possible way to work around this is to do a similar hack
|
|
|
|
|
// as the overwintered field in transaction parsing, which we do here:
|
|
|
|
|
// treat the high bit (which zcashd interprets as a sign bit) as an
|
|
|
|
|
// indicator that the version field is meaningful.
|
|
|
|
|
//
|
|
|
|
|
//
|
|
|
|
|
let (version, future_version_flag) = {
|
|
|
|
|
const LOW_31_BITS: u32 = (1 << 31) - 1;
|
|
|
|
|
let raw_version = reader.read_u32::<LittleEndian>()?;
|
|
|
|
|
(raw_version & LOW_31_BITS, raw_version >> 31 != 0)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if future_version_flag {
|
|
|
|
|
return Err(SerializationError::Parse(
|
|
|
|
|
"high bit was set in version field",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
if version < 4 {
|
|
|
|
|
return Err(SerializationError::Parse("version must be at least 4"));
|
2020-02-03 17:02:30 -08:00
|
|
|
|
}
|
|
|
|
|
|
2020-02-03 15:55:42 -08:00
|
|
|
|
Ok(BlockHeader {
|
2020-03-18 16:57:49 -07:00
|
|
|
|
version,
|
2020-01-31 18:02:02 -08:00
|
|
|
|
previous_block_hash: BlockHeaderHash::zcash_deserialize(&mut reader)?,
|
|
|
|
|
merkle_root_hash: MerkleTreeRootHash(reader.read_32_bytes()?),
|
|
|
|
|
final_sapling_root_hash: SaplingNoteTreeRootHash(reader.read_32_bytes()?),
|
|
|
|
|
time: Utc.timestamp(reader.read_u32::<LittleEndian>()? as i64, 0),
|
|
|
|
|
bits: reader.read_u32::<LittleEndian>()?,
|
|
|
|
|
nonce: reader.read_32_bytes()?,
|
2020-01-31 20:31:30 -08:00
|
|
|
|
solution: EquihashSolution::zcash_deserialize(reader)?,
|
2020-02-03 15:55:42 -08:00
|
|
|
|
})
|
2019-09-24 22:14:48 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-07 13:05:04 -08:00
|
|
|
|
/// A Zcash block, containing a [`BlockHeader`] and a sequence of
|
|
|
|
|
/// [`Transaction`]s.
|
2019-09-25 23:28:58 -07:00
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
2020-01-31 21:27:51 -08:00
|
|
|
|
#[cfg_attr(test, derive(Arbitrary))]
|
2019-09-24 11:16:41 -07:00
|
|
|
|
pub struct Block {
|
2020-02-07 13:05:04 -08:00
|
|
|
|
/// The block header, containing block metadata.
|
2019-09-24 11:16:41 -07:00
|
|
|
|
pub header: BlockHeader,
|
2019-09-25 16:33:12 -07:00
|
|
|
|
/// The block transactions.
|
2019-09-24 11:16:41 -07:00
|
|
|
|
pub transactions: Vec<Transaction>,
|
|
|
|
|
}
|
2019-09-26 19:38:18 -07:00
|
|
|
|
|
2020-02-08 13:19:32 -08:00
|
|
|
|
impl Block {
|
|
|
|
|
/// Return the block height reported in the coinbase transaction, if any.
|
|
|
|
|
pub fn coinbase_height(&self) -> Option<BlockHeight> {
|
|
|
|
|
use crate::transaction::TransparentInput;
|
|
|
|
|
self.transactions
|
|
|
|
|
.get(0)
|
|
|
|
|
.and_then(|tx| tx.inputs().next())
|
|
|
|
|
.and_then(|input| match input {
|
|
|
|
|
TransparentInput::Coinbase { ref height, .. } => Some(*height),
|
|
|
|
|
_ => None,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-07 09:21:23 -08:00
|
|
|
|
impl<'a> From<&'a Block> for BlockHeaderHash {
|
|
|
|
|
fn from(block: &'a Block) -> BlockHeaderHash {
|
|
|
|
|
(&block.header).into()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-26 19:38:18 -07:00
|
|
|
|
impl ZcashSerialize for Block {
|
2020-02-05 14:32:10 -08:00
|
|
|
|
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
|
2020-01-31 20:31:51 -08:00
|
|
|
|
self.header.zcash_serialize(&mut writer)?;
|
|
|
|
|
self.transactions.zcash_serialize(&mut writer)?;
|
|
|
|
|
Ok(())
|
2019-09-26 19:38:18 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ZcashDeserialize for Block {
|
2020-01-31 20:31:51 -08:00
|
|
|
|
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
|
|
|
|
|
Ok(Block {
|
|
|
|
|
header: BlockHeader::zcash_deserialize(&mut reader)?,
|
|
|
|
|
transactions: Vec::zcash_deserialize(&mut reader)?,
|
|
|
|
|
})
|
2019-09-26 19:38:18 -07:00
|
|
|
|
}
|
|
|
|
|
}
|