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.BigEndian.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.BigEndian.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	Idx       Idx                `meddler:"idx"`
 69	TokenID   TokenID            `meddler:"token_id"`
 70	BatchNum  BatchNum           `meddler:"batch_num"`
 71	PublicKey *babyjub.PublicKey `meddler:"bjj"`
 72	EthAddr   ethCommon.Address  `meddler:"eth_addr"`
 73	Nonce     Nonce              `meddler:"-"` // max of 40 bits used
 74	Balance   *big.Int           `meddler:"-"` // max of 192 bits used
 75}
 76
 77func (a *Account) String() string {
 78	buf := bytes.NewBufferString("")
 79	fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
 80	fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
 81	fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
 82	fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
 83	fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
 84	return buf.String()
 85}
 86
 87// Bytes returns the bytes representing the Account, in a way that each BigInt
 88// is represented by 32 bytes, in spite of the BigInt could be represented in
 89// less bytes (due a small big.Int), so in this way each BigInt is always 32
 90// bytes and can be automatically parsed from a byte array.
 91func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
 92	var b [32 * NLeafElems]byte
 93
 94	if a.Nonce > maxNonceValue {
 95		return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
 96	}
 97	if len(a.Balance.Bytes()) > maxBalanceBytes {
 98		return b, fmt.Errorf("%s Balance", ErrNumOverflow)
 99	}
100
101	nonceBytes, err := a.Nonce.Bytes()
102	if err != nil {
103		return b, err
104	}
105
106	copy(b[0:4], a.TokenID.Bytes())
107	copy(b[4:9], nonceBytes[:])
108	if babyjub.PointCoordSign(a.PublicKey.X) {
109		b[10] = 1
110	}
111	copy(b[32:64], SwapEndianness(a.Balance.Bytes()))
112	copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
113	copy(b[96:116], a.EthAddr.Bytes())
114
115	return b, nil
116}
117
118// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
119func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
120	e := [NLeafElems]*big.Int{}
121
122	b, err := a.Bytes()
123	if err != nil {
124		return e, err
125	}
126
127	e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
128	e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
129	e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
130	e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
131
132	return e, nil
133}
134
135// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
136func (a *Account) HashValue() (*big.Int, error) {
137	b0 := big.NewInt(0)
138	toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
139	lBI, err := a.BigInts()
140	if err != nil {
141		return nil, err
142	}
143	copy(toHash[:], lBI[:])
144
145	v, err := poseidon.Hash(toHash)
146	return v, err
147}
148
149// AccountFromBigInts returns a Account from a [5]*big.Int
150func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
151	if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
152		return nil, ErrNotInFF
153	}
154	var b [32 * NLeafElems]byte
155	copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
156	copy(b[32:64], SwapEndianness(e[1].Bytes()))
157	copy(b[64:96], SwapEndianness(e[2].Bytes()))
158	copy(b[96:128], SwapEndianness(e[3].Bytes()))
159
160	return AccountFromBytes(b)
161}
162
163// AccountFromBytes returns a Account from a byte array
164func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
165	tokenID, err := TokenIDFromBytes(b[0:4])
166	if err != nil {
167		return nil, err
168	}
169	var nonceBytes5 [5]byte
170	copy(nonceBytes5[:], b[4:9])
171	nonce := NonceFromBytes(nonceBytes5)
172	sign := b[10] == 1
173	balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
174	if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
175		return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
176	}
177	ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
178	pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
179	if err != nil {
180		return nil, err
181	}
182	publicKey := babyjub.PublicKey(*pkPoint)
183	ethAddr := ethCommon.BytesToAddress(b[96:116])
184
185	if !cryptoUtils.CheckBigIntInField(balance) {
186		return nil, ErrNotInFF
187	}
188	if !cryptoUtils.CheckBigIntInField(ay) {
189		return nil, ErrNotInFF
190	}
191
192	a := Account{
193		TokenID:   TokenID(tokenID),
194		Nonce:     nonce,
195		Balance:   balance,
196		PublicKey: &publicKey,
197		EthAddr:   ethAddr,
198	}
199	return &a, nil
200}