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.

58 lines
1.4 KiB

7 years ago
7 years ago
  1. package merkle
  2. import (
  3. "github.com/tendermint/go-crypto/tmhash"
  4. )
  5. // SimpleHashFromTwoHashes is the basic operation of the Merkle tree: Hash(left | right).
  6. func SimpleHashFromTwoHashes(left, right []byte) []byte {
  7. var hasher = tmhash.New()
  8. err := encodeByteSlice(hasher, left)
  9. if err != nil {
  10. panic(err)
  11. }
  12. err = encodeByteSlice(hasher, right)
  13. if err != nil {
  14. panic(err)
  15. }
  16. return hasher.Sum(nil)
  17. }
  18. // SimpleHashFromHashers computes a Merkle tree from items that can be hashed.
  19. func SimpleHashFromHashers(items []Hasher) []byte {
  20. hashes := make([][]byte, len(items))
  21. for i, item := range items {
  22. hash := item.Hash()
  23. hashes[i] = hash
  24. }
  25. return simpleHashFromHashes(hashes)
  26. }
  27. // SimpleHashFromMap computes a Merkle tree from sorted map.
  28. // Like calling SimpleHashFromHashers with
  29. // `item = []byte(Hash(key) | Hash(value))`,
  30. // sorted by `item`.
  31. func SimpleHashFromMap(m map[string]Hasher) []byte {
  32. sm := newSimpleMap()
  33. for k, v := range m {
  34. sm.Set(k, v)
  35. }
  36. return sm.Hash()
  37. }
  38. //----------------------------------------------------------------
  39. // Expects hashes!
  40. func simpleHashFromHashes(hashes [][]byte) []byte {
  41. // Recursive impl.
  42. switch len(hashes) {
  43. case 0:
  44. return nil
  45. case 1:
  46. return hashes[0]
  47. default:
  48. left := simpleHashFromHashes(hashes[:(len(hashes)+1)/2])
  49. right := simpleHashFromHashes(hashes[(len(hashes)+1)/2:])
  50. return SimpleHashFromTwoHashes(left, right)
  51. }
  52. }