arnaucube
arnaucube/merkletree-rsPublic Self-hosted repository
merkletree-rs/README.md
README.mdRaw
 1# merkletree-rs [![Crates.io](https://img.shields.io/crates/v/merkletree-rs.svg)](https://crates.io/crates/merkletree-rs) [![Build Status](https://travis-ci.org/arnaucube/merkletree-rs.svg?branch=master)](https://travis-ci.org/arnaucube/merkletree-rs)
 2Sparse MerkleTree implementation in Rust.
 3
 4The MerkleTree is optimized in the design and concepts, to have a faster and lighter MerkleTree, maintaining compatibility with a non optimized MerkleTree. In this way, the MerkleRoot of the optimized MerkleTree will be the same that the MerkleRoot of the non optimized MerkleTree.
 5
 6Compatible with the Go version: https://github.com/arnaucube/go-merkletree
 7
 8
 9## Usage
10Import lib:
11```rust
12extern crate merkletree_rs;
13use merkletree_rs::{db, MerkleTree, TestValue, Value};
14```
15
16Create new tree:
17```rust
18// to build the storage, the first parameter is the path and the second parameter specifies if wants to use a in_memory database or a directory of the filesystem
19let mut sto = db::Db::new("test".to_string(), true);
20let mut mt = MerkleTree::new(&mut sto, 140 as u32);
21```
22
23Add value to leaf:
24```rust
25let val: TestValue = TestValue {
26    bytes: "this is a test leaf".as_bytes().to_vec(),
27    index_length: 15,
28};
29mt.add(&val).unwrap();
30```
31
32Get proof:
33```rust
34let mp = mt.generate_proof(val.hi());
35println!("{:?}", mp);
36```
37
38Verify proof:
39```rust
40// check if the value exist
41let v =
42    merkletree_rs::verify_proof(mt.get_root(), &mp, val.hi(), val.ht(), mt.get_num_levels());
43println!("{:?}", v);
44
45// check if the don't value exist (in that case, the 'ht' will be an empty value)
46let v = merkletree_rs::verify_proof(
47    mt.get_root(),
48    &mp,
49    val.hi(),
50    merkletree_rs::constants::EMPTYNODEVALUE,
51    mt.get_num_levels(),
52);
53println!("{:?}", v);
54```
55
56Print current MerkleRoot:
57```rust
58println!("{:?}", mt.get_root());
59```