2014-07-18 13:56:17 +00:00
|
|
|
// Rust Bitcoin Library
|
|
|
|
// Written in 2014 by
|
2015-04-07 22:51:57 +00:00
|
|
|
// Andrew Poelstra <apoelstra@wpsoftware.net>
|
2014-07-18 13:56:17 +00:00
|
|
|
// To the extent possible under law, the author(s) have dedicated all
|
|
|
|
// copyright and related and neighboring rights to this software to
|
|
|
|
// the public domain worldwide. This software is distributed without
|
|
|
|
// any warranty.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the CC0 Public Domain Dedication
|
|
|
|
// along with this software.
|
|
|
|
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
|
|
|
|
//
|
|
|
|
|
2021-11-05 21:58:18 +00:00
|
|
|
//! Bitcoin hash functions.
|
|
|
|
//!
|
|
|
|
//! This module provides utility functions related to hashing data, including
|
|
|
|
//! merkleization.
|
2014-07-18 13:56:17 +00:00
|
|
|
//!
|
|
|
|
|
2021-11-18 22:58:58 +00:00
|
|
|
use core::iter;
|
|
|
|
|
2021-06-09 10:34:44 +00:00
|
|
|
use prelude::*;
|
|
|
|
|
2021-06-09 10:40:41 +00:00
|
|
|
use io;
|
|
|
|
use core::cmp::min;
|
2014-07-18 13:56:17 +00:00
|
|
|
|
2019-12-06 09:01:15 +00:00
|
|
|
use hashes::Hash;
|
2019-12-18 11:40:46 +00:00
|
|
|
use consensus::encode::Encodable;
|
2014-07-18 13:56:17 +00:00
|
|
|
|
2021-11-18 22:58:58 +00:00
|
|
|
/// Calculates the merkle root of a list of *hashes*, inline (in place) in `hashes`.
|
2019-12-18 11:40:46 +00:00
|
|
|
///
|
|
|
|
/// In most cases, you'll want to use [bitcoin_merkle_root] instead.
|
2021-11-18 22:58:58 +00:00
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
/// - `None` if `hashes` is empty. The merkle root of an empty tree of hashes is undefined.
|
|
|
|
/// - `Some(hash)` if `hashes` contains one element. A single hash is by definition the merkle root.
|
|
|
|
/// - `Some(merkle_root)` if length of `hashes` is greater than one.
|
|
|
|
pub fn bitcoin_merkle_root_inline<T>(hashes: &mut [T]) -> Option<T>
|
2022-01-24 00:33:03 +00:00
|
|
|
where
|
|
|
|
T: Hash + Encodable,
|
2019-12-18 11:40:46 +00:00
|
|
|
<T as Hash>::Engine: io::Write,
|
|
|
|
{
|
2021-11-18 22:58:58 +00:00
|
|
|
match hashes.len() {
|
|
|
|
0 => None,
|
|
|
|
1 => Some(hashes[0]),
|
|
|
|
_ => Some(merkle_root_r(hashes)),
|
2019-12-18 11:40:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-18 22:58:58 +00:00
|
|
|
/// Calculates the merkle root of an iterator of *hashes*.
|
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
/// - `None` if `hashes` is empty. The merkle root of an empty tree of hashes is undefined.
|
|
|
|
/// - `Some(hash)` if `hashes` contains one element. A single hash is by definition the merkle root.
|
|
|
|
/// - `Some(merkle_root)` if length of `hashes` is greater than one.
|
|
|
|
pub fn bitcoin_merkle_root<T, I>(mut hashes: I) -> Option<T>
|
2022-01-24 00:33:03 +00:00
|
|
|
where
|
|
|
|
T: Hash + Encodable,
|
|
|
|
<T as Hash>::Engine: io::Write,
|
|
|
|
I: Iterator<Item = T>,
|
2019-12-18 11:40:46 +00:00
|
|
|
{
|
2021-11-18 22:58:58 +00:00
|
|
|
let first = hashes.next()?;
|
|
|
|
let second = match hashes.next() {
|
|
|
|
Some(second) => second,
|
|
|
|
None => return Some(first),
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut hashes = iter::once(first).chain(iter::once(second)).chain(hashes);
|
|
|
|
|
|
|
|
// We need a local copy to pass to `merkle_root_r`. It's more efficient to do the first loop of
|
|
|
|
// processing as we make the copy instead of copying the whole iterator.
|
|
|
|
let (min, max) = hashes.size_hint();
|
|
|
|
let mut alloc = Vec::with_capacity(max.unwrap_or(min) / 2 + 1);
|
|
|
|
|
|
|
|
while let Some(hash1) = hashes.next() {
|
2019-12-18 11:40:46 +00:00
|
|
|
// If the size is odd, use the last element twice.
|
2021-11-18 22:58:58 +00:00
|
|
|
let hash2 = hashes.next().unwrap_or(hash1);
|
2019-12-18 11:40:46 +00:00
|
|
|
let mut encoder = T::engine();
|
2021-11-24 23:07:25 +00:00
|
|
|
hash1.consensus_encode(&mut encoder).expect("in-memory writers don't error");
|
|
|
|
hash2.consensus_encode(&mut encoder).expect("in-memory writers don't error");
|
2019-12-18 11:40:46 +00:00
|
|
|
alloc.push(T::from_engine(encoder));
|
2018-06-01 22:46:10 +00:00
|
|
|
}
|
2021-11-18 22:58:58 +00:00
|
|
|
|
|
|
|
Some(merkle_root_r(&mut alloc))
|
|
|
|
}
|
|
|
|
|
|
|
|
// `hashes` must contain at least one hash.
|
|
|
|
fn merkle_root_r<T>(hashes: &mut [T]) -> T
|
2022-01-24 00:33:03 +00:00
|
|
|
where
|
|
|
|
T: Hash + Encodable,
|
|
|
|
<T as Hash>::Engine: io::Write,
|
2021-11-18 22:58:58 +00:00
|
|
|
{
|
|
|
|
if hashes.len() == 1 {
|
|
|
|
return hashes[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
for idx in 0..((hashes.len() + 1) / 2) {
|
|
|
|
let idx1 = 2 * idx;
|
|
|
|
let idx2 = min(idx1 + 1, hashes.len() - 1);
|
|
|
|
let mut encoder = T::engine();
|
|
|
|
hashes[idx1].consensus_encode(&mut encoder).expect("in-memory writers don't error");
|
|
|
|
hashes[idx2].consensus_encode(&mut encoder).expect("in-memory writers don't error");
|
|
|
|
hashes[idx] = T::from_engine(encoder);
|
|
|
|
}
|
|
|
|
let half_len = hashes.len() / 2 + hashes.len() % 2;
|
|
|
|
|
|
|
|
merkle_root_r(&mut hashes[0..half_len])
|
2018-06-01 22:46:10 +00:00
|
|
|
}
|
2021-11-19 00:18:51 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use consensus::encode::deserialize;
|
|
|
|
use hashes::sha256d;
|
|
|
|
|
|
|
|
use blockdata::block::Block;
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
2021-11-23 23:30:11 +00:00
|
|
|
fn both_merkle_root_functions_return_the_same_result() {
|
2021-11-19 00:18:51 +00:00
|
|
|
// testnet block 000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b
|
2021-12-31 10:07:36 +00:00
|
|
|
let segwit_block = include_bytes!("../../test_data/testnet_block_000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b.raw");
|
|
|
|
let block: Block = deserialize(&segwit_block[..]).expect("Failed to deserialize block");
|
2021-11-19 00:18:51 +00:00
|
|
|
assert!(block.check_merkle_root()); // Sanity check.
|
|
|
|
|
|
|
|
let hashes_iter = block.txdata.iter().map(|obj| obj.txid().as_hash());
|
|
|
|
|
|
|
|
let mut hashes_array: [sha256d::Hash; 15] = [Default::default(); 15];
|
|
|
|
for (i, hash) in hashes_iter.clone().enumerate() {
|
|
|
|
hashes_array[i] = hash;
|
|
|
|
}
|
|
|
|
|
|
|
|
let from_iter = bitcoin_merkle_root(hashes_iter);
|
|
|
|
let from_array = bitcoin_merkle_root_inline(&mut hashes_array);
|
|
|
|
assert_eq!(from_iter, from_array);
|
|
|
|
}
|
|
|
|
}
|