2023-04-30 23:26:36 +00:00
|
|
|
// SPDX-License-Identifier: CC0-1.0
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
//! Rust hashes library.
|
|
|
|
//!
|
|
|
|
//! This is a simple, no-dependency library which implements the hash functions
|
|
|
|
//! needed by Bitcoin. These are SHA256, SHA256d, and RIPEMD160. As an ancillary
|
|
|
|
//! thing, it exposes hexadecimal serialization and deserialization, since these
|
|
|
|
//! are needed to display hashes anway.
|
|
|
|
//!
|
|
|
|
//! ## Commonly used operations
|
|
|
|
//!
|
|
|
|
//! Hashing a single byte slice or a string:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use bitcoin_hashes::sha256;
|
|
|
|
//! use bitcoin_hashes::Hash;
|
|
|
|
//!
|
|
|
|
//! let bytes = [0u8; 5];
|
|
|
|
//! let hash_of_bytes = sha256::Hash::hash(&bytes);
|
|
|
|
//! let hash_of_string = sha256::Hash::hash("some string".as_bytes());
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//!
|
|
|
|
//! Hashing content from a reader:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use bitcoin_hashes::sha256;
|
|
|
|
//! use bitcoin_hashes::Hash;
|
|
|
|
//!
|
|
|
|
//! #[cfg(std)]
|
|
|
|
//! # fn main() -> std::io::Result<()> {
|
|
|
|
//! let mut reader: &[u8] = b"hello"; // in real code, this could be a `File` or `TcpStream`
|
|
|
|
//! let mut engine = sha256::HashEngine::default();
|
|
|
|
//! std::io::copy(&mut reader, &mut engine)?;
|
|
|
|
//! let hash = sha256::Hash::from_engine(engine);
|
|
|
|
//! # Ok(())
|
|
|
|
//! # }
|
|
|
|
//!
|
|
|
|
//! #[cfg(not(std))]
|
|
|
|
//! # fn main() {}
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//!
|
|
|
|
//! Hashing content by [`std::io::Write`] on HashEngine:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! use bitcoin_hashes::sha256;
|
|
|
|
//! use bitcoin_hashes::Hash;
|
|
|
|
//! use std::io::Write;
|
|
|
|
//!
|
|
|
|
//! #[cfg(std)]
|
|
|
|
//! # fn main() -> std::io::Result<()> {
|
|
|
|
//! let mut part1: &[u8] = b"hello";
|
|
|
|
//! let mut part2: &[u8] = b" ";
|
|
|
|
//! let mut part3: &[u8] = b"world";
|
|
|
|
//! let mut engine = sha256::HashEngine::default();
|
|
|
|
//! engine.write_all(part1)?;
|
|
|
|
//! engine.write_all(part2)?;
|
|
|
|
//! engine.write_all(part3)?;
|
|
|
|
//! let hash = sha256::Hash::from_engine(engine);
|
|
|
|
//! # Ok(())
|
|
|
|
//! # }
|
|
|
|
//!
|
|
|
|
//! #[cfg(not(std))]
|
|
|
|
//! # fn main() {}
|
|
|
|
//! ```
|
|
|
|
|
2024-01-25 06:41:01 +00:00
|
|
|
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
|
|
|
|
|
2022-09-16 01:52:57 +00:00
|
|
|
// Experimental features we need.
|
2023-03-29 03:40:23 +00:00
|
|
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
2022-09-16 01:52:57 +00:00
|
|
|
#![cfg_attr(bench, feature(test))]
|
2024-01-25 06:41:01 +00:00
|
|
|
|
|
|
|
// Coding conventions.
|
|
|
|
#![warn(missing_docs)]
|
|
|
|
|
2022-11-30 04:05:05 +00:00
|
|
|
// Instead of littering the codebase for non-fuzzing code just globally allow.
|
2023-04-28 18:44:54 +00:00
|
|
|
#![cfg_attr(hashes_fuzz, allow(dead_code, unused_imports))]
|
2024-01-25 06:41:01 +00:00
|
|
|
|
|
|
|
// Exclude lints we don't think are valuable.
|
2023-10-20 14:58:42 +00:00
|
|
|
#![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134
|
2024-01-25 06:41:01 +00:00
|
|
|
#![allow(clippy::manual_range_contains)] // More readable than clippy's format.
|
2022-11-30 04:05:05 +00:00
|
|
|
|
2023-02-21 23:25:12 +00:00
|
|
|
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
|
|
|
extern crate alloc;
|
|
|
|
#[cfg(any(test, feature = "std"))]
|
|
|
|
extern crate core;
|
2023-05-08 08:57:49 +00:00
|
|
|
|
2023-02-21 23:25:12 +00:00
|
|
|
#[cfg(feature = "serde")]
|
2023-05-08 08:57:49 +00:00
|
|
|
/// A generic serialization/deserialization framework.
|
2023-02-21 23:25:12 +00:00
|
|
|
pub extern crate serde;
|
2023-05-08 08:57:49 +00:00
|
|
|
|
2023-02-21 23:25:12 +00:00
|
|
|
#[cfg(all(test, feature = "serde"))]
|
|
|
|
extern crate serde_test;
|
|
|
|
#[cfg(bench)]
|
|
|
|
extern crate test;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
2023-07-21 00:38:34 +00:00
|
|
|
/// Re-export the `hex-conservative` crate.
|
|
|
|
pub extern crate hex;
|
|
|
|
|
2022-09-16 01:52:57 +00:00
|
|
|
#[doc(hidden)]
|
|
|
|
pub mod _export {
|
|
|
|
/// A re-export of core::*
|
|
|
|
pub mod _core {
|
|
|
|
pub use core::*;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "schemars")]
|
2023-03-06 22:39:20 +00:00
|
|
|
extern crate schemars;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
mod internal_macros;
|
2023-02-21 23:25:12 +00:00
|
|
|
#[macro_use]
|
|
|
|
mod util;
|
|
|
|
#[macro_use]
|
|
|
|
pub mod serde_macros;
|
|
|
|
pub mod cmp;
|
2022-09-16 01:52:57 +00:00
|
|
|
pub mod hash160;
|
|
|
|
pub mod hmac;
|
Add a `bitcoin_io` crate
In order to support standard (de)serialization of structs, the
`rust-bitcoin` ecosystem uses the standard `std::io::{Read,Write}`
traits. This works great for environments with `std`, however sadly
the `std::io` module has not yet been added to the `core` crate.
Thus, in `no-std`, the `rust-bitcoin` ecosystem has historically
used the `core2` crate to provide copies of the `std::io` module
without any major dependencies. Sadly, its one dependency,
`memchr`, recently broke our MSRV.
Worse, because we didn't want to take on any excess dependencies
for `std` builds, `rust-bitcoin` has had to have
mutually-exclusive `std` and `no-std` builds. This breaks general
assumptions about how features work in Rust, causing substantial
pain for applications far downstream of `rust-bitcoin` crates.
Here, we add a new `bitcoin_io` crate, making it an unconditional
dependency and using its `io` module in the in-repository crates
in place of `std::io` and `core2::io`. As it is not substantial
additional code, the `hashes` io implementations are no longer
feature-gated.
This doesn't actually accomplish anything on its own, only adding
the new crate which still depends on `core2`.
2023-10-04 05:51:26 +00:00
|
|
|
#[cfg(feature = "bitcoin-io")]
|
2023-02-21 23:25:12 +00:00
|
|
|
mod impls;
|
2022-09-16 01:52:57 +00:00
|
|
|
pub mod ripemd160;
|
|
|
|
pub mod sha1;
|
|
|
|
pub mod sha256;
|
|
|
|
pub mod sha256d;
|
|
|
|
pub mod sha256t;
|
|
|
|
pub mod sha512;
|
2022-11-23 07:48:57 +00:00
|
|
|
pub mod sha512_256;
|
2023-02-21 23:25:12 +00:00
|
|
|
pub mod siphash24;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
use core::{borrow, fmt, hash, ops};
|
|
|
|
|
2023-02-21 23:25:12 +00:00
|
|
|
pub use hmac::{Hmac, HmacEngine};
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// A hashing engine which bytes can be serialized into.
|
|
|
|
pub trait HashEngine: Clone + Default {
|
|
|
|
/// Byte array representing the internal state of the hash engine.
|
|
|
|
type MidState;
|
|
|
|
|
|
|
|
/// Outputs the midstate of the hash engine. This function should not be
|
|
|
|
/// used directly unless you really know what you're doing.
|
|
|
|
fn midstate(&self) -> Self::MidState;
|
|
|
|
|
|
|
|
/// Length of the hash's internal block size, in bytes.
|
|
|
|
const BLOCK_SIZE: usize;
|
|
|
|
|
|
|
|
/// Add data to the hash engine.
|
|
|
|
fn input(&mut self, data: &[u8]);
|
|
|
|
|
|
|
|
/// Return the number of bytes already n_bytes_hashed(inputted).
|
|
|
|
fn n_bytes_hashed(&self) -> usize;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Trait which applies to hashes of all types.
|
2023-02-21 23:25:12 +00:00
|
|
|
pub trait Hash:
|
|
|
|
Copy
|
|
|
|
+ Clone
|
|
|
|
+ PartialEq
|
|
|
|
+ Eq
|
|
|
|
+ PartialOrd
|
|
|
|
+ Ord
|
|
|
|
+ hash::Hash
|
|
|
|
+ fmt::Debug
|
|
|
|
+ fmt::Display
|
|
|
|
+ fmt::LowerHex
|
|
|
|
+ ops::Index<ops::RangeFull, Output = [u8]>
|
|
|
|
+ ops::Index<ops::RangeFrom<usize>, Output = [u8]>
|
|
|
|
+ ops::Index<ops::RangeTo<usize>, Output = [u8]>
|
|
|
|
+ ops::Index<ops::Range<usize>, Output = [u8]>
|
|
|
|
+ ops::Index<usize, Output = u8>
|
|
|
|
+ borrow::Borrow<[u8]>
|
2022-09-16 01:52:57 +00:00
|
|
|
{
|
|
|
|
/// A hashing engine which bytes can be serialized into. It is expected
|
|
|
|
/// to implement the `io::Write` trait, and to never return errors under
|
|
|
|
/// any conditions.
|
|
|
|
type Engine: HashEngine;
|
|
|
|
|
|
|
|
/// The byte array that represents the hash internally.
|
2023-01-28 22:47:24 +00:00
|
|
|
type Bytes: hex::FromHex + Copy;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// Constructs a new engine.
|
2023-02-21 23:25:12 +00:00
|
|
|
fn engine() -> Self::Engine { Self::Engine::default() }
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// Produces a hash from the current state of a given engine.
|
|
|
|
fn from_engine(e: Self::Engine) -> Self;
|
|
|
|
|
|
|
|
/// Length of the hash, in bytes.
|
|
|
|
const LEN: usize;
|
|
|
|
|
|
|
|
/// Copies a byte slice into a hash object.
|
2023-05-24 03:29:30 +00:00
|
|
|
fn from_slice(sl: &[u8]) -> Result<Self, FromSliceError>;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// Hashes some bytes.
|
|
|
|
fn hash(data: &[u8]) -> Self {
|
|
|
|
let mut engine = Self::engine();
|
|
|
|
engine.input(data);
|
|
|
|
Self::from_engine(engine)
|
|
|
|
}
|
|
|
|
|
2023-12-10 18:03:52 +00:00
|
|
|
/// Hashes all the byte slices retrieved from the iterator together.
|
|
|
|
fn hash_byte_chunks<B, I>(byte_slices: I) -> Self
|
|
|
|
where
|
|
|
|
B: AsRef<[u8]>,
|
|
|
|
I: IntoIterator<Item = B>,
|
|
|
|
{
|
|
|
|
let mut engine = Self::engine();
|
|
|
|
for slice in byte_slices {
|
|
|
|
engine.input(slice.as_ref());
|
|
|
|
}
|
|
|
|
Self::from_engine(engine)
|
|
|
|
}
|
|
|
|
|
2022-09-16 01:52:57 +00:00
|
|
|
/// Flag indicating whether user-visible serializations of this hash
|
|
|
|
/// should be backward. For some reason Satoshi decided this should be
|
|
|
|
/// true for `Sha256dHash`, so here we are.
|
|
|
|
const DISPLAY_BACKWARD: bool = false;
|
|
|
|
|
2023-01-28 22:47:24 +00:00
|
|
|
/// Returns the underlying byte array.
|
|
|
|
fn to_byte_array(self) -> Self::Bytes;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
2023-01-28 22:47:24 +00:00
|
|
|
/// Returns a reference to the underlying byte array.
|
|
|
|
fn as_byte_array(&self) -> &Self::Bytes;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// Constructs a hash from the underlying byte array.
|
2023-01-28 22:47:24 +00:00
|
|
|
fn from_byte_array(bytes: Self::Bytes) -> Self;
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
/// Returns an all zero hash.
|
|
|
|
///
|
|
|
|
/// An all zeros hash is a made up construct because there is not a known input that can create
|
|
|
|
/// it, however it is used in various places in Bitcoin e.g., the Bitcoin genesis block's
|
|
|
|
/// previous blockhash and the coinbase transaction's outpoint txid.
|
|
|
|
fn all_zeros() -> Self;
|
|
|
|
}
|
|
|
|
|
2023-05-24 03:29:30 +00:00
|
|
|
/// Attempted to create a hash from an invalid length slice.
|
Make error types uniform
On our way to v1.0.0 we are defining a standard for our error types,
this includes:
- Uses the following derives (unless not possible, usually because of `io::Error`)
`#[derive(Debug, Clone, PartialEq, Eq)]`
- Has `non_exhaustive` unless we really know we can commit to not adding
anything.
Furthermore, we are trying to make the codebase easy to read. Error code
is write-once-read-many (well it should be) so if we make all the error
code super uniform the users can flick to an error and quickly see what
it includes. In an effort to achieve this I have made up a style and
over recent times have change much of the error code to that new style,
this PR audits _all_ error types in the code base and enforces the
style, specifically:
- Is layed out: definition, [impl block], Display impl, error::Error impl, From impls
- `error::Error` impl matches on enum even if it returns `None` for all variants
- Display/Error impls import enum variants locally
- match uses *self and `ref e`
- error::Error variants that return `Some` come first, `None` after
Re: non_exhaustive
To make dev and review easier I have added `non_exhaustive` to _every_
error type. We can then remove it error by error as we see fit. This is
because it takes a bit of thinking to do and review where as this patch
should not take much brain power to review.
2023-10-04 02:55:45 +00:00
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
#[non_exhaustive]
|
2023-05-24 03:29:30 +00:00
|
|
|
pub struct FromSliceError {
|
|
|
|
expected: usize,
|
|
|
|
got: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for FromSliceError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "invalid slice length {} (expected {})", self.got, self.expected)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "std")]
|
|
|
|
impl std::error::Error for FromSliceError {
|
|
|
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
|
|
|
|
}
|
|
|
|
|
2022-09-16 01:52:57 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-02-21 23:25:12 +00:00
|
|
|
use crate::{sha256d, Hash};
|
2022-09-16 01:52:57 +00:00
|
|
|
|
2023-02-22 08:20:28 +00:00
|
|
|
hash_newtype! {
|
|
|
|
/// A test newtype
|
|
|
|
struct TestNewtype(sha256d::Hash);
|
|
|
|
|
|
|
|
/// A test newtype
|
|
|
|
struct TestNewtype2(sha256d::Hash);
|
|
|
|
}
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn convert_newtypes() {
|
|
|
|
let h1 = TestNewtype::hash(&[]);
|
2023-01-28 22:47:24 +00:00
|
|
|
let h2: TestNewtype2 = h1.to_raw_hash().into();
|
2022-09-16 01:52:57 +00:00
|
|
|
assert_eq!(&h1[..], &h2[..]);
|
|
|
|
|
|
|
|
let h = sha256d::Hash::hash(&[]);
|
|
|
|
let h2: TestNewtype = h.to_string().parse().unwrap();
|
2023-01-28 22:47:24 +00:00
|
|
|
assert_eq!(h2.to_raw_hash(), h);
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
}
|