#merkle-tree #tree-hash #hash-tree #data-integrity #stream #data-stream #incoming

merkle-tree-stream

A stream that generates a merkle tree based on the incoming data

18 releases (11 breaking)

0.12.1 Jul 9, 2020
0.12.0 Mar 3, 2020
0.11.0 Feb 18, 2020
0.10.0 Jul 18, 2019
0.1.1 Mar 16, 2018

#1045 in Cryptography

Download history 70/week @ 2024-07-22 220/week @ 2024-07-29 35/week @ 2024-08-05 44/week @ 2024-08-12 31/week @ 2024-08-19 57/week @ 2024-08-26 119/week @ 2024-09-02 176/week @ 2024-09-09 21/week @ 2024-09-16 199/week @ 2024-09-23 78/week @ 2024-09-30 4/week @ 2024-10-07 26/week @ 2024-10-14 121/week @ 2024-10-21 45/week @ 2024-10-28 17/week @ 2024-11-04

209 downloads per month
Used in 6 crates (via hypercore)

MIT/Apache

24KB
204 lines

merkle-tree-stream

crates.io version build status downloads docs.rs docs

A stream that generates a merkle tree based on the incoming data. Adapted from mafintosh/merkle-tree-stream.

Why?

Signatures & integrity checks are part of what makes Dat a great protocol. Each chunk that passes through the system is hashed and made part of a tree of hashes. We end up creating hashes of hashes thanks to flat-tree, which in the end allows us to validate our complete data set.

This module is only needed to create new Dat archives, but not to read them.

Usage

extern crate merkle_tree_stream;
extern crate rust_sodium;

use merkle_tree_stream::{HashMethods, DefaultNode, MerkleTreeStream, Node,
                        PartialNode};
use rust_sodium::crypto::hash::sha256;
use std::sync::Arc;

struct H;
impl HashMethods for H {
  type Node = DefaultNode;
  type Hash = Vec<u8>;

  fn leaf(&self, leaf: &PartialNode, _roots: &[Arc<Self::Node>]) -> Self::Hash {
    let data = leaf.as_ref().unwrap();
    sha256::hash(&data).0.to_vec()
  }

  fn parent(&self, a: &Self::Node, b: &Self::Node) -> Self::Hash {
    let mut buf = Vec::with_capacity(a.hash().len() + b.hash().len());
    buf.extend_from_slice(a.hash());
    buf.extend_from_slice(b.hash());
    sha256::hash(&buf).0.to_vec()
  }
}

fn main() {
  let roots = Vec::new();
  let mut mts = MerkleTreeStream::new(H, roots);
  let mut nodes = vec![];
  mts.next(b"hello", &mut nodes);
  mts.next(b"hashed", &mut nodes);
  mts.next(b"world", &mut nodes);
  println!("nodes {:?}", nodes);
}

Custom Node or Hash types

If you have a specific need for a Node type that is not covered by the DefaultNode type, you can define your own by implementing the Node trait and the appropriate From<NodeParts<Self::Hash>> trait for your new type. You can use the DefaultNode implementation as a guide.

Installation

$ cargo add merkle-tree-stream

License

MIT OR Apache-2.0

Dependencies

~26KB