bitcoin_hashes/
sha256d.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! SHA256d implementation (double SHA256).
4//!
5
6use core::ops::Index;
7use core::slice::SliceIndex;
8use core::str;
9
10use crate::{sha256, FromSliceError};
11
12crate::internal_macros::hash_type! {
13    256,
14    true,
15    "Output of the SHA256d hash function.",
16    "crate::util::json_hex_string::len_32"
17}
18
19type HashEngine = sha256::HashEngine;
20
21fn from_engine(e: sha256::HashEngine) -> Hash {
22    use crate::Hash as _;
23
24    let sha2 = sha256::Hash::from_engine(e);
25    let sha2d = sha256::Hash::hash(&sha2[..]);
26
27    let mut ret = [0; 32];
28    ret.copy_from_slice(&sha2d[..]);
29    Hash(ret)
30}
31
32#[cfg(test)]
33mod tests {
34    #[test]
35    #[cfg(feature = "alloc")]
36    fn test() {
37        use crate::{sha256, sha256d, Hash, HashEngine};
38
39        #[derive(Clone)]
40        struct Test {
41            input: &'static str,
42            output: Vec<u8>,
43            output_str: &'static str,
44        }
45
46        #[rustfmt::skip]
47        let tests = vec![
48            // Test vector copied out of rust-bitcoin
49            Test {
50                input: "",
51                output: vec![
52                    0x5d, 0xf6, 0xe0, 0xe2, 0x76, 0x13, 0x59, 0xd3,
53                    0x0a, 0x82, 0x75, 0x05, 0x8e, 0x29, 0x9f, 0xcc,
54                    0x03, 0x81, 0x53, 0x45, 0x45, 0xf5, 0x5c, 0xf4,
55                    0x3e, 0x41, 0x98, 0x3f, 0x5d, 0x4c, 0x94, 0x56,
56                ],
57                output_str: "56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d",
58            },
59        ];
60
61        for test in tests {
62            // Hash through high-level API, check hex encoding/decoding
63            let hash = sha256d::Hash::hash(test.input.as_bytes());
64            assert_eq!(hash, test.output_str.parse::<sha256d::Hash>().expect("parse hex"));
65            assert_eq!(&hash[..], &test.output[..]);
66            assert_eq!(&hash.to_string(), &test.output_str);
67
68            // Hash through engine, checking that we can input byte by byte
69            let mut engine = sha256d::Hash::engine();
70            for ch in test.input.as_bytes() {
71                engine.input(&[*ch]);
72            }
73            let manual_hash = sha256d::Hash::from_engine(engine);
74            assert_eq!(hash, manual_hash);
75
76            // Hash by computing a sha256 then `hash_again`ing it
77            let sha2_hash = sha256::Hash::hash(test.input.as_bytes());
78            let sha2d_hash = sha2_hash.hash_again();
79            assert_eq!(hash, sha2d_hash);
80
81            assert_eq!(hash.to_byte_array()[..].as_ref(), test.output.as_slice());
82        }
83    }
84
85    #[cfg(feature = "serde")]
86    #[test]
87    fn sha256_serde() {
88        use serde_test::{assert_tokens, Configure, Token};
89
90        use crate::{sha256d, Hash};
91
92        #[rustfmt::skip]
93        static HASH_BYTES: [u8; 32] = [
94            0xef, 0x53, 0x7f, 0x25, 0xc8, 0x95, 0xbf, 0xa7,
95            0x82, 0x52, 0x65, 0x29, 0xa9, 0xb6, 0x3d, 0x97,
96            0xaa, 0x63, 0x15, 0x64, 0xd5, 0xd7, 0x89, 0xc2,
97            0xb7, 0x65, 0x44, 0x8c, 0x86, 0x35, 0xfb, 0x6c,
98        ];
99
100        let hash = sha256d::Hash::from_slice(&HASH_BYTES).expect("right number of bytes");
101        assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]);
102        assert_tokens(
103            &hash.readable(),
104            &[Token::Str("6cfb35868c4465b7c289d7d5641563aa973db6a929655282a7bf95c8257f53ef")],
105        );
106    }
107}
108
109#[cfg(bench)]
110mod benches {
111    use test::Bencher;
112
113    use crate::{sha256d, Hash, HashEngine};
114
115    #[bench]
116    pub fn sha256d_10(bh: &mut Bencher) {
117        let mut engine = sha256d::Hash::engine();
118        let bytes = [1u8; 10];
119        bh.iter(|| {
120            engine.input(&bytes);
121        });
122        bh.bytes = bytes.len() as u64;
123    }
124
125    #[bench]
126    pub fn sha256d_1k(bh: &mut Bencher) {
127        let mut engine = sha256d::Hash::engine();
128        let bytes = [1u8; 1024];
129        bh.iter(|| {
130            engine.input(&bytes);
131        });
132        bh.bytes = bytes.len() as u64;
133    }
134
135    #[bench]
136    pub fn sha256d_64k(bh: &mut Bencher) {
137        let mut engine = sha256d::Hash::engine();
138        let bytes = [1u8; 65536];
139        bh.iter(|| {
140            engine.input(&bytes);
141        });
142        bh.bytes = bytes.len() as u64;
143    }
144}