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