use std::{fmt, io::Write};
use hex::{FromHex, ToHex};
use crate::{
serialization::{sha256d, BytesInDisplayOrder},
transaction::{self, Transaction, UnminedTx, UnminedTxId, VerifiedUnminedTx},
};
#[cfg(any(test, feature = "proptest-impl"))]
use proptest_derive::Arbitrary;
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary, Default))]
pub struct Root(pub [u8; 32]);
impl fmt::Debug for Root {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Root").field(&hex::encode(self.0)).finish()
}
}
impl From<[u8; 32]> for Root {
fn from(hash: [u8; 32]) -> Self {
Root(hash)
}
}
impl From<Root> for [u8; 32] {
fn from(hash: Root) -> Self {
hash.0
}
}
impl BytesInDisplayOrder<true> for Root {
fn bytes_in_serialized_order(&self) -> [u8; 32] {
self.0
}
fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
Root(bytes)
}
}
impl ToHex for &Root {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
self.bytes_in_display_order().encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
self.bytes_in_display_order().encode_hex_upper()
}
}
impl ToHex for Root {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex_upper()
}
}
impl FromHex for Root {
type Error = <[u8; 32] as FromHex>::Error;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let mut hash = <[u8; 32]>::from_hex(hex)?;
hash.reverse();
Ok(hash.into())
}
}
fn hash(h1: &[u8; 32], h2: &[u8; 32]) -> [u8; 32] {
let mut w = sha256d::Writer::default();
w.write_all(h1).unwrap();
w.write_all(h2).unwrap();
w.finish()
}
fn auth_data_hash(h1: &[u8; 32], h2: &[u8; 32]) -> [u8; 32] {
blake2b_simd::Params::new()
.hash_length(32)
.personal(b"ZcashAuthDatHash")
.to_state()
.update(h1)
.update(h2)
.finalize()
.as_bytes()
.try_into()
.expect("32 byte array")
}
impl<T> std::iter::FromIterator<T> for Root
where
T: std::convert::AsRef<Transaction>,
{
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = T>,
{
transactions
.into_iter()
.map(|tx| tx.as_ref().hash())
.collect()
}
}
impl std::iter::FromIterator<UnminedTx> for Root {
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = UnminedTx>,
{
transactions
.into_iter()
.map(|tx| tx.id.mined_id())
.collect()
}
}
impl std::iter::FromIterator<UnminedTxId> for Root {
fn from_iter<I>(tx_ids: I) -> Self
where
I: IntoIterator<Item = UnminedTxId>,
{
tx_ids.into_iter().map(|tx_id| tx_id.mined_id()).collect()
}
}
impl std::iter::FromIterator<VerifiedUnminedTx> for Root {
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = VerifiedUnminedTx>,
{
transactions
.into_iter()
.map(|tx| tx.transaction.id.mined_id())
.collect()
}
}
impl std::iter::FromIterator<transaction::Hash> for Root {
fn from_iter<I>(hashes: I) -> Self
where
I: IntoIterator<Item = transaction::Hash>,
{
let mut hashes = hashes.into_iter().map(|hash| hash.0).collect::<Vec<_>>();
while hashes.len() > 1 {
hashes = hashes
.chunks(2)
.map(|chunk| match chunk {
[h1, h2] => hash(h1, h2),
[h1] => hash(h1, h1),
_ => unreachable!("chunks(2)"),
})
.collect();
}
Self(hashes[0])
}
}
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
pub struct AuthDataRoot(pub(crate) [u8; 32]);
impl fmt::Debug for AuthDataRoot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("AuthRoot")
.field(&hex::encode(self.0))
.finish()
}
}
impl From<[u8; 32]> for AuthDataRoot {
fn from(hash: [u8; 32]) -> Self {
AuthDataRoot(hash)
}
}
impl From<AuthDataRoot> for [u8; 32] {
fn from(hash: AuthDataRoot) -> Self {
hash.0
}
}
impl BytesInDisplayOrder<true> for AuthDataRoot {
fn bytes_in_serialized_order(&self) -> [u8; 32] {
self.0
}
fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
AuthDataRoot(bytes)
}
}
impl ToHex for &AuthDataRoot {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
self.bytes_in_display_order().encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
self.bytes_in_display_order().encode_hex_upper()
}
}
impl ToHex for AuthDataRoot {
fn encode_hex<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex()
}
fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
(&self).encode_hex_upper()
}
}
impl FromHex for AuthDataRoot {
type Error = <[u8; 32] as FromHex>::Error;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let mut hash = <[u8; 32]>::from_hex(hex)?;
hash.reverse();
Ok(hash.into())
}
}
pub const AUTH_DIGEST_PLACEHOLDER: transaction::AuthDigest = transaction::AuthDigest([0xFF; 32]);
impl<T> std::iter::FromIterator<T> for AuthDataRoot
where
T: std::convert::AsRef<Transaction>,
{
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = T>,
{
transactions
.into_iter()
.map(|tx| tx.as_ref().auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
.collect()
}
}
impl std::iter::FromIterator<UnminedTx> for AuthDataRoot {
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = UnminedTx>,
{
transactions
.into_iter()
.map(|tx| tx.id.auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
.collect()
}
}
impl std::iter::FromIterator<VerifiedUnminedTx> for AuthDataRoot {
fn from_iter<I>(transactions: I) -> Self
where
I: IntoIterator<Item = VerifiedUnminedTx>,
{
transactions
.into_iter()
.map(|tx| {
tx.transaction
.id
.auth_digest()
.unwrap_or(AUTH_DIGEST_PLACEHOLDER)
})
.collect()
}
}
impl std::iter::FromIterator<UnminedTxId> for AuthDataRoot {
fn from_iter<I>(tx_ids: I) -> Self
where
I: IntoIterator<Item = UnminedTxId>,
{
tx_ids
.into_iter()
.map(|tx_id| tx_id.auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
.collect()
}
}
impl std::iter::FromIterator<transaction::AuthDigest> for AuthDataRoot {
fn from_iter<I>(hashes: I) -> Self
where
I: IntoIterator<Item = transaction::AuthDigest>,
{
let mut hashes = hashes.into_iter().map(|hash| hash.0).collect::<Vec<_>>();
let pad_count = hashes.len().next_power_of_two() - hashes.len();
hashes.extend(std::iter::repeat_n([0u8; 32], pad_count));
assert!(hashes.len().is_power_of_two());
while hashes.len() > 1 {
hashes = hashes
.chunks(2)
.map(|chunk| match chunk {
[h1, h2] => auth_data_hash(h1, h2),
_ => unreachable!("number of nodes is always even since tree is full"),
})
.collect();
}
Self(hashes[0])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{block::Block, serialization::ZcashDeserialize, transaction::AuthDigest};
#[test]
fn block_test_vectors() {
for block_bytes in zebra_test::vectors::BLOCKS.iter() {
let block = Block::zcash_deserialize(&**block_bytes).unwrap();
let merkle_root = block.transactions.iter().collect::<Root>();
assert_eq!(
merkle_root,
block.header.merkle_root,
"block: {:?} {:?} transaction hashes: {:?}",
block.coinbase_height().unwrap(),
block.hash(),
block
.transactions
.iter()
.map(|tx| tx.hash())
.collect::<Vec<_>>()
);
}
}
#[test]
fn auth_digest() {
for block_bytes in zebra_test::vectors::BLOCKS.iter() {
let block = Block::zcash_deserialize(&**block_bytes).unwrap();
let _auth_root = block.transactions.iter().collect::<AuthDataRoot>();
}
}
#[test]
fn auth_data_padding() {
let mut v = vec![
AuthDigest([0x42; 32]),
AuthDigest([0xAA; 32]),
AuthDigest([0x77; 32]),
];
let root_3 = v.iter().copied().collect::<AuthDataRoot>();
v.push(AuthDigest([0x00; 32]));
let root_4 = v.iter().copied().collect::<AuthDataRoot>();
assert_eq!(root_3, root_4);
}
#[test]
fn auth_data_pre_v5() {
let block =
Block::zcash_deserialize(&**zebra_test::vectors::BLOCK_MAINNET_1046400_BYTES).unwrap();
let auth_root = block.transactions.iter().take(1).collect::<AuthDataRoot>();
let expect_auth_root = [AuthDigest([0xFF; 32])]
.iter()
.copied()
.collect::<AuthDataRoot>();
assert_eq!(auth_root, expect_auth_root);
}
}