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