diem_crypto/
hash.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! This module defines traits and implementations of
5//! [cryptographic hash functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function)
6//! for the Diem project.
7//!
8//! It is designed to help authors protect against two types of real world attacks:
9//!
10//! 1. **Semantic Ambiguity**: imagine that Alice has a private key and is using
11//!    two different applications, X and Y. X asks Alice to sign a message saying
12//!    "I am Alice". Alice accepts to sign this message in the context of X. However,
13//!    unbeknownst to Alice, in application Y, messages beginning with the letter "I"
14//!    represent transfers. " am " represents a transfer of 500 coins and "Alice"
15//!    can be interpreted as a destination address. When Alice signed the message she
16//!    needed to be aware of how other applications might interpret that message.
17//!
18//! 2. **Format Ambiguity**: imagine a program that hashes a pair of strings.
19//!    To hash the strings `a` and `b` it hashes `a + "||" + b`. The pair of
20//!    strings `a="foo||", b = "bar"` and `a="foo", b = "||bar"` result in the
21//!    same input to the hash function and therefore the same hash. This
22//!    creates a collision.
23//!
24//! Regarding (1), this library makes it easy for Diem developers to create as
25//! many new "hashable" Rust types as needed so that each Rust type hashed and signed
26//! in Diem has a unique meaning, that is, unambiguously captures the intent of a signer.
27//!
28//! Regarding (2), this library provides the `CryptoHasher` abstraction to easily manage
29//! cryptographic seeds for hashing. Hashing seeds aim to ensure that
30//! the hashes of values of a given type `MyNewStruct` never collide with hashes of values
31//! from another type.
32//!
33//! Finally, to prevent format ambiguity within a same type `MyNewStruct` and facilitate protocol
34//! specifications, we use [Binary Canonical Serialization (BCS)](https://docs.rs/bcs/)
35//! as the recommended solution to write Rust values into a hasher.
36//!
37//! # Quick Start
38//!
39//! To obtain a `hash()` method for any new type `MyNewStruct`, it is (strongly) recommended to
40//! use the derive macros of `serde` and `diem_crypto_derive` as follows:
41//! ```
42//! use diem_crypto::hash::CryptoHash;
43//! use diem_crypto_derive::{CryptoHasher, BCSCryptoHash};
44//! use serde::{Deserialize, Serialize};
45//! #[derive(Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
46//! struct MyNewStruct { /*...*/ }
47//!
48//! let value = MyNewStruct { /*...*/ };
49//! value.hash();
50//! ```
51//!
52//! Under the hood, this will generate a new implementation `MyNewStructHasher` for the trait
53//! `CryptoHasher` and implement the trait `CryptoHash` for `MyNewStruct` using BCS.
54//!
55//! # Implementing New Hashers
56//!
57//! The trait `CryptoHasher` captures the notion of a pre-seeded hash function, aka a "hasher".
58//! New implementations can be defined in two ways.
59//!
60//! ## Derive macro (recommended)
61//!
62//! For any new structure `MyNewStruct` that needs to be hashed, it is recommended to simply
63//! use the derive macro [`CryptoHasher`](https://doc.rust-lang.org/reference/procedural-macros.html).
64//!
65//! ```
66//! use diem_crypto_derive::CryptoHasher;
67//! use serde::Deserialize;
68//! #[derive(Deserialize, CryptoHasher)]
69//! #[serde(rename = "OptionalCustomSerdeName")]
70//! struct MyNewStruct { /*...*/ }
71//! ```
72//!
73//! The macro `CryptoHasher` will define a hasher automatically called `MyNewStructHasher`, and derive a salt
74//! using the name of the type as seen by the Serde library. In the example above, this name
75//! was changed using the Serde parameter `rename`: the salt will be based on the value `OptionalCustomSerdeName`
76//! instead of the default name `MyNewStruct`.
77//!
78//! ## Customized hashers
79//!
80//! **IMPORTANT:** Do NOT use this for new code unless you know what you are doing.
81//!
82//! This library also provides a few customized hashers defined in the code as follows:
83//!
84//! ```
85//! # // To get around that there's no way to doc-test a non-exported macro:
86//! # macro_rules! define_hasher { ($e:expr) => () }
87//! define_hasher! { (MyNewDataHasher, MY_NEW_DATA_HASHER, MY_NEW_DATA_SEED, b"MyUniqueSaltString") }
88//! ```
89//!
90//! # Using a hasher directly
91//!
92//! **IMPORTANT:** Do NOT use this for new code unless you know what you are doing.
93//!
94//! ```
95//! use diem_crypto::hash::{CryptoHasher, TestOnlyHasher};
96//!
97//! let mut hasher = TestOnlyHasher::default();
98//! hasher.update("Test message".as_bytes());
99//! let hash_value = hasher.finish();
100//! ```
101#![allow(clippy::integer_arithmetic)]
102use bytes::Bytes;
103use hex::FromHex;
104use mirai_annotations::*;
105use once_cell::sync::{Lazy, OnceCell};
106#[cfg(any(test, feature = "fuzzing"))]
107use proptest_derive::Arbitrary;
108use rand::{rngs::OsRng, Rng};
109use serde::{de, ser};
110use std::{
111    self,
112    convert::{AsRef, TryFrom},
113    fmt,
114    str::FromStr,
115};
116use tiny_keccak::{Hasher, Sha3};
117
118/// A prefix used to begin the salt of every diem hashable structure. The salt
119/// consists in this global prefix, concatenated with the specified
120/// serialization name of the struct.
121pub(crate) const DIEM_HASH_PREFIX: &[u8] = b"DIEM::";
122
123/// Output value of our hash function. Intentionally opaque for safety and modularity.
124#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
125#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
126pub struct HashValue {
127    hash: [u8; HashValue::LENGTH],
128}
129
130impl HashValue {
131    /// The length of the hash in bytes.
132    pub const LENGTH: usize = 32;
133    /// The length of the hash in bits.
134    pub const LENGTH_IN_BITS: usize = Self::LENGTH * 8;
135
136    /// Create a new [`HashValue`] from a byte array.
137    pub fn new(hash: [u8; HashValue::LENGTH]) -> Self {
138        HashValue { hash }
139    }
140
141    /// Create from a slice (e.g. retrieved from storage).
142    pub fn from_slice<T: AsRef<[u8]>>(bytes: T) -> Result<Self, HashValueParseError> {
143        <[u8; Self::LENGTH]>::try_from(bytes.as_ref())
144            .map_err(|_| HashValueParseError)
145            .map(Self::new)
146    }
147
148    /// Dumps into a vector.
149    pub fn to_vec(&self) -> Vec<u8> {
150        self.hash.to_vec()
151    }
152
153    /// Creates a zero-initialized instance.
154    pub const fn zero() -> Self {
155        HashValue {
156            hash: [0; HashValue::LENGTH],
157        }
158    }
159
160    /// Create a cryptographically random instance.
161    pub fn random() -> Self {
162        let mut rng = OsRng;
163        let hash: [u8; HashValue::LENGTH] = rng.gen();
164        HashValue { hash }
165    }
166
167    /// Creates a random instance with given rng. Useful in unit tests.
168    pub fn random_with_rng<R: Rng>(rng: &mut R) -> Self {
169        let hash: [u8; HashValue::LENGTH] = rng.gen();
170        HashValue { hash }
171    }
172
173    /// Convenience function that computes a `HashValue` internally equal to
174    /// the sha3_256 of a byte buffer. It will handle hasher creation, data
175    /// feeding and finalization.
176    ///
177    /// Note this will not result in the `<T as CryptoHash>::hash()` for any
178    /// reasonable struct T, as this computes a sha3 without any ornaments.
179    pub fn sha3_256_of(buffer: &[u8]) -> Self {
180        let mut sha3 = Sha3::v256();
181        sha3.update(buffer);
182        HashValue::from_keccak(sha3)
183    }
184
185    #[cfg(test)]
186    pub fn from_iter_sha3<'a, I>(buffers: I) -> Self
187    where
188        I: IntoIterator<Item = &'a [u8]>,
189    {
190        let mut sha3 = Sha3::v256();
191        for buffer in buffers {
192            sha3.update(buffer);
193        }
194        HashValue::from_keccak(sha3)
195    }
196
197    fn as_ref_mut(&mut self) -> &mut [u8] {
198        &mut self.hash[..]
199    }
200
201    fn from_keccak(state: Sha3) -> Self {
202        let mut hash = Self::zero();
203        state.finalize(hash.as_ref_mut());
204        hash
205    }
206
207    /// Returns the `index`-th bit in the bytes.
208    pub fn bit(&self, index: usize) -> bool {
209        assume!(index < Self::LENGTH_IN_BITS); // assumed precondition
210        let pos = index / 8;
211        let bit = 7 - index % 8;
212        (self.hash[pos] >> bit) & 1 != 0
213    }
214
215    /// Returns the `index`-th nibble in the bytes.
216    pub fn nibble(&self, index: usize) -> u8 {
217        assume!(index < Self::LENGTH * 2); // assumed precondition
218        let pos = index / 2;
219        let shift = if index % 2 == 0 { 4 } else { 0 };
220        (self.hash[pos] >> shift) & 0x0f
221    }
222
223    /// Returns a `HashValueBitIterator` over all the bits that represent this `HashValue`.
224    pub fn iter_bits(&self) -> HashValueBitIterator<'_> {
225        HashValueBitIterator::new(self)
226    }
227
228    /// Constructs a `HashValue` from an iterator of bits.
229    pub fn from_bit_iter(
230        iter: impl ExactSizeIterator<Item = bool>,
231    ) -> Result<Self, HashValueParseError> {
232        if iter.len() != Self::LENGTH_IN_BITS {
233            return Err(HashValueParseError);
234        }
235
236        let mut buf = [0; Self::LENGTH];
237        for (i, bit) in iter.enumerate() {
238            if bit {
239                buf[i / 8] |= 1 << (7 - i % 8);
240            }
241        }
242        Ok(Self::new(buf))
243    }
244
245    /// Returns the length of common prefix of `self` and `other` in bits.
246    pub fn common_prefix_bits_len(&self, other: HashValue) -> usize {
247        self.iter_bits()
248            .zip(other.iter_bits())
249            .take_while(|(x, y)| x == y)
250            .count()
251    }
252
253    /// Full hex representation of a given hash value.
254    pub fn to_hex(&self) -> String {
255        format!("{:x}", self)
256    }
257
258    /// Full hex representation of a given hash value with `0x` prefix.
259    pub fn to_hex_literal(&self) -> String {
260        format!("{:#x}", self)
261    }
262
263    /// Parse a given hex string to a hash value.
264    pub fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, HashValueParseError> {
265        <[u8; Self::LENGTH]>::from_hex(hex)
266            .map_err(|_| HashValueParseError)
267            .map(Self::new)
268    }
269
270    /// Create a hash value whose contents are just the given integer. Useful for
271    /// generating basic mock hash values.
272    ///
273    /// Ex: HashValue::from_u64(0x1234) => HashValue([0, .., 0, 0x12, 0x34])
274    #[cfg(any(test, feature = "fuzzing"))]
275    pub fn from_u64(v: u64) -> Self {
276        let mut hash = [0u8; Self::LENGTH];
277        let bytes = v.to_be_bytes();
278        hash[Self::LENGTH - bytes.len()..].copy_from_slice(&bytes[..]);
279        Self::new(hash)
280    }
281}
282
283impl ser::Serialize for HashValue {
284    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
285    where
286        S: ser::Serializer,
287    {
288        if serializer.is_human_readable() {
289            serializer.serialize_str(&self.to_hex())
290        } else {
291            // In order to preserve the Serde data model and help analysis tools,
292            // make sure to wrap our value in a container with the same name
293            // as the original type.
294            serializer
295                .serialize_newtype_struct("HashValue", serde_bytes::Bytes::new(&self.hash[..]))
296        }
297    }
298}
299
300impl<'de> de::Deserialize<'de> for HashValue {
301    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
302    where
303        D: de::Deserializer<'de>,
304    {
305        if deserializer.is_human_readable() {
306            let encoded_hash = <String>::deserialize(deserializer)?;
307            HashValue::from_hex(encoded_hash.as_str())
308                .map_err(<D::Error as ::serde::de::Error>::custom)
309        } else {
310            // See comment in serialize.
311            #[derive(::serde::Deserialize)]
312            #[serde(rename = "HashValue")]
313            struct Value<'a>(&'a [u8]);
314
315            let value = Value::deserialize(deserializer)?;
316            Self::from_slice(value.0).map_err(<D::Error as ::serde::de::Error>::custom)
317        }
318    }
319}
320
321impl Default for HashValue {
322    fn default() -> Self {
323        HashValue::zero()
324    }
325}
326
327impl AsRef<[u8; HashValue::LENGTH]> for HashValue {
328    fn as_ref(&self) -> &[u8; HashValue::LENGTH] {
329        &self.hash
330    }
331}
332
333impl std::ops::Deref for HashValue {
334    type Target = [u8; Self::LENGTH];
335
336    fn deref(&self) -> &Self::Target {
337        &self.hash
338    }
339}
340
341impl std::ops::Index<usize> for HashValue {
342    type Output = u8;
343
344    fn index(&self, s: usize) -> &u8 {
345        self.hash.index(s)
346    }
347}
348
349impl fmt::Binary for HashValue {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        for byte in &self.hash {
352            write!(f, "{:08b}", byte)?;
353        }
354        Ok(())
355    }
356}
357
358impl fmt::LowerHex for HashValue {
359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360        if f.alternate() {
361            write!(f, "0x")?;
362        }
363        for byte in &self.hash {
364            write!(f, "{:02x}", byte)?;
365        }
366        Ok(())
367    }
368}
369
370impl fmt::Debug for HashValue {
371    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372        write!(f, "HashValue(")?;
373        <Self as fmt::LowerHex>::fmt(self, f)?;
374        write!(f, ")")?;
375        Ok(())
376    }
377}
378
379/// Will print shortened (4 bytes) hash
380impl fmt::Display for HashValue {
381    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382        for byte in self.hash.iter().take(4) {
383            write!(f, "{:02x}", byte)?;
384        }
385        Ok(())
386    }
387}
388
389impl From<HashValue> for Bytes {
390    fn from(value: HashValue) -> Bytes {
391        Bytes::copy_from_slice(value.hash.as_ref())
392    }
393}
394
395impl FromStr for HashValue {
396    type Err = HashValueParseError;
397
398    fn from_str(s: &str) -> Result<Self, HashValueParseError> {
399        HashValue::from_hex(s)
400    }
401}
402
403/// Parse error when attempting to construct a HashValue
404#[derive(Clone, Copy, Debug)]
405pub struct HashValueParseError;
406
407impl fmt::Display for HashValueParseError {
408    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409        write!(f, "unable to parse HashValue")
410    }
411}
412
413impl std::error::Error for HashValueParseError {}
414
415/// An iterator over `HashValue` that generates one bit for each iteration.
416pub struct HashValueBitIterator<'a> {
417    /// The reference to the bytes that represent the `HashValue`.
418    hash_bytes: &'a [u8],
419    pos: std::ops::Range<usize>,
420    // invariant hash_bytes.len() == HashValue::LENGTH;
421    // invariant pos.end == hash_bytes.len() * 8;
422}
423
424impl<'a> HashValueBitIterator<'a> {
425    /// Constructs a new `HashValueBitIterator` using given `HashValue`.
426    fn new(hash_value: &'a HashValue) -> Self {
427        HashValueBitIterator {
428            hash_bytes: hash_value.as_ref(),
429            pos: (0..HashValue::LENGTH_IN_BITS),
430        }
431    }
432
433    /// Returns the `index`-th bit in the bytes.
434    fn get_bit(&self, index: usize) -> bool {
435        assume!(index < self.pos.end); // assumed precondition
436        assume!(self.hash_bytes.len() == HashValue::LENGTH); // invariant
437        assume!(self.pos.end == self.hash_bytes.len() * 8); // invariant
438        let pos = index / 8;
439        let bit = 7 - index % 8;
440        (self.hash_bytes[pos] >> bit) & 1 != 0
441    }
442}
443
444impl<'a> std::iter::Iterator for HashValueBitIterator<'a> {
445    type Item = bool;
446
447    fn next(&mut self) -> Option<Self::Item> {
448        self.pos.next().map(|x| self.get_bit(x))
449    }
450
451    fn size_hint(&self) -> (usize, Option<usize>) {
452        self.pos.size_hint()
453    }
454}
455
456impl<'a> std::iter::DoubleEndedIterator for HashValueBitIterator<'a> {
457    fn next_back(&mut self) -> Option<Self::Item> {
458        self.pos.next_back().map(|x| self.get_bit(x))
459    }
460}
461
462impl<'a> std::iter::ExactSizeIterator for HashValueBitIterator<'a> {}
463
464/// A type that can be cryptographically hashed to produce a `HashValue`.
465///
466/// In most cases, this trait should not be implemented manually but rather derived using
467/// the macros `serde::Serialize`, `CryptoHasher`, and `BCSCryptoHash`.
468pub trait CryptoHash {
469    /// The associated `Hasher` type which comes with a unique salt for this type.
470    type Hasher: CryptoHasher;
471
472    /// Hashes the object and produces a `HashValue`.
473    fn hash(&self) -> HashValue;
474}
475
476/// A trait for representing the state of a cryptographic hasher.
477pub trait CryptoHasher: Default + std::io::Write {
478    /// the seed used to initialize hashing `Self` before the serialization bytes of the actual value
479    fn seed() -> &'static [u8; 32];
480
481    /// Write bytes into the hasher.
482    fn update(&mut self, bytes: &[u8]);
483
484    /// Finish constructing the [`HashValue`].
485    fn finish(self) -> HashValue;
486
487    /// Convenience method to compute the hash of a complete byte slice.
488    fn hash_all(bytes: &[u8]) -> HashValue {
489        let mut hasher = Self::default();
490        hasher.update(bytes);
491        hasher.finish()
492    }
493}
494
495/// The default hasher underlying generated implementations of `CryptoHasher`.
496#[doc(hidden)]
497#[derive(Clone)]
498pub struct DefaultHasher {
499    state: Sha3,
500}
501
502impl DefaultHasher {
503    #[doc(hidden)]
504    /// This function does not return a HashValue in the sense of our usual
505    /// hashes, but a construction of initial bytes that are fed into any hash
506    /// provided we're passed  a (bcs) serialization name as argument.
507    pub fn prefixed_hash(buffer: &[u8]) -> [u8; HashValue::LENGTH] {
508        // The salt is initial material we prefix to actual value bytes for
509        // domain separation. Its length is variable.
510        let salt: Vec<u8> = [DIEM_HASH_PREFIX, buffer].concat();
511        // The seed is a fixed-length hash of the salt, thereby preventing
512        // suffix attacks on the domain separation bytes.
513        HashValue::sha3_256_of(&salt[..]).hash
514    }
515
516    #[doc(hidden)]
517    pub fn new(typename: &[u8]) -> Self {
518        let mut state = Sha3::v256();
519        if !typename.is_empty() {
520            state.update(&Self::prefixed_hash(typename));
521        }
522        DefaultHasher { state }
523    }
524
525    #[doc(hidden)]
526    pub fn update(&mut self, bytes: &[u8]) {
527        self.state.update(bytes);
528    }
529
530    #[doc(hidden)]
531    pub fn finish(self) -> HashValue {
532        let mut hasher = HashValue::default();
533        self.state.finalize(hasher.as_ref_mut());
534        hasher
535    }
536}
537
538impl fmt::Debug for DefaultHasher {
539    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
540        write!(f, "DefaultHasher: state = Sha3")
541    }
542}
543
544macro_rules! define_hasher {
545    (
546        $(#[$attr:meta])*
547        ($hasher_type: ident, $hasher_name: ident, $seed_name: ident, $salt: expr)
548    ) => {
549
550        #[derive(Clone, Debug)]
551        $(#[$attr])*
552        pub struct $hasher_type(DefaultHasher);
553
554        impl $hasher_type {
555            fn new() -> Self {
556                $hasher_type(DefaultHasher::new($salt))
557            }
558        }
559
560        static $hasher_name: Lazy<$hasher_type> = Lazy::new(|| { $hasher_type::new() });
561        static $seed_name: OnceCell<[u8; 32]> = OnceCell::new();
562
563        impl Default for $hasher_type {
564            fn default() -> Self {
565                $hasher_name.clone()
566            }
567        }
568
569        impl CryptoHasher for $hasher_type {
570            fn seed() -> &'static [u8;32] {
571                $seed_name.get_or_init(|| {
572                    DefaultHasher::prefixed_hash($salt)
573                })
574            }
575
576            fn update(&mut self, bytes: &[u8]) {
577                self.0.update(bytes);
578            }
579
580            fn finish(self) -> HashValue {
581                self.0.finish()
582            }
583        }
584
585        impl std::io::Write for $hasher_type {
586            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
587                self.0.update(bytes);
588                Ok(bytes.len())
589            }
590            fn flush(&mut self) -> std::io::Result<()> {
591                Ok(())
592            }
593        }
594    };
595}
596
597define_hasher! {
598    /// The hasher used to compute the hash of an internal node in the transaction accumulator.
599    (
600        TransactionAccumulatorHasher,
601        TRANSACTION_ACCUMULATOR_HASHER,
602        TRANSACTION_ACCUMULATOR_SEED,
603        b"TransactionAccumulator"
604    )
605}
606
607define_hasher! {
608    /// The hasher used to compute the hash of an internal node in the event accumulator.
609    (
610        EventAccumulatorHasher,
611        EVENT_ACCUMULATOR_HASHER,
612        EVENT_ACCUMULATOR_SEED,
613        b"EventAccumulator"
614    )
615}
616
617define_hasher! {
618    /// The hasher used to compute the hash of an internal node in the Sparse Merkle Tree.
619    (
620        SparseMerkleInternalHasher,
621        SPARSE_MERKLE_INTERNAL_HASHER,
622        SPARSE_MERKLE_INTERNAL_SEED,
623        b"SparseMerkleInternal"
624    )
625}
626
627define_hasher! {
628    /// The hasher used to compute the hash of an internal node in the transaction accumulator.
629    (
630        VoteProposalHasher,
631        VOTE_PROPOSAL_HASHER,
632        VOTE_PROPOSAL_SEED,
633        b"VoteProposalHasher"
634    )
635}
636
637define_hasher! {
638    /// The hasher used only for testing. It doesn't have a salt.
639    (TestOnlyHasher, TEST_ONLY_HASHER, TEST_ONLY_SEED, b"")
640}
641
642fn create_literal_hash(word: &str) -> HashValue {
643    let mut s = word.as_bytes().to_vec();
644    assert!(s.len() <= HashValue::LENGTH);
645    s.resize(HashValue::LENGTH, 0);
646    HashValue::from_slice(&s).expect("Cannot fail")
647}
648
649/// Placeholder hash of `Accumulator`.
650pub static ACCUMULATOR_PLACEHOLDER_HASH: Lazy<HashValue> =
651    Lazy::new(|| create_literal_hash("ACCUMULATOR_PLACEHOLDER_HASH"));
652
653/// Placeholder hash of `SparseMerkleTree`.
654pub static SPARSE_MERKLE_PLACEHOLDER_HASH: Lazy<HashValue> =
655    Lazy::new(|| create_literal_hash("SPARSE_MERKLE_PLACEHOLDER_HASH"));
656
657/// Block id reserved as the id of parent block of the genesis block.
658pub static PRE_GENESIS_BLOCK_ID: Lazy<HashValue> =
659    Lazy::new(|| create_literal_hash("PRE_GENESIS_BLOCK_ID"));
660
661/// Genesis block id is used as a parent of the very first block executed by the executor.
662pub static GENESIS_BLOCK_ID: Lazy<HashValue> = Lazy::new(|| {
663    // This maintains the invariant that block.id() == block.hash(), for
664    // the genesis block and allows us to (de/)serialize it consistently
665    HashValue::new([
666        0x5e, 0x10, 0xba, 0xd4, 0x5b, 0x35, 0xed, 0x92, 0x9c, 0xd6, 0xd2, 0xc7, 0x09, 0x8b, 0x13,
667        0x5d, 0x02, 0xdd, 0x25, 0x9a, 0xe8, 0x8a, 0x8d, 0x09, 0xf4, 0xeb, 0x5f, 0xba, 0xe9, 0xa6,
668        0xf6, 0xe4,
669    ])
670});
671
672/// Provides a test_only_hash() method that can be used in tests on types that implement
673/// `serde::Serialize`.
674///
675/// # Example
676/// ```
677/// use diem_crypto::hash::TestOnlyHash;
678///
679/// b"hello world".test_only_hash();
680/// ```
681pub trait TestOnlyHash {
682    /// Generates a hash used only for tests.
683    fn test_only_hash(&self) -> HashValue;
684}
685
686impl<T: ser::Serialize + ?Sized> TestOnlyHash for T {
687    fn test_only_hash(&self) -> HashValue {
688        let bytes = bcs::to_bytes(self).expect("serialize failed during hash.");
689        let mut hasher = TestOnlyHasher::default();
690        hasher.update(&bytes);
691        hasher.finish()
692    }
693}