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
//! Merkle Tree to calculate Root.
//! Suppert Two Way:
//! One is traditional use MerkleTree, it need send all hashed list.
//! Two is efficient, but need to save state, like state machine. it
//! need send new value, it will return the lastest root.
//! Example:
//! ```rust
//! use rcmerkle::{BetterMerkleTreeSHA256, Hash, MerkleTreeSHA256, SHA256};
//!
//! let list = [
//!    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
//! ];
//! let hashed_list: Vec<SHA256> = list.iter().map(|v| SHA256::hash(v.as_bytes())).collect();
//! let mut better_merkle = BetterMerkleTreeSHA256::new();
//!
//! for i in 0..hashed_list.len() {
//!    let root1 = MerkleTreeSHA256::root(hashed_list[0..i + 1].to_vec());
//!    let root2 = better_merkle.root(hashed_list[i].clone());
//!    assert_eq!(root1, root2);
//! }
//! ```

use sha2::Sha256;
use sha3::{Digest, Sha3_256};
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::marker::PhantomData;

/// trait to define different hash function
pub trait Hash: Default + Clone + Eq + PartialEq {
    fn hash(data: &[u8]) -> Self;

    fn to_string(hash: &Self) -> String;
}

/// Traditional merkle tree.
pub struct MerkleTree<H: Hash>(PhantomData<H>);

/// Efficient, and save state.
pub struct BetterMerkleTree<H: Hash>(Vec<H>, H);

impl<H: Hash> MerkleTree<H> {
    /// Recursive calculation.
    fn merkle(mut vec: Vec<H>) -> Vec<H> {
        let vec_len = vec.len();
        if vec_len == 1 {
            return vec;
        }

        let mut next = vec![];
        let (mut r, m) = (vec_len / 2, vec_len % 2);
        if m == 1 {
            let last = vec[vec_len - 1].clone();
            vec.push(last);
            r += 1;
        }

        for i in 0..r {
            let mut s1 = H::to_string(&vec[i * 2]);
            s1.push_str(&H::to_string(&vec[i * 2 + 1]));
            next.push(H::hash(s1.as_bytes()))
        }

        MerkleTree::merkle(next)
    }

    /// new a MerkleTree, but use.
    pub fn new() -> Self {
        MerkleTree(Default::default())
    }

    /// Entrance, inpurt your list. and return merkle root.
    pub fn root(hashes: Vec<H>) -> H {
        if hashes.len() == 0 {
            return Default::default();
        }

        MerkleTree::merkle(hashes).remove(0)
    }
}

impl<H: Hash> BetterMerkleTree<H> {
    /// Recursive calculation.
    fn merkle(&mut self, new: H, is_full: bool, round: usize) -> H {
        let mut next_full = false;

        if self.0.len() <= round {
            let mut need_append = true;
            for i in self.0.iter() {
                if i != &H::default() {
                    need_append = false;
                }
            }
            if need_append {
                self.0.push(new.clone())
            }

            return new;
        }

        let next = if self.0[round] != H::default() {
            let mut s1 = H::to_string(&self.0[round]);
            s1.push_str(&H::to_string(&new));

            if is_full {
                self.0[round] = H::default();
                next_full = true;
            }

            H::hash(s1.as_bytes())
        } else {
            let mut s1 = H::to_string(&new);
            s1.push_str(&s1.clone());

            if is_full {
                self.0[round] = new;
            }

            H::hash(s1.as_bytes())
        };

        self.merkle(next, next_full, round + 1)
    }

    /// when start, you need new this state machine.
    pub fn new() -> Self {
        BetterMerkleTree(vec![], Default::default())
    }

    /// load the state machine.
    pub fn load(vec: Vec<H>) -> Self {
        BetterMerkleTree(vec, Default::default())
    }

    /// output the state machine status.
    pub fn helper(&self) -> &Vec<H> {
        &self.0
    }

    /// get now root.
    pub fn now(&self) -> &H {
        &self.1
    }

    /// Entrance, when new input to this machine.
    pub fn root(&mut self, new: H) -> H {
        let hash = self.merkle(new, true, 0);
        self.1 = hash.clone();
        hash
    }
}

/// helper SHA256
#[derive(Default, Clone, Eq, PartialEq)]
pub struct SHA256([u8; 32]);

impl Hash for SHA256 {
    fn hash(data: &[u8]) -> Self {
        let mut h: SHA256 = Default::default();
        let mut hasher = Sha256::new();
        hasher.input(data);
        h.0.copy_from_slice(&hasher.result()[..]);
        h
    }

    fn to_string(hash: &Self) -> String {
        format!("{}", hash)
    }
}

impl Display for SHA256 {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let mut hex = String::new();
        hex.extend(self.0.iter().map(|byte| format!("{:02x?}", byte)));
        write!(f, "0x{}", hex)
    }
}

impl Debug for SHA256 {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let mut hex = String::new();
        hex.extend(self.0.iter().map(|byte| format!("{:02x?}", byte)));
        write!(f, "0x{}", hex)
    }
}

/// helper Keccak256(SHA3)
#[derive(Default, Clone, Eq, PartialEq)]
pub struct Keccak256([u8; 32]);

impl Hash for Keccak256 {
    fn hash(data: &[u8]) -> Self {
        let mut h: Keccak256 = Default::default();
        let mut hasher = Sha3_256::new();
        hasher.input(data);
        h.0.copy_from_slice(&hasher.result()[..]);
        h
    }

    fn to_string(hash: &Self) -> String {
        format!("{}", hash)
    }
}

impl Display for Keccak256 {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let mut hex = String::new();
        hex.extend(self.0.iter().map(|byte| format!("{:02x?}", byte)));
        write!(f, "0x{}", hex)
    }
}

impl Debug for Keccak256 {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let mut hex = String::new();
        hex.extend(self.0.iter().map(|byte| format!("{:02x?}", byte)));
        write!(f, "0x{}", hex)
    }
}

pub type MerkleTreeSHA256 = MerkleTree<SHA256>;
pub type BetterMerkleTreeSHA256 = BetterMerkleTree<SHA256>;

pub type MerkleTreeKeccak256 = MerkleTree<Keccak256>;
pub type BetterMerkleTreeKeccak256 = BetterMerkleTree<Keccak256>;

#[cfg(test)]
mod tests {
    use super::{
        BetterMerkleTreeKeccak256, BetterMerkleTreeSHA256, Hash, Keccak256, MerkleTreeKeccak256,
        MerkleTreeSHA256, SHA256,
    };

    #[test]
    fn test_sha256() {
        let list = [
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        ];
        let hashed_list: Vec<SHA256> = list.iter().map(|v| SHA256::hash(v.as_bytes())).collect();
        let mut better_merkle = BetterMerkleTreeSHA256::new();

        for i in 0..hashed_list.len() {
            let root1 = MerkleTreeSHA256::root(hashed_list[0..i + 1].to_vec());
            let root2 = better_merkle.root(hashed_list[i].clone());
            assert_eq!(root1, root2);
        }
    }

    #[test]
    fn test_keccak() {
        let list = [
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        ];
        let hashed_list: Vec<Keccak256> =
            list.iter().map(|v| Keccak256::hash(v.as_bytes())).collect();
        let mut better_merkle = BetterMerkleTreeKeccak256::new();

        for i in 0..hashed_list.len() {
            let root1 = MerkleTreeKeccak256::root(hashed_list[0..i + 1].to_vec());
            let root2 = better_merkle.root(hashed_list[i].clone());
            assert_eq!(root1, root2);
        }
    }
}