1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#![allow(dead_code)]
use std::collections::VecDeque;
use std::io::prelude::*;
use std::io::Result;
use std::fmt::{Debug, Display};

type NodePtr<T> = Box<HashTreeNode<T>>;

/// A node from the `HashTree`.
#[derive(Debug, Clone)]
pub struct HashTreeNode<T>
where
    T: Debug + Clone + PartialEq 
{
    hash: T,
    left: Option<NodePtr<T>>,
    right: Option<NodePtr<T>>,
}

impl<T> HashTreeNode<T> 
where
    T: Debug + Clone + PartialEq 
{
    pub fn new(hash: T) -> Self {
        Self {
            hash,
            left: None,
            right: None,
        }
    }

    pub fn hash(&self) -> &T {
        &self.hash
    }

    pub fn print_inorder(&self) {
        if let Some(ref left) = self.left {
            left.print_inorder();
        }
        println!("{}", self);
        if let Some(ref right) = self.right {
            right.print_inorder();
        }
    }

    pub fn print_preorder(&self) {
        println!("{}", self);
        if let Some(ref left) = self.left {
            left.print_preorder();
        }
        if let Some(ref right) = self.right {
            right.print_preorder();
        }
    }

    pub fn print_postorder(&self) {
        if let Some(ref left) = self.left {
            left.print_postorder();
        }
        if let Some(ref right) = self.right {
            right.print_postorder();
        }
        println!("{}", self);
    }
}

impl<T> Display for HashTreeNode<T> 
where
    T: Debug + Clone + PartialEq
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[hash {:?}]", self.hash)
    }
}

/// A struct that defines how the `HashTree` should partition and hash
/// the blocks of data.
#[derive(Debug, Clone)]
pub struct HashStrategy<T, F> 
where
    T: Debug + Clone + PartialEq,
    F: Fn(&[u8]) -> T,
{
    block_size: usize,
    hash_function: F,
}

// TODO: Implement custom hash function strategy through 
// a closure to HashStrategy::new()
impl<T, F> HashStrategy<T, F>
where
    T: Debug + Clone + PartialEq,
    F: Fn(&[u8]) -> T,
{
    pub fn new(block_size: usize, hash_function: F) -> Self {
        Self {
            block_size,
            hash_function
        }
    }
}

/// A Merkle-tree.
#[derive(Debug, Clone)]
pub struct HashTree<T, F> 
where
    T: Debug + Clone + PartialEq,
    F: Fn(&[u8]) -> T,
{
    root: Option<NodePtr<T>>,
    num_nodes: usize,
    num_blocks: usize,
    strategy: HashStrategy<T, F>,
}

