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.

94 lines
2.0 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. package merkletree
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "fmt"
  7. "strings"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. )
  10. // Hex returns a hex string from the Hash type
  11. func (hash Hash) Hex() string {
  12. r := "0x"
  13. h := hex.EncodeToString(hash[:])
  14. r = r + h
  15. return r
  16. }
  17. // Bytes returns a byte array from a Hash
  18. func (hash Hash) Bytes() []byte {
  19. return hash[:]
  20. }
  21. // HashBytes performs a Keccak256 hash over the bytes
  22. func HashBytes(b []byte) (hash Hash) {
  23. h := crypto.Keccak256(b)
  24. copy(hash[:], h)
  25. // if instead of Keccak256 want to use SHA256:
  26. // hash = sha256.Sum256(b)
  27. return hash
  28. }
  29. // getPath returns the binary path, from the leaf to the root
  30. func getPath(numLevels int, hi Hash) []bool {
  31. path := []bool{}
  32. for bitno := numLevels - 2; bitno >= 0; bitno-- {
  33. path = append(path, testbitmap(hi[:], uint(bitno)))
  34. }
  35. return path
  36. }
  37. func comparePaths(b1 []bool, b2 []bool) int {
  38. for i := len(b1) - 1; i >= 0; i-- {
  39. if b1[i] != b2[i] {
  40. return i
  41. }
  42. }
  43. return -1
  44. }
  45. func getEmptiesBetweenIAndPosHash(mt *MerkleTree, iPos int, posHash int) []Hash {
  46. var sibl []Hash
  47. for i := iPos; i >= posHash; i-- {
  48. sibl = append(sibl, EmptyNodeValue)
  49. }
  50. return sibl
  51. }
  52. func setbitmap(bitmap []byte, bitno uint) {
  53. bitmap[uint(len(bitmap))-bitno/8-1] |= 1 << (bitno % 8)
  54. }
  55. func testbitmap(bitmap []byte, bitno uint) bool {
  56. return bitmap[uint(len(bitmap))-bitno/8-1]&(1<<(bitno%8)) > 0
  57. }
  58. // Uint32ToBytes returns a byte array from a uint32
  59. func Uint32ToBytes(u uint32) []byte {
  60. buff := new(bytes.Buffer)
  61. err := binary.Write(buff, binary.LittleEndian, u)
  62. if err != nil {
  63. panic(err)
  64. }
  65. return buff.Bytes()
  66. }
  67. // BytesToUint32 returns a uint32 from a byte array
  68. func BytesToUint32(b []byte) uint32 {
  69. return binary.LittleEndian.Uint32(b)
  70. }
  71. // BytesToHex encodes an array of bytes into a string in hex.
  72. func BytesToHex(bs []byte) string {
  73. return fmt.Sprintf("0x%s", hex.EncodeToString(bs))
  74. }
  75. // HexToBytes decodes a hex string into an array of bytes.
  76. func HexToBytes(h string) ([]byte, error) {
  77. if strings.HasPrefix(h, "0x") {
  78. h = h[2:]
  79. }
  80. return hex.DecodeString(h)
  81. }