arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/account.go
common/account.goRaw
  1package common
  2
  3import (
  4	"bytes"
  5	"encoding/binary"
  6	"fmt"
  7	"math/big"
  8
  9	ethCommon "github.com/ethereum/go-ethereum/common"
 10	"github.com/iden3/go-iden3-crypto/babyjub"
 11	"github.com/iden3/go-iden3-crypto/poseidon"
 12	cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
 13)
 14
 15const (
 16	// NLEAFELEMS is the number of elements for a leaf
 17	NLEAFELEMS = 4
 18	// maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
 19	maxNonceValue = 0xffffffffff
 20	// maxBalanceBytes is the maximum bytes that can use the Account.Balance *big.Int
 21	maxBalanceBytes = 24
 22)
 23
 24// Account is a struct that gives information of the holdings of an address and a specific token. Is the data structure that generates the Value stored in the leaf of the MerkleTree
 25type Account struct {
 26	TokenID   TokenID
 27	Nonce     Nonce    // max of 40 bits used
 28	Balance   *big.Int // max of 192 bits used
 29	PublicKey *babyjub.PublicKey
 30	EthAddr   ethCommon.Address
 31}
 32
 33func (a *Account) String() string {
 34	buf := bytes.NewBufferString("")
 35	fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
 36	fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
 37	fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
 38	fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
 39	fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
 40	return buf.String()
 41}
 42
 43// Bytes returns the bytes representing the Account, in a way that each BigInt is represented by 32 bytes, in spite of the BigInt could be represented in less bytes (due a small big.Int), so in this way each BigInt is always 32 bytes and can be automatically parsed from a byte array.
 44func (a *Account) Bytes() ([32 * NLEAFELEMS]byte, error) {
 45	var b [32 * NLEAFELEMS]byte
 46
 47	if a.Nonce > maxNonceValue {
 48		return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
 49	}
 50	if len(a.Balance.Bytes()) > maxBalanceBytes {
 51		return b, fmt.Errorf("%s Balance", ErrNumOverflow)
 52	}
 53
 54	nonceBytes, err := a.Nonce.Bytes()
 55	if err != nil {
 56		return b, err
 57	}
 58
 59	copy(b[0:4], a.TokenID.Bytes())
 60	copy(b[4:9], nonceBytes[:])
 61	if babyjub.PointCoordSign(a.PublicKey.X) {
 62		b[10] = 1
 63	}
 64	copy(b[32:64], SwapEndianness(a.Balance.Bytes())) // SwapEndianness, as big.Int uses BigEndian
 65	copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
 66	copy(b[96:116], a.EthAddr.Bytes())
 67
 68	return b, nil
 69}
 70
 71// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
 72func (a *Account) BigInts() ([NLEAFELEMS]*big.Int, error) {
 73	e := [NLEAFELEMS]*big.Int{}
 74
 75	b, err := a.Bytes()
 76	if err != nil {
 77		return e, err
 78	}
 79
 80	e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
 81	e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
 82	e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
 83	e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
 84
 85	return e, nil
 86}
 87
 88// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
 89func (a *Account) HashValue() (*big.Int, error) {
 90	b0 := big.NewInt(0)
 91	toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
 92	lBI, err := a.BigInts()
 93	if err != nil {
 94		return nil, err
 95	}
 96	copy(toHash[:], lBI[:])
 97
 98	v, err := poseidon.Hash(toHash)
 99	return v, err
100}
101
102// AccountFromBigInts returns a Account from a [5]*big.Int
103func AccountFromBigInts(e [NLEAFELEMS]*big.Int) (*Account, error) {
104	if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
105		return nil, ErrNotInFF
106	}
107	var b [32 * NLEAFELEMS]byte
108	copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
109	copy(b[32:64], SwapEndianness(e[1].Bytes()))
110	copy(b[64:96], SwapEndianness(e[2].Bytes()))
111	copy(b[96:128], SwapEndianness(e[3].Bytes()))
112
113	return AccountFromBytes(b)
114}
115
116// AccountFromBytes returns a Account from a byte array
117func AccountFromBytes(b [32 * NLEAFELEMS]byte) (*Account, error) {
118	tokenID := binary.LittleEndian.Uint32(b[0:4])
119	var nonceBytes5 [5]byte
120	copy(nonceBytes5[:], b[4:9])
121	nonce := NonceFromBytes(nonceBytes5)
122	sign := b[10] == 1
123	balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
124	if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
125		return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
126	}
127	ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
128	pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
129	if err != nil {
130		return nil, err
131	}
132	publicKey := babyjub.PublicKey(*pkPoint)
133	ethAddr := ethCommon.BytesToAddress(b[96:116])
134
135	if !cryptoUtils.CheckBigIntInField(balance) {
136		return nil, ErrNotInFF
137	}
138	if !cryptoUtils.CheckBigIntInField(ay) {
139		return nil, ErrNotInFF
140	}
141
142	a := Account{
143		TokenID:   TokenID(tokenID),
144		Nonce:     nonce,
145		Balance:   balance,
146		PublicKey: &publicKey,
147		EthAddr:   ethAddr,
148	}
149	return &a, nil
150}