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	"strconv"
  9
 10	ethCommon "github.com/ethereum/go-ethereum/common"
 11	"github.com/iden3/go-iden3-crypto/babyjub"
 12	"github.com/iden3/go-iden3-crypto/poseidon"
 13	cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
 14)
 15
 16const (
 17	// NLeafElems is the number of elements for a leaf
 18	NLeafElems = 4
 19	// maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
 20	maxNonceValue = 0xffffffffff
 21	// maxBalanceBytes is the maximum bytes that can use the Account.Balance *big.Int
 22	maxBalanceBytes = 24
 23
 24	idxBytesLen = 4
 25	// maxIdxValue is the maximum value that Idx can have (32 bits: maxIdxValue=2**32-1)
 26	maxIdxValue = 0xffffffff
 27
 28	// userThreshold determines the threshold from the User Idxs can be
 29	userThreshold = 256
 30	// IdxUserThreshold is a Idx type value that determines the threshold
 31	// from the User Idxs can be
 32	IdxUserThreshold = Idx(userThreshold)
 33)
 34
 35// Idx represents the account Index in the MerkleTree
 36type Idx uint32
 37
 38// String returns a string representation of the Idx
 39func (idx Idx) String() string {
 40	return strconv.Itoa(int(idx))
 41}
 42
 43// Bytes returns a byte array representing the Idx
 44func (idx Idx) Bytes() []byte {
 45	var b [4]byte
 46	binary.BigEndian.PutUint32(b[:], uint32(idx))
 47	return b[:]
 48}
 49
 50// BigInt returns a *big.Int representing the Idx
 51func (idx Idx) BigInt() *big.Int {
 52	return big.NewInt(int64(idx))
 53}
 54
 55// IdxFromBytes returns Idx from a byte array
 56func IdxFromBytes(b []byte) (Idx, error) {
 57	if len(b) != idxBytesLen {
 58		return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected 4", len(b))
 59	}
 60	idx := binary.BigEndian.Uint32(b[:4])
 61	return Idx(idx), nil
 62}
 63
 64// IdxFromBigInt converts a *big.Int to Idx type
 65func IdxFromBigInt(b *big.Int) (Idx, error) {
 66	if b.Int64() > maxIdxValue {
 67		return 0, ErrNumOverflow
 68	}
 69	return Idx(uint32(b.Int64())), nil
 70}
 71
 72// 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
 73type Account struct {
 74	Idx       Idx                `meddler:"idx"`
 75	TokenID   TokenID            `meddler:"token_id"`
 76	BatchNum  BatchNum           `meddler:"batch_num"`
 77	PublicKey *babyjub.PublicKey `meddler:"bjj"`
 78	EthAddr   ethCommon.Address  `meddler:"eth_addr"`
 79	Nonce     Nonce              `meddler:"-"` // max of 40 bits used
 80	Balance   *big.Int           `meddler:"-"` // max of 192 bits used
 81}
 82
 83func (a *Account) String() string {
 84	buf := bytes.NewBufferString("")
 85	fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
 86	fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
 87	fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
 88	fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
 89	fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
 90	return buf.String()
 91}
 92
 93// Bytes returns the bytes representing the Account, in a way that each BigInt
 94// is represented by 32 bytes, in spite of the BigInt could be represented in
 95// less bytes (due a small big.Int), so in this way each BigInt is always 32
 96// bytes and can be automatically parsed from a byte array.
 97func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
 98	var b [32 * NLeafElems]byte
 99
100	if a.Nonce > maxNonceValue {
101		return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
102	}
103	if len(a.Balance.Bytes()) > maxBalanceBytes {
104		return b, fmt.Errorf("%s Balance", ErrNumOverflow)
105	}
106
107	nonceBytes, err := a.Nonce.Bytes()
108	if err != nil {
109		return b, err
110	}
111
112	copy(b[0:4], a.TokenID.Bytes())
113	copy(b[4:9], nonceBytes[:])
114	if babyjub.PointCoordSign(a.PublicKey.X) {
115		b[10] = 1
116	}
117	copy(b[32:64], SwapEndianness(a.Balance.Bytes()))
118	copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
119	copy(b[96:116], a.EthAddr.Bytes())
120
121	return b, nil
122}
123
124// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
125func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
126	e := [NLeafElems]*big.Int{}
127
128	b, err := a.Bytes()
129	if err != nil {
130		return e, err
131	}
132
133	e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
134	e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
135	e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
136	e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
137
138	return e, nil
139}
140
141// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
142func (a *Account) HashValue() (*big.Int, error) {
143	b0 := big.NewInt(0)
144	toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
145	lBI, err := a.BigInts()
146	if err != nil {
147		return nil, err
148	}
149	copy(toHash[:], lBI[:])
150
151	v, err := poseidon.Hash(toHash)
152	return v, err
153}
154
155// AccountFromBigInts returns a Account from a [5]*big.Int
156func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
157	if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
158		return nil, ErrNotInFF
159	}
160	var b [32 * NLeafElems]byte
161	copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
162	copy(b[32:64], SwapEndianness(e[1].Bytes()))
163	copy(b[64:96], SwapEndianness(e[2].Bytes()))
164	copy(b[96:128], SwapEndianness(e[3].Bytes()))
165
166	return AccountFromBytes(b)
167}
168
169// AccountFromBytes returns a Account from a byte array
170func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
171	tokenID, err := TokenIDFromBytes(b[0:4])
172	if err != nil {
173		return nil, err
174	}
175	var nonceBytes5 [5]byte
176	copy(nonceBytes5[:], b[4:9])
177	nonce := NonceFromBytes(nonceBytes5)
178	sign := b[10] == 1
179	balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
180	if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
181		return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
182	}
183	ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
184	pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
185	if err != nil {
186		return nil, err
187	}
188	publicKey := babyjub.PublicKey(*pkPoint)
189	ethAddr := ethCommon.BytesToAddress(b[96:116])
190
191	if !cryptoUtils.CheckBigIntInField(balance) {
192		return nil, ErrNotInFF
193	}
194	if !cryptoUtils.CheckBigIntInField(ay) {
195		return nil, ErrNotInFF
196	}
197
198	a := Account{
199		TokenID:   TokenID(tokenID),
200		Nonce:     nonce,
201		Balance:   balance,
202		PublicKey: &publicKey,
203		EthAddr:   ethAddr,
204	}
205	return &a, nil
206}