elements/
hash_types.rs

1// Rust Elements Library
2// Written in 2020 by
3//   Andrew Poelstra <apoelstra@blockstream.com>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! File defines types for hashes used throughout the library.
16//!
17//! These types are needed in order
18//! to avoid mixing data of the same hash format (like SHA256d) but of different meaning
19//! (transaction id, block hash etc).
20
21use crate::hashes::{hash160, hash_newtype, sha256, sha256d, Hash};
22
23macro_rules! impl_hashencode {
24    ($hashtype:ident) => {
25        impl $crate::encode::Encodable for $hashtype {
26            fn consensus_encode<W: std::io::Write>(
27                &self,
28                w: W,
29            ) -> Result<usize, crate::encode::Error> {
30                self.0.consensus_encode(w)
31            }
32        }
33
34        impl $crate::encode::Decodable for $hashtype {
35            fn consensus_decode<R: std::io::Read>(r: R) -> Result<Self, $crate::encode::Error> {
36                Ok(Self::from_byte_array(
37                    <<$hashtype as $crate::hashes::Hash>::Bytes>::consensus_decode(r)?,
38                ))
39            }
40        }
41    };
42}
43
44hash_newtype! {
45    /// An elements transaction ID
46    pub struct Txid(sha256d::Hash);
47    /// An elements witness transaction ID
48    pub struct Wtxid(sha256d::Hash);
49    /// An elements blockhash
50    pub struct BlockHash(sha256d::Hash);
51
52    /// "Hash of the transaction according to the signature algorithm"
53    pub struct Sighash(sha256d::Hash);
54
55    /// A hash of a public key.
56    pub struct PubkeyHash(hash160::Hash);
57    /// A hash of Bitcoin Script bytecode.
58    pub struct ScriptHash(hash160::Hash);
59    /// SegWit version of a public key hash.
60    pub struct WPubkeyHash(hash160::Hash);
61    /// SegWit version of a Bitcoin Script bytecode hash.
62    pub struct WScriptHash(sha256::Hash);
63
64    /// A hash of the Merkle tree branch or root for transactions
65    pub struct TxMerkleNode(sha256d::Hash);
66}
67
68impl_hashencode!(Txid);
69impl_hashencode!(Wtxid);
70impl_hashencode!(Sighash);
71impl_hashencode!(BlockHash);
72impl_hashencode!(TxMerkleNode);