Skip to content

res-web3/merkletree

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Merkle Tree

GoDoc Go Report Card Build Status

A simple Merkle tree implementation.

Install

Fist, use go get to install the latest version of the library:

go get -u github.com/lynn9388/merkletree

Next, include this package in your application:

import "github.com/lynn9388/merkletree"

Usage

  1. Create a new Merkle tree and print it with PrettyString:

    tests := [][]byte{[]byte("http"), []byte("www"), []byte("lynn"), []byte("9388"), []byte("com")}
    mt := NewMerkleTree(tests...)
    
    fmt.Println("Merkle Tree:\n" + mt.PrettyString(6, 2))
    // Output:
    // Merkle Tree:
    //                 cf5744
    //                   / \
    //                  /   \
    //                 /     \
    //             1b5c1e  71b4f3
    //               / \
    //              /   \
    //             /     \
    //            /       \
    //           /         \
    //          /           \
    //         /             \
    //     4b2099          19ec96
    //       / \             / \
    //      /   \           /   \
    //     /     \         /     \
    // e0603c  7c2ecd  1502fe  6d86b7
  2. Get a proof of hash of data is in the Merkle tree with GetProof:

    proof, _ := mt.GetProof(tests[3])
    
    prettyTree := mt.PrettyString(6, 2)
    for i, p := range proof {
        hash := hex.EncodeToString(p.Hash)[:6]
        prettyTree = strings.Replace(prettyTree, hash, fmt.Sprintf("%v-%v", i, hash[:4]), 1)
    }
    fmt.Println("Proof Path:\n" + prettyTree)
    // Output:
    // Proof Path:
    //                 cf5744
    //                   / \
    //                  /   \
    //                 /     \
    //             1b5c1e  2-71b4
    //               / \
    //              /   \
    //             /     \
    //            /       \
    //           /         \
    //          /           \
    //         /             \
    //     1-4b20          19ec96
    //       / \             / \
    //      /   \           /   \
    //     /     \         /     \
    // e0603c  7c2ecd  0-1502  6d86b7
  3. Verify the proof with IsProofValid:

    if IsProofValid(tests[2], proof, mt.Root.Hash) == false {
        fmt.Println("failed to verify")
    }

About

A simple Merkle tree implementation.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 100.0%