fuchsia_merkle/
lib.rs

1// Copyright 2018 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! `fuchsia_merkle` contains types and methods for building and working with merkle trees.
6//!
7//! See https://fuchsia.dev/fuchsia-src/concepts/security/merkleroot for information on constructing
8//! merkle trees.
9
10#![deny(missing_docs)]
11
12use std::io::{self, Read};
13
14pub use fuchsia_hash::{HASH_SIZE, Hash};
15
16/// The size of a single block of data (or hashes), in bytes.
17pub const BLOCK_SIZE: usize = 8192;
18
19mod util;
20
21mod merkle_root_builder;
22pub use crate::merkle_root_builder::{
23    BufferedMerkleRootBuilder, LeafHashCollector, MerkleRootBuilder, NoopLeafHashCollector,
24};
25
26mod merkle_verifier;
27pub use crate::merkle_verifier::{MerkleVerifier, ReadSizedMerkleVerifier};
28
29/// Computes the merkle root of in-memory data.
30pub fn root_from_slice(slice: impl AsRef<[u8]>) -> Hash {
31    MerkleRootBuilder::default().complete(slice.as_ref())
32}
33
34/// Computes the merkle root of the contents of a `std::io::Read`.
35pub fn root_from_reader(mut reader: impl Read) -> Result<Hash, io::Error> {
36    let mut builder = BufferedMerkleRootBuilder::default();
37    std::io::copy(&mut reader, &mut builder)?;
38    Ok(builder.complete())
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_root_from_reader() {
47        let file = b"hello world";
48        let expected = MerkleRootBuilder::default().complete(file);
49
50        let actual = root_from_reader(&file[..]).unwrap();
51        assert_eq!(expected, actual);
52    }
53}