This commit is contained in:
dtsbourg
2016-11-11 19:39:07 +01:00
parent a57d0c803e
commit a0497ec4ad
5 changed files with 14 additions and 4 deletions

View File

@ -1,19 +1,23 @@
/// By definition, data in the Merkle Tree must implement Hashable
pub trait Hashable {
fn to_bytes(&self) -> Vec<u8>;
}
/// Hashable implementation for standard String type
impl Hashable for String {
fn to_bytes(&self) -> Vec<u8> {
self.clone().into_bytes()
}
}
// Implementation for standard u8 type
impl Hashable for u8 {
fn to_bytes(&self) -> Vec<u8> {
vec![*self]
}
}
// Implementation for standard &str type
impl Hashable for &'static str {
fn to_bytes(&self) -> Vec<u8> {
self.as_bytes().to_vec()

View File

@ -1,6 +1,7 @@
#![allow(dead_code)]
//! *merkle* implements a Merkle Tree in Rust.
#[doc(no_inline)]
pub extern crate crypto;
mod tree;
@ -14,4 +15,3 @@ pub use merkledigest::{ MerkleDigest };
#[cfg(test)]
mod tests;

View File

@ -1,5 +1,6 @@
use crypto::digest::Digest;
/// Extends the standard `crypto::digest::Digest` to play nicely with our Merkle Tree
pub trait MerkleDigest {
fn hash_bytes(&mut self, bytes: &Vec<u8>) -> Vec<u8>;
fn combine_hashes(&mut self, left: &Vec<u8>, right: &Vec<u8>) -> Vec<u8>;

View File

@ -4,6 +4,7 @@ use tree::{ Tree };
use hashable::{ Hashable };
use merkledigest::{ MerkleDigest };
/// The Merkle tree
pub struct MerkleTree<D, T> {
digest: D,
tree: Tree<T>,
@ -12,7 +13,7 @@ pub struct MerkleTree<D, T> {
}
impl <D, T> MerkleTree<D, T> where D: Digest, T: Hashable {
/// Constructs a Merkle Tree from a vector of data blocks.
pub fn from_vec(mut digest: D, values: Vec<T>) -> Self {
if values.is_empty() {
panic!("Cannot build a Merkle tree from an empty vector.");
@ -72,6 +73,7 @@ impl <D, T> MerkleTree<D, T> where D: Digest, T: Hashable {
}
}
/// Returns the tree's root hash.
pub fn root_hash(&self) -> &Vec<u8> {
self.tree.get_hash()
}

View File

@ -3,6 +3,7 @@ use crypto::digest::Digest;
use hashable::{ Hashable };
use merkledigest::{ MerkleDigest };
/// Binary Tree where leaves hold a stand-alone value.
pub enum Tree<T> {
Leaf {
hash: Vec<u8>,
@ -17,7 +18,7 @@ pub enum Tree<T> {
}
impl <T> Tree<T> where T: Hashable {
/// Create a new tree
pub fn new(hash: Vec<u8>, value: T) -> Self {
Tree::Leaf {
hash: hash,
@ -25,6 +26,7 @@ impl <T> Tree<T> where T: Hashable {
}
}
/// Returns a hash from the tree.
pub fn get_hash(&self) -> &Vec<u8> {
match *self {
Tree::Leaf { ref hash, value: _ } => hash,
@ -32,6 +34,7 @@ impl <T> Tree<T> where T: Hashable {
}
}
/// Create a new leaf
pub fn make_leaf<D: Digest>(digest: &mut D, value: T) -> Tree<T> {
let hash = digest.hash_bytes(&value.to_bytes());
Tree::new(hash, value)