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.

47 lines
1.0 KiB

  1. package merkle
  2. import (
  3. "math/bits"
  4. )
  5. // SimpleHashFromByteSlices computes a Merkle tree where the leaves are the byte slice,
  6. // in the provided order.
  7. func SimpleHashFromByteSlices(items [][]byte) []byte {
  8. switch len(items) {
  9. case 0:
  10. return nil
  11. case 1:
  12. return leafHash(items[0])
  13. default:
  14. k := getSplitPoint(len(items))
  15. left := SimpleHashFromByteSlices(items[:k])
  16. right := SimpleHashFromByteSlices(items[k:])
  17. return innerHash(left, right)
  18. }
  19. }
  20. // SimpleHashFromMap computes a Merkle tree from sorted map.
  21. // Like calling SimpleHashFromHashers with
  22. // `item = []byte(Hash(key) | Hash(value))`,
  23. // sorted by `item`.
  24. func SimpleHashFromMap(m map[string][]byte) []byte {
  25. sm := newSimpleMap()
  26. for k, v := range m {
  27. sm.Set(k, v)
  28. }
  29. return sm.Hash()
  30. }
  31. // getSplitPoint returns the largest power of 2 less than length
  32. func getSplitPoint(length int) int {
  33. if length < 1 {
  34. panic("Trying to split a tree with size < 1")
  35. }
  36. uLength := uint(length)
  37. bitlen := bits.Len(uLength)
  38. k := 1 << uint(bitlen-1)
  39. if k == length {
  40. k >>= 1
  41. }
  42. return k
  43. }