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
999 B

  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. func getSplitPoint(length int) int {
  32. if length < 1 {
  33. panic("Trying to split a tree with size < 1")
  34. }
  35. uLength := uint(length)
  36. bitlen := bits.Len(uLength)
  37. k := 1 << uint(bitlen-1)
  38. if k == length {
  39. k >>= 1
  40. }
  41. return k
  42. }