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.

61 lines
1.3 KiB

5 years ago
  1. package merkletree
  2. import (
  3. "encoding/hex"
  4. "github.com/ethereum/go-ethereum/crypto"
  5. )
  6. // Hex returns a hex string from the Hash type
  7. func (hash Hash) Hex() string {
  8. r := "0x"
  9. h := hex.EncodeToString(hash[:])
  10. r = r + h
  11. return r
  12. }
  13. // Bytes returns a byte array from a Hash
  14. func (hash Hash) Bytes() []byte {
  15. return hash[:]
  16. }
  17. // HashBytes performs a Keccak256 hash over the bytes
  18. func HashBytes(b []byte) (hash Hash) {
  19. h := crypto.Keccak256(b)
  20. copy(hash[:], h)
  21. return hash
  22. }
  23. // getPath returns the binary path, from the leaf to the root
  24. func getPath(numLevels int, hi Hash) []bool {
  25. path := []bool{}
  26. for bitno := numLevels - 2; bitno >= 0; bitno-- {
  27. path = append(path, testbitmap(hi[:], uint(bitno)))
  28. }
  29. return path
  30. }
  31. func comparePaths(b1 []bool, b2 []bool) int {
  32. for i := len(b1) - 1; i >= 0; i-- {
  33. if b1[i] != b2[i] {
  34. return i
  35. }
  36. }
  37. return -1
  38. }
  39. func getEmptiesBetweenIAndPosHash(mt *MerkleTree, iPos int, posHash int) []Hash {
  40. var sibl []Hash
  41. for i := iPos; i >= posHash; i-- {
  42. sibl = append(sibl, EmptyNodeValue)
  43. }
  44. return sibl
  45. }
  46. func setbitmap(bitmap []byte, bitno uint) {
  47. bitmap[uint(len(bitmap))-bitno/8-1] |= 1 << (bitno % 8)
  48. }
  49. func testbitmap(bitmap []byte, bitno uint) bool {
  50. return bitmap[uint(len(bitmap))-bitno/8-1]&(1<<(bitno%8)) > 0
  51. }