zebra_chain/transaction/
hash.rs

1//! Transaction identifiers for Zcash.
2//!
3//! Zcash has two different transaction identifiers, with different widths:
4//! * [`struct@Hash`]: a 32-byte transaction ID, which uniquely identifies mined transactions
5//!   (transactions that have been committed to the blockchain in blocks), and
6//! * [`WtxId`]: a 64-byte witnessed transaction ID, which uniquely identifies unmined transactions
7//!   (transactions that are sent by wallets or stored in node mempools).
8//!
9//! Transaction version 5 uses both these unique identifiers:
10//! * [`struct@Hash`] uniquely identifies the effects of a v5 transaction (spends and outputs),
11//!   so it uniquely identifies the transaction's data after it has been mined into a block;
12//! * [`WtxId`] uniquely identifies the effects and authorizing data of a v5 transaction
13//!   (signatures, proofs, and scripts), so it uniquely identifies the transaction's data
14//!   outside a block. (For example, transactions produced by Zcash wallets, or in node mempools.)
15//!
16//! Transaction versions 1-4 are uniquely identified by legacy [`struct@Hash`] transaction IDs,
17//! whether they have been mined or not. So Zebra, and the Zcash network protocol,
18//! don't use witnessed transaction IDs for them.
19//!
20//! There is no unique identifier that only covers the effects of a v1-4 transaction,
21//! so their legacy IDs are malleable, if submitted with different authorizing data.
22//! So the same spends and outputs can have a completely different [`struct@Hash`].
23//!
24//! Zebra's [`UnminedTxId`][1] and [`UnminedTx`][1] enums provide the correct
25//! unique ID for unmined transactions. They can be used to handle transactions
26//! regardless of version, and get the [`WtxId`] or [`struct@Hash`] when
27//! required.
28//!
29//! [1]: crate::transaction::UnminedTx
30
31use std::{fmt, sync::Arc};
32
33#[cfg(any(test, feature = "proptest-impl"))]
34use proptest_derive::Arbitrary;
35
36use hex::{FromHex, ToHex};
37
38use crate::serialization::{
39    BytesInDisplayOrder, ReadZcashExt, SerializationError, WriteZcashExt, ZcashDeserialize,
40    ZcashSerialize,
41};
42
43use super::{txid::TxIdBuilder, AuthDigest, Transaction};
44
45/// A transaction ID, which uniquely identifies mined v5 transactions,
46/// and all v1-v4 transactions.
47///
48/// Note: Zebra displays transaction and block hashes in big-endian byte-order,
49/// following the u256 convention set by Bitcoin and zcashd.
50///
51/// "The transaction ID of a version 4 or earlier transaction is the SHA-256d hash
52/// of the transaction encoding in the pre-v5 format described above.
53///
54/// The transaction ID of a version 5 transaction is as defined in [ZIP-244]."
55/// [Spec: Transaction Identifiers]
56///
57/// [ZIP-244]: https://zips.z.cash/zip-0244
58/// [Spec: Transaction Identifiers]: https://zips.z.cash/protocol/protocol.pdf#txnidentifiers
59#[derive(
60    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, serde::Deserialize, serde::Serialize,
61)]
62#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
63pub struct Hash(pub [u8; 32]);
64
65impl From<Transaction> for Hash {
66    fn from(transaction: Transaction) -> Self {
67        // use the ref implementation, to avoid cloning the transaction
68        Hash::from(&transaction)
69    }
70}
71
72impl From<&Transaction> for Hash {
73    fn from(transaction: &Transaction) -> Self {
74        let hasher = TxIdBuilder::new(transaction);
75        hasher
76            .txid()
77            .expect("zcash_primitives and Zebra transaction formats must be compatible")
78    }
79}
80
81impl From<Arc<Transaction>> for Hash {
82    fn from(transaction: Arc<Transaction>) -> Self {
83        Hash::from(transaction.as_ref())
84    }
85}
86
87impl From<[u8; 32]> for Hash {
88    fn from(bytes: [u8; 32]) -> Self {
89        Self(bytes)
90    }
91}
92
93impl From<Hash> for [u8; 32] {
94    fn from(hash: Hash) -> Self {
95        hash.0
96    }
97}
98
99impl From<&Hash> for [u8; 32] {
100    fn from(hash: &Hash) -> Self {
101        (*hash).into()
102    }
103}
104
105impl BytesInDisplayOrder<true> for Hash {
106    fn bytes_in_serialized_order(&self) -> [u8; 32] {
107        self.0
108    }
109
110    fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
111        Hash(bytes)
112    }
113}
114
115impl ToHex for &Hash {
116    fn encode_hex<T: FromIterator<char>>(&self) -> T {
117        self.bytes_in_display_order().encode_hex()
118    }
119
120    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
121        self.bytes_in_display_order().encode_hex_upper()
122    }
123}
124
125impl ToHex for Hash {
126    fn encode_hex<T: FromIterator<char>>(&self) -> T {
127        (&self).encode_hex()
128    }
129
130    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
131        (&self).encode_hex_upper()
132    }
133}
134
135impl FromHex for Hash {
136    type Error = <[u8; 32] as FromHex>::Error;
137
138    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
139        let mut hash = <[u8; 32]>::from_hex(hex)?;
140        hash.reverse();
141
142        Ok(hash.into())
143    }
144}
145
146impl fmt::Display for Hash {
147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148        f.write_str(&self.encode_hex::<String>())
149    }
150}
151
152impl fmt::Debug for Hash {
153    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154        f.debug_tuple("transaction::Hash")
155            .field(&self.encode_hex::<String>())
156            .finish()
157    }
158}
159
160impl std::str::FromStr for Hash {
161    type Err = SerializationError;
162
163    fn from_str(s: &str) -> Result<Self, Self::Err> {
164        let mut bytes = [0; 32];
165        if hex::decode_to_slice(s, &mut bytes[..]).is_err() {
166            Err(SerializationError::Parse("hex decoding error"))
167        } else {
168            bytes.reverse();
169            Ok(Hash(bytes))
170        }
171    }
172}
173
174impl ZcashSerialize for Hash {
175    fn zcash_serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), std::io::Error> {
176        writer.write_32_bytes(&self.into())
177    }
178}
179
180impl ZcashDeserialize for Hash {
181    fn zcash_deserialize<R: std::io::Read>(mut reader: R) -> Result<Self, SerializationError> {
182        Ok(reader.read_32_bytes()?.into())
183    }
184}
185
186/// A witnessed transaction ID, which uniquely identifies unmined v5 transactions.
187///
188/// Witnessed transaction IDs are not used for transaction versions 1-4.
189///
190/// "A v5 transaction also has a wtxid (used for example in the peer-to-peer protocol)
191/// as defined in [ZIP-239]."
192/// [Spec: Transaction Identifiers]
193///
194/// [ZIP-239]: https://zips.z.cash/zip-0239
195/// [Spec: Transaction Identifiers]: https://zips.z.cash/protocol/protocol.pdf#txnidentifiers
196#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
197#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
198pub struct WtxId {
199    /// The non-malleable transaction ID for this transaction's effects.
200    pub id: Hash,
201
202    /// The authorizing data digest for this transactions signatures, proofs, and scripts.
203    pub auth_digest: AuthDigest,
204}
205
206impl WtxId {
207    /// Return this witnessed transaction ID as a serialized byte array.
208    pub fn as_bytes(&self) -> [u8; 64] {
209        <[u8; 64]>::from(self)
210    }
211}
212
213impl From<Transaction> for WtxId {
214    /// Computes the witnessed transaction ID for a transaction.
215    ///
216    /// # Panics
217    ///
218    /// If passed a pre-v5 transaction.
219    fn from(transaction: Transaction) -> Self {
220        // use the ref implementation, to avoid cloning the transaction
221        WtxId::from(&transaction)
222    }
223}
224
225impl From<&Transaction> for WtxId {
226    /// Computes the witnessed transaction ID for a transaction.
227    ///
228    /// # Panics
229    ///
230    /// If passed a pre-v5 transaction.
231    fn from(transaction: &Transaction) -> Self {
232        Self {
233            id: transaction.into(),
234            auth_digest: transaction.into(),
235        }
236    }
237}
238
239impl From<Arc<Transaction>> for WtxId {
240    /// Computes the witnessed transaction ID for a transaction.
241    ///
242    /// # Panics
243    ///
244    /// If passed a pre-v5 transaction.
245    fn from(transaction: Arc<Transaction>) -> Self {
246        transaction.as_ref().into()
247    }
248}
249
250impl From<[u8; 64]> for WtxId {
251    fn from(bytes: [u8; 64]) -> Self {
252        let id: [u8; 32] = bytes[0..32].try_into().expect("length is 64");
253        let auth_digest: [u8; 32] = bytes[32..64].try_into().expect("length is 64");
254
255        Self {
256            id: id.into(),
257            auth_digest: auth_digest.into(),
258        }
259    }
260}
261
262impl From<WtxId> for [u8; 64] {
263    fn from(wtx_id: WtxId) -> Self {
264        let mut bytes = [0; 64];
265        let (id, auth_digest) = bytes.split_at_mut(32);
266
267        id.copy_from_slice(&wtx_id.id.0);
268        auth_digest.copy_from_slice(&wtx_id.auth_digest.0);
269
270        bytes
271    }
272}
273
274impl From<&WtxId> for [u8; 64] {
275    fn from(wtx_id: &WtxId) -> Self {
276        (*wtx_id).into()
277    }
278}
279
280impl TryFrom<&[u8]> for WtxId {
281    type Error = SerializationError;
282
283    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
284        let bytes: [u8; 64] = bytes.try_into()?;
285
286        Ok(bytes.into())
287    }
288}
289
290impl TryFrom<Vec<u8>> for WtxId {
291    type Error = SerializationError;
292
293    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
294        bytes.as_slice().try_into()
295    }
296}
297
298impl TryFrom<&Vec<u8>> for WtxId {
299    type Error = SerializationError;
300
301    fn try_from(bytes: &Vec<u8>) -> Result<Self, Self::Error> {
302        bytes.clone().try_into()
303    }
304}
305
306impl fmt::Display for WtxId {
307    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
308        f.write_str(&self.id.to_string())?;
309        f.write_str(&self.auth_digest.to_string())
310    }
311}
312
313impl std::str::FromStr for WtxId {
314    type Err = SerializationError;
315
316    fn from_str(s: &str) -> Result<Self, Self::Err> {
317        // we need to split using bytes,
318        // because str::split_at panics if it splits a UTF-8 codepoint
319        let s = s.as_bytes();
320
321        if s.len() == 128 {
322            let (id, auth_digest) = s.split_at(64);
323            let id = std::str::from_utf8(id)?;
324            let auth_digest = std::str::from_utf8(auth_digest)?;
325
326            Ok(Self {
327                id: id.parse()?,
328                auth_digest: auth_digest.parse()?,
329            })
330        } else {
331            Err(SerializationError::Parse(
332                "wrong length for WtxId hex string",
333            ))
334        }
335    }
336}
337
338impl ZcashSerialize for WtxId {
339    fn zcash_serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), std::io::Error> {
340        writer.write_64_bytes(&self.into())
341    }
342}
343
344impl ZcashDeserialize for WtxId {
345    fn zcash_deserialize<R: std::io::Read>(mut reader: R) -> Result<Self, SerializationError> {
346        Ok(reader.read_64_bytes()?.into())
347    }
348}