You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.2 KiB

  1. /*
  2. Computes a deterministic minimal height merkle tree hash.
  3. If the number of items is not a power of two, some leaves
  4. will be at different levels. Tries to keep both sides of
  5. the tree the same size, but the left may be one greater.
  6. Use this for short deterministic trees, such as the validator list.
  7. For larger datasets, use IAVLTree.
  8. *
  9. / \
  10. / \
  11. / \
  12. / \
  13. * *
  14. / \ / \
  15. / \ / \
  16. / \ / \
  17. * * * h6
  18. / \ / \ / \
  19. h0 h1 h2 h3 h4 h5
  20. */
  21. package merkle
  22. import (
  23. "golang.org/x/crypto/ripemd160"
  24. "github.com/tendermint/go-wire"
  25. )
  26. func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
  27. var hasher = ripemd160.New()
  28. err := wire.EncodeByteSlice(hasher, left)
  29. err = wire.EncodeByteSlice(hasher, right)
  30. if err != nil {
  31. panic(err)
  32. }
  33. return hasher.Sum(nil)
  34. }
  35. func SimpleHashFromHashes(hashes [][]byte) []byte {
  36. // Recursive impl.
  37. switch len(hashes) {
  38. case 0:
  39. return nil
  40. case 1:
  41. return hashes[0]
  42. default:
  43. left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2])
  44. right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:])
  45. return SimpleHashFromTwoHashes(left, right)
  46. }
  47. }
  48. // NOTE: Do not implement this, use SimpleHashFromByteslices instead.
  49. // type Byteser interface { Bytes() []byte }
  50. // func SimpleHashFromBytesers(items []Byteser) []byte { ... }
  51. func SimpleHashFromByteslices(bzs [][]byte) []byte {
  52. hashes := make([][]byte, len(bzs))
  53. for i, bz := range bzs {
  54. hashes[i] = SimpleHashFromBytes(bz)
  55. }
  56. return SimpleHashFromHashes(hashes)
  57. }
  58. func SimpleHashFromBytes(bz []byte) []byte {
  59. hasher := ripemd160.New()
  60. hasher.Write(bz)
  61. return hasher.Sum(nil)
  62. }
  63. func SimpleHashFromHashers(items []Hasher) []byte {
  64. hashes := make([][]byte, len(items))
  65. for i, item := range items {
  66. hash := item.Hash()
  67. hashes[i] = hash
  68. }
  69. return SimpleHashFromHashes(hashes)
  70. }
  71. func SimpleHashFromMap(m map[string]Hasher) []byte {
  72. sm := NewSimpleMap()
  73. for k, v := range m {
  74. sm.Set(k, v)
  75. }
  76. return sm.Hash()
  77. }