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 idx bytes
 25	IdxBytesLen = 6
 26	// maxIdxValue is the maximum value that Idx can have (48 bits: maxIdxValue=2**48-1)
 27	maxIdxValue = 0xffffffffffff
 28
 29	// userThreshold determines the threshold from the User Idxs can be
 30	userThreshold = 256
 31	// IdxUserThreshold is a Idx type value that determines the threshold
 32	// from the User Idxs can be
 33	IdxUserThreshold = Idx(userThreshold)
 34)
 35
 36var (
 37	// FFAddr is used to check if an ethereum address is 0xff..ff
 38	FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
 39	// EmptyAddr is used to check if an ethereum address is 0
 40	EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
 41)
 42
 43// Idx represents the account Index in the MerkleTree
 44type Idx uint64
 45
 46// String returns a string representation of the Idx
 47func (idx Idx) String() string {
 48	return strconv.Itoa(int(idx))
 49}
 50
 51// Bytes returns a byte array representing the Idx
 52func (idx Idx) Bytes() ([6]byte, error) {
 53	if idx > maxIdxValue {
 54		return [6]byte{}, ErrIdxOverflow
 55	}
 56	var idxBytes [8]byte
 57	binary.BigEndian.PutUint64(idxBytes[:], uint64(idx))
 58	var b [6]byte
 59	copy(b[:], idxBytes[2:])
 60	return b, nil
 61}
 62
 63// BigInt returns a *big.Int representing the Idx
 64func (idx Idx) BigInt() *big.Int {
 65	return big.NewInt(int64(idx))
 66}
 67
 68// IdxFromBytes returns Idx from a byte array
 69func IdxFromBytes(b []byte) (Idx, error) {
 70	if len(b) != IdxBytesLen {
 71		return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected %d", len(b), IdxBytesLen)
 72	}
 73	var idxBytes [8]byte
 74	copy(idxBytes[2:], b[:])
 75	idx := binary.BigEndian.Uint64(idxBytes[:])
 76	return Idx(idx), nil
 77}
 78
 79// IdxFromBigInt converts a *big.Int to Idx type
 80func IdxFromBigInt(b *big.Int) (Idx, error) {
 81	if b.Int64() > maxIdxValue {
 82		return 0, ErrNumOverflow
 83	}
 84	return Idx(uint64(b.Int64())), nil
 85}
 86
 87// Nonce represents the nonce value in a uint64, which has the method Bytes that returns a byte array of length 5 (40 bits).
 88type Nonce uint64
 89
 90// Bytes returns a byte array of length 5 representing the Nonce
 91func (n Nonce) Bytes() ([5]byte, error) {
 92	if n > maxNonceValue {
 93		return [5]byte{}, ErrNonceOverflow
 94	}
 95	var nonceBytes [8]byte
 96	binary.BigEndian.PutUint64(nonceBytes[:], uint64(n))
 97	var b [5]byte
 98	copy(b[:], nonceBytes[3:])
 99	return b, nil
100}
101
102// BigInt returns the *big.Int representation of the Nonce value
103func (n Nonce) BigInt() *big.Int {
104	return big.NewInt(int64(n))
105}
106
107// NonceFromBytes returns Nonce from a [5]byte
108func NonceFromBytes(b [5]byte) Nonce {
109	var nonceBytes [8]byte
110	copy(nonceBytes[3:], b[:])
111	nonce := binary.BigEndian.Uint64(nonceBytes[:])
112	return Nonce(nonce)
113}
114
115// 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
116type Account struct {
117	Idx       Idx                `meddler:"idx"`
118	TokenID   TokenID            `meddler:"token_id"`
119	BatchNum  BatchNum           `meddler:"batch_num"`
120	PublicKey *babyjub.PublicKey `meddler:"bjj"`
121	EthAddr   ethCommon.Address  `meddler:"eth_addr"`
122	Nonce     Nonce              `meddler:"-"` // max of 40 bits used
123	Balance   *big.Int           `meddler:"-"` // max of 192 bits used
124}
125
126func (a *Account) String() string {
127	buf := bytes.NewBufferString("")
128	fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
129	fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
130	fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
131	fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
132	fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
133	return buf.String()
134}
135
136// Bytes returns the bytes representing the Account, in a way that each BigInt
137// is represented by 32 bytes, in spite of the BigInt could be represented in
138// less bytes (due a small big.Int), so in this way each BigInt is always 32
139// bytes and can be automatically parsed from a byte array.
140func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
141	var b [32 * NLeafElems]byte
142
143	if a.Nonce > maxNonceValue {
144		return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
145	}
146	if len(a.Balance.Bytes()) > maxBalanceBytes {
147		return b, fmt.Errorf("%s Balance", ErrNumOverflow)
148	}
149
150	nonceBytes, err := a.Nonce.Bytes()
151	if err != nil {
152		return b, err
153	}
154
155	copy(b[0:4], a.TokenID.Bytes())
156	copy(b[4:9], nonceBytes[:])
157	if babyjub.PointCoordSign(a.PublicKey.X) {
158		b[10] = 1
159	}
160	copy(b[32:64], SwapEndianness(a.Balance.Bytes()))
161	copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
162	copy(b[96:116], a.EthAddr.Bytes())
163
164	return b, nil
165}
166
167// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
168func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
169	e := [NLeafElems]*big.Int{}
170
171	b, err := a.Bytes()
172	if err != nil {
173		return e, err
174	}
175
176	e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
177	e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
178	e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
179	e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
180
181	return e, nil
182}
183
184// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
185func (a *Account) HashValue() (*big.Int, error) {
186	b0 := big.NewInt(0)
187	toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
188	lBI, err := a.BigInts()
189	if err != nil {
190		return nil, err
191	}
192	copy(toHash[:], lBI[:])
193
194	v, err := poseidon.Hash(toHash)
195	return v, err
196}
197
198// AccountFromBigInts returns a Account from a [5]*big.Int
199func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
200	if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
201		return nil, ErrNotInFF
202	}
203	var b [32 * NLeafElems]byte
204	copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
205	copy(b[32:64], SwapEndianness(e[1].Bytes()))
206	copy(b[64:96], SwapEndianness(e[2].Bytes()))
207	copy(b[96:128], SwapEndianness(e[3].Bytes()))
208
209	return AccountFromBytes(b)
210}
211
212// AccountFromBytes returns a Account from a byte array
213func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
214	tokenID, err := TokenIDFromBytes(b[0:4])
215	if err != nil {
216		return nil, err
217	}
218	var nonceBytes5 [5]byte
219	copy(nonceBytes5[:], b[4:9])
220	nonce := NonceFromBytes(nonceBytes5)
221	sign := b[10] == 1
222	balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
223	if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
224		return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
225	}
226	ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
227	pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
228	if err != nil {
229		return nil, err
230	}
231	publicKey := babyjub.PublicKey(*pkPoint)
232	ethAddr := ethCommon.BytesToAddress(b[96:116])
233
234	if !cryptoUtils.CheckBigIntInField(balance) {
235		return nil, ErrNotInFF
236	}
237	if !cryptoUtils.CheckBigIntInField(ay) {
238		return nil, ErrNotInFF
239	}
240
241	a := Account{
242		TokenID:   TokenID(tokenID),
243		Nonce:     nonce,
244		Balance:   balance,
245		PublicKey: &publicKey,
246		EthAddr:   ethAddr,
247	}
248	return &a, nil
249}