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