impl<T, F> HashTree<T, F> 
where
    T: Debug + Clone + PartialEq,
    F: Fn(&[u8]) -> T,
{
    /// Constructs a new empty `HashTree<T>` with a given
    /// `HashStrategy<T, F>`.
    ///
    /// # Examples
    ///
    /// ```
    /// #![allow(dead_code)]
    /// use hashtree::{HashTree, HashStrategy};
    ///
    /// const BLOCK_SIZE: usize = 4096;
    ///
    /// fn main() {
    ///     let tree = HashTree::new(
    ///         HashStrategy::new(BLOCK_SIZE, |data| {
    ///             md5::compute(data)
    ///         })
    ///     );
    /// }
    /// ```
    pub fn new(strategy: HashStrategy<T, F>) -> Self {
        Self {
            root: None,
            num_nodes: 0,
            num_blocks: 0,
            strategy,
        }
    }

    /// Constructs a new `HashTree<T, F>` from a mutable object
    /// that implements the `Read` trait and a `HashStrategy<T, F>`.
    /// Returns an `Error` value if the function failed to read from
    /// the given object.
    ///
    /// # Examples
    ///
    /// ```
    /// #![allow(dead_code)]
    /// use hashtree::{HashTree, HashStrategy};
    ///
    /// fn main() {
    ///     let mut data = vec![0u8, 1u8];
    ///     let tree = HashTree::create(
    ///         &mut data.as_slice(),
    ///         HashStrategy::new(1, |x| md5::compute(x))
    ///     );
    /// }
    /// ```
    /// The example above uses a `HashStrategy` that splits the data
    /// into 1-byte blocks and computes their MD5 digests for the
    /// `HashTree`.
    pub fn create<R>(data: &mut R, strategy: HashStrategy<T, F>) -> Result<Self>
    where 
        R: Read,
    {
        let mut buf = vec![0u8; strategy.block_size];
        let mut nodes = VecDeque::<NodePtr<T>>::new();
        let mut block_num = 0;

        let mut done = false;
        while !done {
            let bytes_read = data.read(&mut buf)?;

            if bytes_read < strategy.block_size {
                done = true;
            }

            let hash = (strategy.hash_function)(&buf);
            let node = Box::new(HashTreeNode::new(hash));
            nodes.push_back(node);

            block_num += 1; 
        }

        let mut hashtree = HashTree::<T, F>{
            root: None,
            num_nodes: nodes.len(),
            num_blocks: block_num,
            strategy,
        };

        hashtree.build(nodes);
        Ok(hashtree)
    }

    fn build(&mut self, mut nodes: VecDeque<NodePtr<T>>) {
        let nodes_to_process = nodes.len();
        if nodes_to_process == 1 {
            self.root = nodes.pop_front();
            return;
        }

        let mut parents = VecDeque::<NodePtr<T>>::new();
        let mut processed = 0;
        while processed < nodes_to_process {
            let n1 = nodes.pop_front().unwrap();
            let n2 = nodes.pop_front().unwrap_or(n1.clone());

            let merged_hash = format!("{:?}{:?}", n1.hash(), n2.hash());
            let parent_hash = (self.strategy.hash_function)(merged_hash.as_bytes());

            let mut parent = Box::new(HashTreeNode::new(parent_hash));
            parent.left = Some(n1);
            parent.right = Some(n2);

            parents.push_back(parent);
            processed += 2;
            self.num_nodes += 1;
        }

        return self.build(parents);
    }

    // TODO: Implement ability to add data manually and reconstruct HashTree on the fly 
    pub fn insert<R>(&mut self, data: &mut R) 
    where 
        R: Read
    {
        unimplemented!();
    }

    /// Recomputes the hashes and nodes of the `HashTree`. This method should be called
    /// after you are done manually inserting data via the `insert` method.
    pub fn update(&mut self) {
        unimplemented!();
    }

    /// Returns `true` if the `HashTree` is empty and `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// #![allow(dead_code)]
    /// use hashtree::{HashTree, HashStrategy};
    /// 
    /// const BLOCK_SIZE: usize = 4096;
    ///
    /// fn main() {
    ///     let tree = HashTree::new(
    ///         HashStrategy::new(BLOCK_SIZE, |data| {
    ///             md5::compute(data)
    ///         })
    ///     );
    ///
    ///     assert_eq!(tree.is_empty(), true);
    /// }
    /// ```
    pub fn is_empty(&self) -> bool {
        if let Some(_) = self.root {
            return false
        }
        true
    }

    /// Returns the root of the `HashTree` as an `Option<&Box<HashTreeNode<T>>>`.
    pub fn root(&self) -> Option<&HashTreeNode<T>> {
        if let Some(ref root) = self.root {
            return Some(root)
        }
        None
    }

    pub fn find(&self, hash: T) -> Option<&HashTreeNode<T>> {
        if let Some(ref root) = self.root {
            return Some(root)
        }
        None
    }

    /// Returns the number of nodes in the `HashTree`.
    pub fn nodes(&self) -> usize {
        self.num_nodes
    }

    /// Returns the number of blocks that were used to construct the `HashTree`.
    pub fn blocks(&self) -> usize {
        self.num_blocks
    }
}

impl<T, F> PartialEq for HashTree<T, F> 
where 
    T: Debug + Clone + PartialEq,
    F: Fn(&[u8]) -> T,
{
    fn eq(&self, other: &Self) -> bool {
        if let Some(root) = &self.root {
            if let Some(other_root) = &other.root {
                return root.hash == other_root.hash
            }
        }
        false
    }
}

/*
#[cfg(test)]
mod tests {
    use crate::{HashTree, HashStrategy};

    #[test]
    fn it_works() {
        let data = vec![0u8; 4096];
        if let Ok(tree) = HashTree::create(
            &mut data.as_slice(),
            HashStrategy::new(1024, |x| {
                md5::compute(x)
            })
        ) {
            let root = tree.root().unwrap();
            root.print_preorder();
            root.print_inorder();
            root.print_postorder();
        }
    }
}
*/