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.

46 lines
1.1 KiB

  1. package merkle
  2. import (
  3. "github.com/tendermint/tendermint/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. // SimpleHashFromByteSlices computes a Merkle tree where the leaves are the byte slice,
  19. // in the provided order.
  20. func SimpleHashFromByteSlices(items [][]byte) []byte {
  21. switch len(items) {
  22. case 0:
  23. return nil
  24. case 1:
  25. return tmhash.Sum(items[0])
  26. default:
  27. left := SimpleHashFromByteSlices(items[:(len(items)+1)/2])
  28. right := SimpleHashFromByteSlices(items[(len(items)+1)/2:])
  29. return simpleHashFromTwoHashes(left, right)
  30. }
  31. }
  32. // SimpleHashFromMap computes a Merkle tree from sorted map.
  33. // Like calling SimpleHashFromHashers with
  34. // `item = []byte(Hash(key) | Hash(value))`,
  35. // sorted by `item`.
  36. func SimpleHashFromMap(m map[string][]byte) []byte {
  37. sm := newSimpleMap()
  38. for k, v := range m {
  39. sm.Set(k, v)
  40. }
  41. return sm.Hash()
  42. }