arnaucube
arnaucube/go-merkletree-oldPublic Self-hosted repository
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
38	path := []bool{}
39	for bitno := numLevels - 2; bitno >= 0; bitno-- {
40		path = append(path, testbitmap(hi[:], uint(bitno)))
41	}
42	return path
43}
44
45func comparePaths(b1 []bool, b2 []bool) int {
46	for i := len(b1) - 1; i >= 0; i-- {
47		if b1[i] != b2[i] {
48			return i
49		}
50	}
51	return -1
52}
53
54func getEmptiesBetweenIAndPosHash(mt *MerkleTree, iPos int, posHash int) []Hash {
55	var sibl []Hash
56	for i := iPos; i >= posHash; i-- {
57		sibl = append(sibl, EmptyNodeValue)
58	}
59	return sibl
60}
61
62func setbitmap(bitmap []byte, bitno uint) {
63	bitmap[uint(len(bitmap))-bitno/8-1] |= 1 << (bitno % 8)
64}
65func testbitmap(bitmap []byte, bitno uint) bool {
66	return bitmap[uint(len(bitmap))-bitno/8-1]&(1<<(bitno%8)) > 0
67}
68
69// Uint32ToBytes returns a byte array from a uint32
70func Uint32ToBytes(u uint32) []byte {
71	buff := new(bytes.Buffer)
72	err := binary.Write(buff, binary.LittleEndian, u)
73	if err != nil {
74		panic(err)
75	}
76	return buff.Bytes()
77}
78
79// BytesToUint32 returns a uint32 from a byte array
80func BytesToUint32(b []byte) uint32 {
81	return binary.LittleEndian.Uint32(b)
82}
83
84// BytesToHex encodes an array of bytes into a string in hex.
85func BytesToHex(bs []byte) string {
86	return fmt.Sprintf("0x%s", hex.EncodeToString(bs))
87}
88
89// HexToBytes decodes a hex string into an array of bytes.
90func HexToBytes(h string) ([]byte, error) {
91	if strings.HasPrefix(h, "0x") {
92		h = h[2:]
93	}
94	return hex.DecodeString(h)
95}