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