use std::fmt;
use hex::{FromHex, ToHex};
use thiserror::Error;
use crate::{
block::{self, merkle::AuthDataRoot},
parameters::{
Network,
NetworkUpgrade::{self, *},
},
sapling,
serialization::BytesInDisplayOrder,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum Commitment {
PreSaplingReserved([u8; 32]),
FinalSaplingRoot(sapling::tree::Root),
ChainHistoryActivationReserved,
ChainHistoryRoot(ChainHistoryMmrRootHash),
ChainHistoryBlockTxAuthCommitment(ChainHistoryBlockTxAuthCommitmentHash),
}
pub const CHAIN_HISTORY_ACTIVATION_RESERVED: [u8; 32] = [0; 32];
impl Commitment {
pub(super) fn from_bytes(
bytes: [u8; 32],
network: &Network,
height: block::Height,
) -> Result<Commitment, CommitmentError> {
use Commitment::*;
use CommitmentError::*;
match NetworkUpgrade::current_with_activation_height(network, height) {
(Genesis | BeforeOverwinter | Overwinter, _) => Ok(PreSaplingReserved(bytes)),
(Sapling | Blossom, _) => match sapling::tree::Root::try_from(bytes) {
Ok(root) => Ok(FinalSaplingRoot(root)),
_ => Err(InvalidSapingRootBytes),
},
(Heartwood, activation_height) if height == activation_height => {
if bytes == CHAIN_HISTORY_ACTIVATION_RESERVED {
Ok(ChainHistoryActivationReserved)
} else {
Err(InvalidChainHistoryActivationReserved { actual: bytes })
}
}
(Canopy, _) if Some(height) == Heartwood.activation_height(network) => {
if bytes == CHAIN_HISTORY_ACTIVATION_RESERVED {
Ok(ChainHistoryActivationReserved)
} else {
Err(InvalidChainHistoryActivationReserved { actual: bytes })
}
}
(Heartwood | Canopy, _) => Ok(ChainHistoryRoot(ChainHistoryMmrRootHash(bytes))),
(Nu5 | Nu6 | Nu6_1 | Nu7, _) => Ok(ChainHistoryBlockTxAuthCommitment(
ChainHistoryBlockTxAuthCommitmentHash(bytes),
)),
#[cfg(zcash_unstable = "zfuture")]
(ZFuture, _) => Ok(ChainHistoryBlockTxAuthCommitment(
ChainHistoryBlockTxAuthCommitmentHash(bytes),
)),
}
}
#[cfg(test)]
pub(super) fn to_bytes(self) -> [u8; 32] {
use Commitment::*;
match self {
PreSaplingReserved(bytes) => bytes,
FinalSaplingRoot(hash) => hash.0.into(),
ChainHistoryActivationReserved => CHAIN_HISTORY_ACTIVATION_RESERVED,
ChainHistoryRoot(hash) => hash.0,
ChainHistoryBlockTxAuthCommitment(hash) => hash.0,
}
}
}
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct ChainHistoryMmrRootHash([u8; 32]);
impl fmt::Display for ChainHistoryMmrRootHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.encode_hex::<String>())
}
}
impl fmt::Debug for ChainHistoryMmrRootHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("ChainHistoryMmrRootHash")
.field(&self.encode_hex::<String>())
.finish()
}
}
impl From<[u8; 32]> for ChainHistoryMmrRootHash {
fn from(hash: [u8; 32]) -> Self {
ChainHistoryMmrRootHash(hash)
}
}
impl From<ChainHistoryMmrRootHash> for [u8; 32] {
fn from(hash: ChainHistoryMmrRootHash) -> Self {
hash.0
}
}
impl BytesInDisplayOrder<true> for ChainHistoryMmrRootHash {
fn bytes_in_serialized_order(&self) -> [u8; 32] {
self.0
}
fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
ChainHistoryMmrRootHash(bytes)
}
}
impl ToHex for &ChainHistoryMmrRootHash {
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 ChainHistoryMmrRootHash {
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 ChainHistoryMmrRootHash {
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())
}
}
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub struct ChainHistoryBlockTxAuthCommitmentHash([u8; 32]);
impl fmt::Display for ChainHistoryBlockTxAuthCommitmentHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.encode_hex::<String>())
}
}
impl fmt::Debug for ChainHistoryBlockTxAuthCommitmentHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("ChainHistoryBlockTxAuthCommitmentHash")
.field(&self.encode_hex::<String>())
.finish()
}
}
impl From<[u8; 32]> for ChainHistoryBlockTxAuthCommitmentHash {
fn from(hash: [u8; 32]) -> Self {
ChainHistoryBlockTxAuthCommitmentHash(hash)
}
}
impl From<ChainHistoryBlockTxAuthCommitmentHash> for [u8; 32] {
fn from(hash: ChainHistoryBlockTxAuthCommitmentHash) -> Self {
hash.0
}
}
impl BytesInDisplayOrder<true> for ChainHistoryBlockTxAuthCommitmentHash {
fn bytes_in_serialized_order(&self) -> [u8; 32] {
self.0
}
fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
ChainHistoryBlockTxAuthCommitmentHash(bytes)
}
}
impl ChainHistoryBlockTxAuthCommitmentHash {
pub fn from_commitments(
history_tree_root: &ChainHistoryMmrRootHash,
auth_data_root: &AuthDataRoot,
) -> Self {
let hash_block_commitments: [u8; 32] = blake2b_simd::Params::new()
.hash_length(32)
.personal(b"ZcashBlockCommit")
.to_state()
.update(&<[u8; 32]>::from(*history_tree_root)[..])
.update(&<[u8; 32]>::from(*auth_data_root))
.update(&[0u8; 32])
.finalize()
.as_bytes()
.try_into()
.expect("32 byte array");
Self(hash_block_commitments)
}
}
impl ToHex for &ChainHistoryBlockTxAuthCommitmentHash {
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 ChainHistoryBlockTxAuthCommitmentHash {
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 ChainHistoryBlockTxAuthCommitmentHash {
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())
}
}
#[allow(missing_docs)]
#[derive(Error, Clone, Debug, PartialEq, Eq)]
pub enum CommitmentError {
#[error(
"invalid final sapling root: expected {:?}, actual: {:?}",
hex::encode(expected),
hex::encode(actual)
)]
InvalidFinalSaplingRoot {
expected: [u8; 32],
actual: [u8; 32],
},
#[error("invalid chain history activation reserved block commitment: expected all zeroes, actual: {:?}", hex::encode(actual))]
InvalidChainHistoryActivationReserved { actual: [u8; 32] },
#[error(
"invalid chain history root: expected {:?}, actual: {:?}",
hex::encode(expected),
hex::encode(actual)
)]
InvalidChainHistoryRoot {
expected: [u8; 32],
actual: [u8; 32],
},
#[error(
"invalid block commitment root: expected {:?}, actual: {:?}",
hex::encode(expected),
hex::encode(actual)
)]
InvalidChainHistoryBlockTxAuthCommitment {
expected: [u8; 32],
actual: [u8; 32],
},
#[error("missing required block height: block commitments can't be parsed without a block height, block hash: {block_hash:?}")]
MissingBlockHeight { block_hash: block::Hash },
#[error("provided bytes are not a valid sapling root")]
InvalidSapingRootBytes,
}