go-merkletree-iden3/utils.go
utils.goRaw
1package merkletree
2
3import (
4 "math/big"
5
6 "github.com/iden3/go-iden3-crypto/poseidon"
7)
8
9// HashElems performs a poseidon hash over the array of ElemBytes, currently we
10// are using 2 elements. Uses poseidon.Hash to be compatible with the circom
11// circuits implementations.
12func HashElems(elems ...*big.Int) (*Hash, error) {
13 poseidonHash, err := poseidon.Hash(elems)
14 if err != nil {
15 return nil, err
16 }
17 return NewHashFromBigInt(poseidonHash), nil
18}
19
20// HashElemsKey performs a poseidon hash over the array of ElemBytes, currently
21// we are using 2 elements.
22func HashElemsKey(key *big.Int, elems ...*big.Int) (*Hash, error) {
23 if key == nil {
24 key = new(big.Int).SetInt64(0)
25 }
26 bi := make([]*big.Int, 3)
27 copy(bi[:], elems)
28 bi[2] = key
29 poseidonHash, err := poseidon.Hash(bi)
30 if err != nil {
31 return nil, err
32 }
33 return NewHashFromBigInt(poseidonHash), nil
34}
35
36// SetBitBigEndian sets the bit n in the bitmap to 1, in Big Endian.
37func SetBitBigEndian(bitmap []byte, n uint) {
38 bitmap[uint(len(bitmap))-n/8-1] |= 1 << (n % 8)
39}
40
41// TestBit tests whether the bit n in bitmap is 1.
42func TestBit(bitmap []byte, n uint) bool {
43 return bitmap[n/8]&(1<<(n%8)) != 0
44}
45
46// TestBitBigEndian tests whether the bit n in bitmap is 1, in Big Endian.
47func TestBitBigEndian(bitmap []byte, n uint) bool {
48 return bitmap[uint(len(bitmap))-n/8-1]&(1<<(n%8)) != 0
49}
50
51// SwapEndianness swaps the order of the bytes in the slice.
52func SwapEndianness(b []byte) []byte {
53 o := make([]byte, len(b))
54 for i := range b {
55 o[len(b)-1-i] = b[i]
56 }
57 return o
58}