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