A simple Merkle tree implementation.
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"
-
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
-
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
-
Verify the proof with IsProofValid:
if IsProofValid(tests[2], proof, mt.Root.Hash) == false { fmt.Println("failed to verify") }