bitcoin_hashes/
lib.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Rust hashes library.
4//!
5//! This is a simple, no-dependency library which implements the hash functions
6//! needed by Bitcoin. These are SHA256, SHA256d, and RIPEMD160. As an ancillary
7//! thing, it exposes hexadecimal serialization and deserialization, since these
8//! are needed to display hashes anway.
9//!
10//! ## Commonly used operations
11//!
12//! Hashing a single byte slice or a string:
13//!
14//! ```rust
15//! use bitcoin_hashes::sha256;
16//! use bitcoin_hashes::Hash;
17//!
18//! let bytes = [0u8; 5];
19//! let hash_of_bytes = sha256::Hash::hash(&bytes);
20//! let hash_of_string = sha256::Hash::hash("some string".as_bytes());
21//! ```
22//!
23//!
24//! Hashing content from a reader:
25//!
26//! ```rust
27//! use bitcoin_hashes::sha256;
28//! use bitcoin_hashes::Hash;
29//!
30//! #[cfg(std)]
31//! # fn main() -> std::io::Result<()> {
32//! let mut reader: &[u8] = b"hello"; // in real code, this could be a `File` or `TcpStream`
33//! let mut engine = sha256::HashEngine::default();
34//! std::io::copy(&mut reader, &mut engine)?;
35//! let hash = sha256::Hash::from_engine(engine);
36//! # Ok(())
37//! # }
38//!
39//! #[cfg(not(std))]
40//! # fn main() {}
41//! ```
42//!
43//!
44//! Hashing content by [`std::io::Write`] on HashEngine:
45//!
46//! ```rust
47//! use bitcoin_hashes::sha256;
48//! use bitcoin_hashes::Hash;
49//! use std::io::Write;
50//!
51//! #[cfg(std)]
52//! # fn main() -> std::io::Result<()> {
53//! let mut part1: &[u8] = b"hello";
54//! let mut part2: &[u8] = b" ";
55//! let mut part3: &[u8] = b"world";
56//! let mut engine = sha256::HashEngine::default();
57//! engine.write_all(part1)?;
58//! engine.write_all(part2)?;
59//! engine.write_all(part3)?;
60//! let hash = sha256::Hash::from_engine(engine);
61//! # Ok(())
62//! # }
63//!
64//! #[cfg(not(std))]
65//! # fn main() {}
66//! ```
67
68#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
69
70// Experimental features we need.
71#![cfg_attr(docsrs, feature(doc_auto_cfg))]
72#![cfg_attr(bench, feature(test))]
73
74// Coding conventions.
75#![warn(missing_docs)]
76
77// Instead of littering the codebase for non-fuzzing code just globally allow.
78#![cfg_attr(hashes_fuzz, allow(dead_code, unused_imports))]
79
80// Exclude lints we don't think are valuable.
81#![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134
82#![allow(clippy::manual_range_contains)] // More readable than clippy's format.
83
84#[cfg(all(feature = "alloc", not(feature = "std")))]
85extern crate alloc;
86#[cfg(any(test, feature = "std"))]
87extern crate core;
88
89#[cfg(feature = "serde")]
90/// A generic serialization/deserialization framework.
91pub extern crate serde;
92
93#[cfg(all(test, feature = "serde"))]
94extern crate serde_test;
95#[cfg(bench)]
96extern crate test;
97
98/// Re-export the `hex-conservative` crate.
99pub extern crate hex;
100
101#[doc(hidden)]
102pub mod _export {
103    /// A re-export of core::*
104    pub mod _core {
105        pub use core::*;
106    }
107}
108
109#[cfg(feature = "schemars")]
110extern crate schemars;
111
112mod internal_macros;
113#[macro_use]
114mod util;
115#[macro_use]
116pub mod serde_macros;
117pub mod cmp;
118pub mod hash160;
119pub mod hmac;
120#[cfg(feature = "bitcoin-io")]
121mod impls;
122pub mod ripemd160;
123pub mod sha1;
124pub mod sha256;
125pub mod sha256d;
126pub mod sha256t;
127pub mod sha384;
128pub mod sha512;
129pub mod sha512_256;
130pub mod siphash24;
131
132use core::{borrow, fmt, hash, ops};
133
134pub use hmac::{Hmac, HmacEngine};
135
136/// A hashing engine which bytes can be serialized into.
137pub trait HashEngine: Clone + Default {
138    /// Byte array representing the internal state of the hash engine.
139    type MidState;
140
141    /// Outputs the midstate of the hash engine. This function should not be
142    /// used directly unless you really know what you're doing.
143    fn midstate(&self) -> Self::MidState;
144
145    /// Length of the hash's internal block size, in bytes.
146    const BLOCK_SIZE: usize;
147
148    /// Add data to the hash engine.
149    fn input(&mut self, data: &[u8]);
150
151    /// Return the number of bytes already n_bytes_hashed(inputted).
152    fn n_bytes_hashed(&self) -> usize;
153}
154
155/// Trait which applies to hashes of all types.
156pub trait Hash:
157    Copy
158    + Clone
159    + PartialEq
160    + Eq
161    + PartialOrd
162    + Ord
163    + hash::Hash
164    + fmt::Debug
165    + fmt::Display
166    + fmt::LowerHex
167    + ops::Index<ops::RangeFull, Output = [u8]>
168    + ops::Index<ops::RangeFrom<usize>, Output = [u8]>
169    + ops::Index<ops::RangeTo<usize>, Output = [u8]>
170    + ops::Index<ops::Range<usize>, Output = [u8]>
171    + ops::Index<usize, Output = u8>
172    + borrow::Borrow<[u8]>
173{
174    /// A hashing engine which bytes can be serialized into. It is expected
175    /// to implement the `io::Write` trait, and to never return errors under
176    /// any conditions.
177    type Engine: HashEngine;
178
179    /// The byte array that represents the hash internally.
180    type Bytes: hex::FromHex + Copy;
181
182    /// Constructs a new engine.
183    fn engine() -> Self::Engine { Self::Engine::default() }
184
185    /// Produces a hash from the current state of a given engine.
186    fn from_engine(e: Self::Engine) -> Self;
187
188    /// Length of the hash, in bytes.
189    const LEN: usize;
190
191    /// Copies a byte slice into a hash object.
192    fn from_slice(sl: &[u8]) -> Result<Self, FromSliceError>;
193
194    /// Hashes some bytes.
195    fn hash(data: &[u8]) -> Self {
196        let mut engine = Self::engine();
197        engine.input(data);
198        Self::from_engine(engine)
199    }
200
201    /// Hashes all the byte slices retrieved from the iterator together.
202    fn hash_byte_chunks<B, I>(byte_slices: I) -> Self
203    where
204        B: AsRef<[u8]>,
205        I: IntoIterator<Item = B>,
206    {
207        let mut engine = Self::engine();
208        for slice in byte_slices {
209            engine.input(slice.as_ref());
210        }
211        Self::from_engine(engine)
212    }
213
214    /// Flag indicating whether user-visible serializations of this hash
215    /// should be backward. For some reason Satoshi decided this should be
216    /// true for `Sha256dHash`, so here we are.
217    const DISPLAY_BACKWARD: bool = false;
218
219    /// Returns the underlying byte array.
220    fn to_byte_array(self) -> Self::Bytes;
221
222    /// Returns a reference to the underlying byte array.
223    fn as_byte_array(&self) -> &Self::Bytes;
224
225    /// Constructs a hash from the underlying byte array.
226    fn from_byte_array(bytes: Self::Bytes) -> Self;
227
228    /// Returns an all zero hash.
229    ///
230    /// An all zeros hash is a made up construct because there is not a known input that can create
231    /// it, however it is used in various places in Bitcoin e.g., the Bitcoin genesis block's
232    /// previous blockhash and the coinbase transaction's outpoint txid.
233    fn all_zeros() -> Self;
234}
235
236/// Attempted to create a hash from an invalid length slice.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct FromSliceError {
239    expected: usize,
240    got: usize,
241}
242
243impl FromSliceError {
244    /// Returns the expected slice length.
245    pub fn expected_length(&self) -> usize { self.expected }
246
247    /// Returns the invalid slice length.
248    pub fn invalid_length(&self) -> usize { self.got }
249}
250
251impl fmt::Display for FromSliceError {
252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253        write!(f, "invalid slice length {} (expected {})", self.got, self.expected)
254    }
255}
256
257#[cfg(feature = "std")]
258impl std::error::Error for FromSliceError {}
259
260#[cfg(test)]
261mod tests {
262    use crate::{sha256d, Hash};
263
264    hash_newtype! {
265        /// A test newtype
266        struct TestNewtype(sha256d::Hash);
267
268        /// A test newtype
269        struct TestNewtype2(sha256d::Hash);
270    }
271
272    #[test]
273    fn convert_newtypes() {
274        let h1 = TestNewtype::hash(&[]);
275        let h2: TestNewtype2 = h1.to_raw_hash().into();
276        assert_eq!(&h1[..], &h2[..]);
277
278        let h = sha256d::Hash::hash(&[]);
279        let h2: TestNewtype = h.to_string().parse().unwrap();
280        assert_eq!(h2.to_raw_hash(), h);
281    }
282
283    #[test]
284    fn newtype_fmt_roundtrip() {
285        let orig = TestNewtype::hash(&[]);
286        let hex = format!("{}", orig);
287        let rinsed = hex.parse::<TestNewtype>().expect("failed to parse hex");
288        assert_eq!(rinsed, orig)
289    }
290}