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::{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 AsRef<[u8; 32]> for Hash {
66 fn as_ref(&self) -> &[u8; 32] {
67 &self.0
68 }
69}
70
71impl From<Transaction> for Hash {
75 fn from(transaction: Transaction) -> Self {
76 Hash::from(&transaction)
78 }
79}
80
81impl From<[u8; 32]> for Hash {
82 fn from(bytes: [u8; 32]) -> Self {
83 Self(bytes)
84 }
85}
86
87impl From<&[u8; 32]> for Hash {
88 fn from(bytes: &[u8; 32]) -> Self {
89 Self::from(*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 Self {
221 id: transaction.hash(),
222 auth_digest: transaction
223 .auth_digest()
224 .expect("WtxId requires a V5+ transaction with an auth digest"),
225 }
226 }
227}
228
229impl From<Arc<Transaction>> for WtxId {
230 fn from(transaction: Arc<Transaction>) -> Self {
231 transaction.as_ref().into()
232 }
233}
234
235impl From<[u8; 64]> for WtxId {
236 fn from(bytes: [u8; 64]) -> Self {
237 let id: [u8; 32] = bytes[0..32].try_into().expect("length is 64");
238 let auth_digest: [u8; 32] = bytes[32..64].try_into().expect("length is 64");
239
240 Self {
241 id: id.into(),
242 auth_digest: auth_digest.into(),
243 }
244 }
245}
246
247impl From<WtxId> for [u8; 64] {
248 fn from(wtx_id: WtxId) -> Self {
249 let mut bytes = [0; 64];
250 let (id, auth_digest) = bytes.split_at_mut(32);
251
252 id.copy_from_slice(&wtx_id.id.0);
253 auth_digest.copy_from_slice(&wtx_id.auth_digest.0);
254
255 bytes
256 }
257}
258
259impl From<&WtxId> for [u8; 64] {
260 fn from(wtx_id: &WtxId) -> Self {
261 (*wtx_id).into()
262 }
263}
264
265impl TryFrom<&[u8]> for WtxId {
266 type Error = SerializationError;
267
268 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
269 let bytes: [u8; 64] = bytes.try_into()?;
270
271 Ok(bytes.into())
272 }
273}
274
275impl TryFrom<Vec<u8>> for WtxId {
276 type Error = SerializationError;
277
278 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
279 bytes.as_slice().try_into()
280 }
281}
282
283impl TryFrom<&Vec<u8>> for WtxId {
284 type Error = SerializationError;
285
286 fn try_from(bytes: &Vec<u8>) -> Result<Self, Self::Error> {
287 bytes.as_slice().try_into()
288 }
289}
290
291impl fmt::Display for WtxId {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 f.write_str(&self.id.to_string())?;
294 f.write_str(&self.auth_digest.to_string())
295 }
296}
297
298impl std::str::FromStr for WtxId {
299 type Err = SerializationError;
300
301 fn from_str(s: &str) -> Result<Self, Self::Err> {
302 let s = s.as_bytes();
305
306 if s.len() == 128 {
307 let (id, auth_digest) = s.split_at(64);
308 let id = std::str::from_utf8(id)?;
309 let auth_digest = std::str::from_utf8(auth_digest)?;
310
311 Ok(Self {
312 id: id.parse()?,
313 auth_digest: auth_digest.parse()?,
314 })
315 } else {
316 Err(SerializationError::Parse(
317 "wrong length for WtxId hex string",
318 ))
319 }
320 }
321}
322
323impl ZcashSerialize for WtxId {
324 fn zcash_serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), std::io::Error> {
325 writer.write_64_bytes(&self.into())
326 }
327}
328
329impl ZcashDeserialize for WtxId {
330 fn zcash_deserialize<R: std::io::Read>(mut reader: R) -> Result<Self, SerializationError> {
331 Ok(reader.read_64_bytes()?.into())
332 }
333}