arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/utils.go
common/utils.goRaw
 1package common
 2
 3import (
 4	"bytes"
 5	"encoding/hex"
 6	"math/big"
 7
 8	ethCommon "github.com/ethereum/go-ethereum/common"
 9	"github.com/hermeznetwork/tracerr"
10	"github.com/iden3/go-iden3-crypto/babyjub"
11	"github.com/iden3/go-merkletree"
12)
13
14// SwapEndianness swaps the order of the bytes in the slice.
15func SwapEndianness(b []byte) []byte {
16	o := make([]byte, len(b))
17	for i := range b {
18		o[len(b)-1-i] = b[i]
19	}
20	return o
21}
22
23// EthAddrToBigInt returns a *big.Int from a given ethereum common.Address.
24func EthAddrToBigInt(a ethCommon.Address) *big.Int {
25	return new(big.Int).SetBytes(a.Bytes())
26}
27
28// BJJFromStringWithChecksum parses a hex string in Hermez format (which has
29// the Hermez checksum at the last byte, and is encoded in BigEndian) and
30// returns the corresponding *babyjub.PublicKey. This method is not part of the
31// spec, is used for importing javascript test vectors data.
32func BJJFromStringWithChecksum(s string) (babyjub.PublicKeyComp, error) {
33	b, err := hex.DecodeString(s)
34	if err != nil {
35		return EmptyBJJComp, tracerr.Wrap(err)
36	}
37	pkBytes := SwapEndianness(b)
38	var pkComp babyjub.PublicKeyComp
39	copy(pkComp[:], pkBytes[:])
40	return pkComp, nil
41}
42
43// CopyBigInt returns a copy of the big int
44func CopyBigInt(a *big.Int) *big.Int {
45	return new(big.Int).SetBytes(a.Bytes())
46}
47
48// RmEndingZeroes is used to convert the Siblings from a CircomProof into
49// Siblings of a merkletree Proof compatible with the js version. This method
50// should be used only if it exist an already generated CircomProof compatible
51// with circom circuits and a CircomProof compatible with SmartContracts is
52// needed. If the proof is not generated yet, this method should not be needed
53// and should be used mt.GenerateSCVerifierProof to directly generate the
54// CircomProof for the SmartContracts.
55func RmEndingZeroes(siblings []*merkletree.Hash) []*merkletree.Hash {
56	pos := 0
57	for i := len(siblings) - 1; i >= 0; i-- {
58		if !bytes.Equal(siblings[i].Bytes(), merkletree.HashZero.Bytes()) {
59			pos = i + 1
60			break
61		}
62	}
63	return siblings[:pos]
64}