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