项目作者: wilfreddenton

项目描述 :
A Merkle Tree implementation in Go
高级语言: Go
项目地址: git://github.com/wilfreddenton/merkle.git
创建时间: 2017-05-15T03:31:03Z
项目社区:https://github.com/wilfreddenton/merkle

开源协议:

下载


merkle


Build Status
codecov

Hash Tree.svg
By Azaghal - Own work, CC0, Link

Usage

  1. package main
  2. import (
  3. "crypto/sha256"
  4. "log"
  5. "os"
  6. "github.com/wilfreddenton/merkle"
  7. )
  8. func main() {
  9. // create a hash function
  10. // it's ok to resuse this in merkle calls because it will be reset after use
  11. h := sha256.New()
  12. // create an io.Reader
  13. f, err := os.Open("main.go")
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. // shard the file into segments (1024 byte sized segments in this case)
  18. preLeaves, err := merkle.Shard(f, 1024)
  19. if err != nil {
  20. log.Fatal(err)
  21. }
  22. // initialize the tree
  23. t := merkle.NewTree()
  24. // compute the root hash from the pre-leaves using the sha256 hash function
  25. err = t.Hash(preLeaves, h)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. // use the LeafHash function to convert a pre-leaf into a leaf
  30. leaf := merkle.LeafHash(preLeaves[0], h)
  31. // create the merkle path for the leaf
  32. path := t.MerklePath(leaf)
  33. if path == nil {
  34. log.Fatalf("tree does not contain %x", leaf)
  35. }
  36. // prove with the path that the tree contains the leaf
  37. if !merkle.Prove(leaf, t.Root(), path, h) {
  38. log.Fatalf("tree should container %x", leaf)
  39. }
  40. }

References

Tree Hash EXchange format (THEX): This site covers a lot of the implementation details of Merkle Trees.

Storj Whitepaper: Storj is a P2P cloud storage network. The whitepaper details their usage of the Merkle Tree datastructure for validating file shards.

Mastering Bitcoin - Unlocking Digital Currencies: Chapter 7 - The Blockchain | Merkle Trees

Blockchain header: Merkle roots and SPV transaction verification: A great youtube video by Matt Thomas explaining in depth how Merkle Trees are used in the bitcoin blockchain.