zebra_chain/transaction/
hash.rs1use 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#[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 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#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
197#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
198pub struct WtxId {
199 pub id: Hash,
201
202 pub auth_digest: AuthDigest,
204}
205
206impl WtxId {
207 pub fn as_bytes(&self) -> [u8; 64] {
209 <[u8; 64]>::from(self)
210 }
211}
212
213impl From<Transaction> for WtxId {
214 fn from(transaction: Transaction) -> Self {
220 WtxId::from(&transaction)
222 }
223}
224
225impl From<&Transaction> for WtxId {
226 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 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 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}