Merkle Tree in Golang
An implementation of a Merkle Tree written in Go. A Merkle Tree is a hash tree that provides an efficient way to verify
the contents of a set data are present and untampered with.
At its core, a Merkle Tree is a list of items representing the data that should be verified. Each of these items
is inserted into a leaf node and a tree of hashes is constructed bottom up using a hash of the nodes left and
right children's hashes. This means that the root node will effictively be a hash of all other nodes (hashes) in
the tree. This property allows the tree to be reproduced and thus verified by on the hash of the root node
of the tree. The benefit of the tree structure is verifying any single content entry in the tree will require only
nlog2(n) steps in the worst case.
Documentation
See the docs here.
Install
go get github.com/plateausnetwork/merkletree@master
Example Usage
Below is an example that makes use of the entire API - its quite small.
package main
import (
"log"
"golang.org/x/crypto/sha3"
"github.com/plateausnetwork/merkletree"
)
type TestContent struct {
x string
}
func (t TestContent) CalculateHash() ([]byte, error) {
h := sha3.New256()
if _, err := h.Write([]byte(t.x)); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
func (t TestContent) Equals(other merkletree.Content) (bool, error) {
return t.x == other.(TestContent).x, nil
}
func main() {
var list []merkletree.Content
list = append(list, TestContent{x: "Hello"})
list = append(list, TestContent{x: "Hi"})
list = append(list, TestContent{x: "Hey"})
list = append(list, TestContent{x: "Hola"})
t, err := merkletree.NewTree(list)
if err != nil {
log.Fatal(err)
}
mr := t.MerkleRoot()
log.Println(mr)
vt, err := t.VerifyTree()
if err != nil {
log.Fatal(err)
}
log.Println("Verify Tree: ", vt)
vc, err := t.VerifyContent(list[0])
if err != nil {
log.Fatal(err)
}
log.Println("Verify Content: ", vc)
log.Println(t)
}
Sample
License
This project is licensed under the MIT License.