Skip to main content

zebra_chain/transaction/
auth_digest.rs

1//! Authorizing digests for Zcash transactions.
2
3use std::{array::TryFromSliceError, fmt, sync::Arc};
4
5use hex::{FromHex, ToHex};
6
7use crate::{
8    primitives::zcash_primitives::auth_digest,
9    serialization::{
10        BytesInDisplayOrder, ReadZcashExt, SerializationError, WriteZcashExt, ZcashDeserialize,
11        ZcashSerialize,
12    },
13};
14
15use super::Transaction;
16
17#[cfg(any(test, feature = "proptest-impl"))]
18use proptest_derive::Arbitrary;
19
20/// An authorizing data commitment hash as specified in [ZIP-244].
21///
22/// Note: Zebra displays transaction and block hashes in big-endian byte-order,
23/// following the u256 convention set by Bitcoin and zcashd.
24///
25/// [ZIP-244]: https://zips.z.cash/zip-0244
26#[derive(Copy, Clone, Eq, PartialEq, Hash, serde::Deserialize, serde::Serialize)]
27#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
28pub struct AuthDigest(pub [u8; 32]);
29
30impl BytesInDisplayOrder<true> for AuthDigest {
31    fn bytes_in_serialized_order(&self) -> [u8; 32] {
32        self.0
33    }
34
35    fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
36        AuthDigest(bytes)
37    }
38}
39
40impl From<Transaction> for AuthDigest {
41    /// Computes the authorizing data commitment for a transaction.
42    ///
43    /// # Panics
44    ///
45    /// If passed a pre-v5 transaction.
46    fn from(transaction: Transaction) -> Self {
47        // use the ref implementation, to avoid cloning the transaction
48        AuthDigest::from(&transaction)
49    }
50}
51
52impl From<&Transaction> for AuthDigest {
53    /// Computes the authorizing data commitment for a transaction.
54    ///
55    /// # Panics
56    ///
57    /// If passed a pre-v5 transaction.
58    fn from(transaction: &Transaction) -> Self {
59        auth_digest(transaction)
60    }
61}
62
63impl From<Arc<Transaction>> for AuthDigest {
64    /// Computes the authorizing data commitment for a transaction.
65    ///
66    /// # Panics
67    ///
68    /// If passed a pre-v5 transaction.
69    fn from(transaction: Arc<Transaction>) -> Self {
70        transaction.as_ref().into()
71    }
72}
73
74impl From<[u8; 32]> for AuthDigest {
75    fn from(bytes: [u8; 32]) -> Self {
76        Self(bytes)
77    }
78}
79
80impl TryFrom<&[u8]> for AuthDigest {
81    type Error = TryFromSliceError;
82
83    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
84        Ok(AuthDigest(bytes.try_into()?))
85    }
86}
87
88impl From<AuthDigest> for [u8; 32] {
89    fn from(auth_digest: AuthDigest) -> Self {
90        auth_digest.0
91    }
92}
93
94impl From<&AuthDigest> for [u8; 32] {
95    fn from(auth_digest: &AuthDigest) -> Self {
96        (*auth_digest).into()
97    }
98}
99
100impl ToHex for &AuthDigest {
101    fn encode_hex<T: FromIterator<char>>(&self) -> T {
102        self.bytes_in_display_order().encode_hex()
103    }
104
105    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
106        self.bytes_in_display_order().encode_hex_upper()
107    }
108}
109
110impl ToHex for AuthDigest {
111    fn encode_hex<T: FromIterator<char>>(&self) -> T {
112        (&self).encode_hex()
113    }
114
115    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
116        (&self).encode_hex_upper()
117    }
118}
119
120impl FromHex for AuthDigest {
121    type Error = <[u8; 32] as FromHex>::Error;
122
123    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
124        let mut hash = <[u8; 32]>::from_hex(hex)?;
125        hash.reverse();
126
127        Ok(hash.into())
128    }
129}
130
131impl fmt::Display for AuthDigest {
132    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133        f.write_str(&self.encode_hex::<String>())
134    }
135}
136
137impl fmt::Debug for AuthDigest {
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        f.debug_tuple("AuthDigest")
140            .field(&self.encode_hex::<String>())
141            .finish()
142    }
143}
144
145impl std::str::FromStr for AuthDigest {
146    type Err = SerializationError;
147
148    fn from_str(s: &str) -> Result<Self, Self::Err> {
149        let mut bytes = [0; 32];
150        if hex::decode_to_slice(s, &mut bytes[..]).is_err() {
151            Err(SerializationError::Parse("hex decoding error"))
152        } else {
153            bytes.reverse();
154            Ok(AuthDigest(bytes))
155        }
156    }
157}
158
159impl ZcashSerialize for AuthDigest {
160    fn zcash_serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), std::io::Error> {
161        writer.write_32_bytes(&self.into())
162    }
163}
164
165impl ZcashDeserialize for AuthDigest {
166    fn zcash_deserialize<R: std::io::Read>(mut reader: R) -> Result<Self, SerializationError> {
167        Ok(reader.read_32_bytes()?.into())
168    }
169}