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