hermez-node/common/utils.go
common/utils.goRaw
1package common
2
3import (
4 "encoding/hex"
5 "math/big"
6
7 ethCommon "github.com/ethereum/go-ethereum/common"
8 "github.com/hermeznetwork/tracerr"
9 "github.com/iden3/go-iden3-crypto/babyjub"
10)
11
12// SwapEndianness swaps the order of the bytes in the slice.
13func SwapEndianness(b []byte) []byte {
14 o := make([]byte, len(b))
15 for i := range b {
16 o[len(b)-1-i] = b[i]
17 }
18 return o
19}
20
21// EthAddrToBigInt returns a *big.Int from a given ethereum common.Address.
22func EthAddrToBigInt(a ethCommon.Address) *big.Int {
23 return new(big.Int).SetBytes(a.Bytes())
24}
25
26// BJJFromStringWithChecksum parses a hex string in Hermez format (which has
27// the Hermez checksum at the last byte, and is encoded in BigEndian) and
28// returns the corresponding *babyjub.PublicKey. This method is not part of the
29// spec, is used for importing javascript test vectors data.
30func BJJFromStringWithChecksum(s string) (babyjub.PublicKeyComp, error) {
31 b, err := hex.DecodeString(s)
32 if err != nil {
33 return EmptyBJJComp, tracerr.Wrap(err)
34 }
35 pkBytes := SwapEndianness(b)
36 var pkComp babyjub.PublicKeyComp
37 copy(pkComp[:], pkBytes[:])
38 return pkComp, nil
39}
40
41// CopyBigInt returns a copy of the big int
42func CopyBigInt(a *big.Int) *big.Int {
43 return new(big.Int).SetBytes(a.Bytes())
44}