Skip to main content

zcash_primitives/transaction/util/
sha256d.rs

1//! SHA-256d (double SHA-256) hashing of data as it is read or written.
2
3use corez::io::{self, Read, Write};
4use sha2::{Digest, Sha256, digest::Output};
5
6/// Abstraction over a reader which SHA-256d-hashes the data being read.
7pub struct HashReader<R: Read> {
8    reader: R,
9    hasher: Sha256,
10}
11
12impl<R: Read> HashReader<R> {
13    /// Construct a new `HashReader` given an existing `reader` by value.
14    pub fn new(reader: R) -> Self {
15        HashReader {
16            reader,
17            hasher: Sha256::new(),
18        }
19    }
20
21    /// Destroy this reader and return the underlying reader, discarding the hash of what
22    /// was read.
23    pub fn into_base_reader(self) -> R {
24        self.reader
25    }
26
27    /// Destroy this reader and return the hash of what was read.
28    pub fn into_hash(self) -> Output<Sha256> {
29        Sha256::digest(self.hasher.finalize())
30    }
31}
32
33impl<R: Read> Read for HashReader<R> {
34    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
35        let bytes = self.reader.read(buf)?;
36
37        if bytes > 0 {
38            self.hasher.update(&buf[0..bytes]);
39        }
40
41        Ok(bytes)
42    }
43}
44
45/// Abstraction over a writer which SHA-256d-hashes the data being written.
46pub struct HashWriter {
47    hasher: Sha256,
48}
49
50impl Default for HashWriter {
51    fn default() -> Self {
52        HashWriter {
53            hasher: Sha256::new(),
54        }
55    }
56}
57
58impl HashWriter {
59    /// Destroy this writer and return the hash of what was written.
60    pub fn into_hash(self) -> Output<Sha256> {
61        Sha256::digest(self.hasher.finalize())
62    }
63}
64
65impl Write for HashWriter {
66    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
67        self.hasher.update(buf);
68
69        Ok(buf.len())
70    }
71
72    fn flush(&mut self) -> io::Result<()> {
73        Ok(())
74    }
75}