hermez-node/db/statedb/txprocessors.go
db/statedb/txprocessors.goRaw
1package statedb
2
3import (
4 "bytes"
5 "errors"
6 "math/big"
7
8 ethCommon "github.com/ethereum/go-ethereum/common"
9 "github.com/hermeznetwork/hermez-node/common"
10 "github.com/hermeznetwork/hermez-node/log"
11 "github.com/iden3/go-iden3-crypto/babyjub"
12 "github.com/iden3/go-iden3-crypto/poseidon"
13 "github.com/iden3/go-merkletree"
14 "github.com/iden3/go-merkletree/db"
15 "github.com/iden3/go-merkletree/db/memory"
16)
17
18var (
19 // keyidx is used as key in the db to store the current Idx
20 keyidx = []byte("idx")
21
22 // ffAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
23 emptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
24)
25
26func (s *StateDB) resetZKInputs() {
27 s.zki = nil
28 s.i = 0
29}
30
31type processedExit struct {
32 exit bool
33 newExit bool
34 idx common.Idx
35 acc common.Account
36}
37
38// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
39// the StateDB depending on the transaction Type. Returns the common.ZKInputs
40// to generate the SnarkProof later used by the BatchBuilder, and if
41// cmpExitTree is set to true, returns common.ExitTreeLeaf that is later used
42// by the Synchronizer to update the HistoryDB.
43func (s *StateDB) ProcessTxs(cmpExitTree, cmpZKInputs bool, l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) (*common.ZKInputs, []*common.ExitInfo, error) {
44 var err error
45 var exitTree *merkletree.MerkleTree
46
47 if s.zki != nil {
48 return nil, nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
49 }
50 defer s.resetZKInputs()
51
52 nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
53 if nTx == 0 {
54 // TODO return ZKInputs of batch without txs
55 return nil, nil, nil
56 }
57 exits := make([]processedExit, nTx)
58
59 if cmpZKInputs {
60 s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function, taken from config file/coordinator call
61 s.zki.OldLastIdx = (s.idx - 1).BigInt()
62 s.zki.OldStateRoot = s.mt.Root().BigInt()
63 }
64
65 // TBD if ExitTree is only in memory or stored in disk, for the moment
66 // only needed in memory
67 if cmpExitTree {
68 exitTree, err = merkletree.NewMerkleTree(memory.NewMemoryStorage(), s.mt.MaxLevels())
69 if err != nil {
70 return nil, nil, err
71 }
72 }
73
74 // assumption: l1usertx are sorted by L1Tx.Position
75 for _, tx := range l1usertxs {
76 exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
77 if err != nil {
78 return nil, nil, err
79 }
80 if exitIdx != nil && cmpExitTree {
81 exits[s.i] = processedExit{
82 exit: true,
83 newExit: newExit,
84 idx: *exitIdx,
85 acc: *exitAccount,
86 }
87 }
88 if s.zki != nil {
89 s.i++
90 }
91 }
92 for _, tx := range l1coordinatortxs {
93 exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
94 if err != nil {
95 return nil, nil, err
96 }
97 if exitIdx != nil {
98 log.Error("Unexpected Exit in L1CoordinatorTx")
99 }
100 if exitIdx != nil && cmpExitTree {
101 exits[s.i] = processedExit{
102 exit: true,
103 newExit: newExit,
104 idx: *exitIdx,
105 acc: *exitAccount,
106 }
107 }
108 if s.zki != nil {
109 s.i++
110 }
111 }
112 for _, tx := range l2txs {
113 exitIdx, exitAccount, newExit, err := s.processL2Tx(exitTree, tx)
114 if err != nil {
115 return nil, nil, err
116 }
117 if exitIdx != nil && cmpExitTree {
118 exits[s.i] = processedExit{
119 exit: true,
120 newExit: newExit,
121 idx: *exitIdx,
122 acc: *exitAccount,
123 }
124 }
125 if s.zki != nil {
126 s.i++
127 }
128 }
129
130 if !cmpExitTree && !cmpZKInputs {
131 return nil, nil, nil
132 }
133
134 // once all txs processed (exitTree root frozen), for each Exit,
135 // generate common.ExitInfo data
136 var exitInfos []*common.ExitInfo
137 for i := 0; i < nTx; i++ {
138 if !exits[i].exit {
139 continue
140 }
141 exitIdx := exits[i].idx
142 exitAccount := exits[i].acc
143
144 // 0. generate MerkleProof
145 p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
146 if err != nil {
147 return nil, nil, err
148 }
149 // 1. compute nullifier
150 exitAccStateValue, err := exitAccount.HashValue()
151 if err != nil {
152 return nil, nil, err
153 }
154 nullifier, err := poseidon.Hash([]*big.Int{
155 exitAccStateValue,
156 big.NewInt(int64(s.currentBatch)),
157 exitTree.Root().BigInt(),
158 })
159 if err != nil {
160 return nil, nil, err
161 }
162 // 2. generate common.ExitInfo
163 ei := &common.ExitInfo{
164 AccountIdx: exitIdx,
165 MerkleProof: p,
166 Nullifier: nullifier,
167 Balance: exitAccount.Balance,
168 }
169 exitInfos = append(exitInfos, ei)
170
171 if s.zki != nil {
172 s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
173 s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
174 if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
175 s.zki.Sign2[i] = big.NewInt(1)
176 }
177 s.zki.Ay2[i] = exitAccount.PublicKey.Y
178 s.zki.Balance2[i] = exitAccount.Balance
179 s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
180 s.zki.Siblings2[i] = p.Siblings
181 if exits[i].newExit {
182 s.zki.NewExit[i] = big.NewInt(1)
183 }
184 if p.IsOld0 {
185 s.zki.IsOld0_2[i] = big.NewInt(1)
186 }
187 s.zki.OldKey2[i] = p.OldKey.BigInt()
188 s.zki.OldValue2[i] = p.OldValue.BigInt()
189 }
190 }
191 if !cmpZKInputs {
192 return nil, exitInfos, nil
193 }
194
195 // compute last ZKInputs parameters
196 s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
197 // zki.FeeIdxs = ? // TODO, this will be get from the config file
198 tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
199 if err != nil {
200 return nil, nil, err
201 }
202 s.zki.FeePlanTokens = tokenIDs
203
204 // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
205
206 // TODO once the Node Config sets the Accounts where to send the Fees
207 // compute fees & update ZKInputs
208
209 // return exitInfos, so Synchronizer will be able to store it into
210 // HistoryDB for the concrete BatchNum
211 return s.zki, exitInfos, nil
212}
213
214// getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
215func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) ([]*big.Int, error) {
216 tokenIDs := make(map[common.TokenID]bool)
217 for i := 0; i < len(l1usertxs); i++ {
218 tokenIDs[l1usertxs[i].TokenID] = true
219 }
220 for i := 0; i < len(l1coordinatortxs); i++ {
221 tokenIDs[l1coordinatortxs[i].TokenID] = true
222 }
223 for i := 0; i < len(l2txs); i++ {
224 // as L2Tx does not have parameter TokenID, get it from the
225 // AccountsDB (in the StateDB)
226 acc, err := s.GetAccount(l2txs[i].ToIdx)
227 if err != nil {
228 return nil, err
229 }
230 tokenIDs[acc.TokenID] = true
231 }
232 var tBI []*big.Int
233 for t := range tokenIDs {
234 tBI = append(tBI, t.BigInt())
235 }
236 return tBI, nil
237}
238
239// processL1Tx process the given L1Tx applying the needed updates to the
240// StateDB depending on the transaction Type. It returns the 3 parameters
241// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
242// the Exit created a new Leaf in the ExitTree.
243func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, error) {
244 // ZKInputs
245 if s.zki != nil {
246 // Txs
247 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
248 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
249 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
250 s.zki.OnChain[s.i] = big.NewInt(1)
251
252 // L1Txs
253 s.zki.LoadAmountF[s.i] = tx.LoadAmount
254 s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
255 if tx.FromBJJ != nil {
256 s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
257 }
258
259 // Intermediate States
260 s.zki.ISOnChain[s.i] = big.NewInt(1)
261 }
262
263 switch tx.Type {
264 case common.TxTypeForceTransfer, common.TxTypeTransfer:
265 // go to the MT account of sender and receiver, and update balance
266 // & nonce
267 err := s.applyTransfer(tx.Tx())
268 if err != nil {
269 return nil, nil, false, err
270 }
271 case common.TxTypeCreateAccountDeposit:
272 // add new account to the MT, update balance of the MT account
273 err := s.applyCreateAccount(tx)
274 if err != nil {
275 return nil, nil, false, err
276 }
277
278 if s.zki != nil {
279 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
280 s.zki.NewAccount[s.i] = big.NewInt(1)
281 }
282 case common.TxTypeDeposit:
283 // update balance of the MT account
284 err := s.applyDeposit(tx, false)
285 if err != nil {
286 return nil, nil, false, err
287 }
288 case common.TxTypeDepositTransfer:
289 // update balance in MT account, update balance & nonce of sender
290 // & receiver
291 err := s.applyDeposit(tx, true)
292 if err != nil {
293 return nil, nil, false, err
294 }
295 case common.TxTypeCreateAccountDepositTransfer:
296 // add new account to the merkletree, update balance in MT account,
297 // update balance & nonce of sender & receiver
298 err := s.applyCreateAccountDepositTransfer(tx)
299 if err != nil {
300 return nil, nil, false, err
301 }
302
303 if s.zki != nil {
304 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
305 s.zki.NewAccount[s.i] = big.NewInt(1)
306 }
307 case common.TxTypeExit:
308 // execute exit flow
309 exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
310 if err != nil {
311 return nil, nil, false, err
312 }
313 return &tx.FromIdx, exitAccount, newExit, nil
314 default:
315 }
316
317 return nil, nil, false, nil
318}
319
320// processL2Tx process the given L2Tx applying the needed updates to the
321// StateDB depending on the transaction Type. It returns the 3 parameters
322// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
323// the Exit created a new Leaf in the ExitTree.
324func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
325 var err error
326 // ZKInputs
327 if s.zki != nil {
328 // Txs
329 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
330 // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
331 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
332 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
333
334 // fill AuxToIdx if needed
335 if tx.ToIdx == common.Idx(0) {
336 var idx common.Idx
337 if !bytes.Equal(tx.ToEthAddr.Bytes(), emptyAddr.Bytes()) && tx.ToBJJ == nil {
338 // case ToEthAddr!=0 && ToBJJ=0
339 idx, err = s.GetIdxByEthAddr(tx.ToEthAddr)
340 if err != nil {
341 return nil, nil, false, ErrToIdxNotFound
342 }
343 } else if !bytes.Equal(tx.ToEthAddr.Bytes(), emptyAddr.Bytes()) && tx.ToBJJ != nil {
344 // case ToEthAddr!=0 && ToBJJ!=0
345 idx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
346 if err != nil {
347 return nil, nil, false, ErrToIdxNotFound
348 }
349 } else {
350 // rest of cases (included case ToEthAddr==0) are not possible
351 return nil, nil, false, ErrToIdxNotFound
352 }
353 s.zki.AuxToIdx[s.i] = idx.BigInt()
354 }
355 s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
356 s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
357
358 s.zki.OnChain[s.i] = big.NewInt(0)
359 s.zki.NewAccount[s.i] = big.NewInt(0)
360
361 // L2Txs
362 // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
363 // s.zki.RqTxCompressedDataV2[s.i] = // TODO
364 // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
365 // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
366 s.zki.S[s.i] = tx.Signature.S
367 s.zki.R8x[s.i] = tx.Signature.R8.X
368 s.zki.R8y[s.i] = tx.Signature.R8.Y
369 }
370
371 switch tx.Type {
372 case common.TxTypeTransfer:
373 // go to the MT account of sender and receiver, and update
374 // balance & nonce
375 err = s.applyTransfer(tx.Tx())
376 if err != nil {
377 return nil, nil, false, err
378 }
379 case common.TxTypeExit:
380 // execute exit flow
381 exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
382 if err != nil {
383 return nil, nil, false, err
384 }
385 return &tx.FromIdx, exitAccount, newExit, nil
386 default:
387 }
388 return nil, nil, false, nil
389}
390
391// applyCreateAccount creates a new account in the account of the depositer, it
392// stores the deposit value
393func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
394 account := &common.Account{
395 TokenID: tx.TokenID,
396 Nonce: 0,
397 Balance: tx.LoadAmount,
398 PublicKey: tx.FromBJJ,
399 EthAddr: tx.FromEthAddr,
400 }
401
402 p, err := s.CreateAccount(common.Idx(s.idx+1), account)
403 if err != nil {
404 return err
405 }
406 if s.zki != nil {
407 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
408 s.zki.Nonce1[s.i] = big.NewInt(0)
409 if babyjub.PointCoordSign(tx.FromBJJ.X) {
410 s.zki.Sign1[s.i] = big.NewInt(1)
411 }
412 s.zki.Ay1[s.i] = tx.FromBJJ.Y
413 s.zki.Balance1[s.i] = tx.LoadAmount
414 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
415 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
416 if p.IsOld0 {
417 s.zki.IsOld0_1[s.i] = big.NewInt(1)
418 }
419 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
420 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
421 }
422
423 s.idx = s.idx + 1
424 return s.setIdx(s.idx)
425}
426
427// applyDeposit updates the balance in the account of the depositer, if
428// andTransfer parameter is set to true, the method will also apply the
429// Transfer of the L1Tx/DepositTransfer
430func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
431 // deposit the tx.LoadAmount into the sender account
432 accSender, err := s.GetAccount(tx.FromIdx)
433 if err != nil {
434 return err
435 }
436 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
437
438 // in case that the tx is a L1Tx>DepositTransfer
439 var accReceiver *common.Account
440 if transfer {
441 accReceiver, err = s.GetAccount(tx.ToIdx)
442 if err != nil {
443 return err
444 }
445 // subtract amount to the sender
446 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
447 // add amount to the receiver
448 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
449 }
450 // update sender account in localStateDB
451 p, err := s.UpdateAccount(tx.FromIdx, accSender)
452 if err != nil {
453 return err
454 }
455 if s.zki != nil {
456 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
457 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
458 if babyjub.PointCoordSign(accSender.PublicKey.X) {
459 s.zki.Sign1[s.i] = big.NewInt(1)
460 }
461 s.zki.Ay1[s.i] = accSender.PublicKey.Y
462 s.zki.Balance1[s.i] = accSender.Balance
463 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
464 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
465 // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
466 }
467
468 // this is done after updating Sender Account (depositer)
469 if transfer {
470 // update receiver account in localStateDB
471 p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
472 if err != nil {
473 return err
474 }
475 if s.zki != nil {
476 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
477 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
478 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
479 s.zki.Sign2[s.i] = big.NewInt(1)
480 }
481 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
482 s.zki.Balance2[s.i] = accReceiver.Balance
483 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
484 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
485 // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
486 }
487 }
488
489 return nil
490}
491
492// applyTransfer updates the balance & nonce in the account of the sender, and
493// the balance in the account of the receiver
494func (s *StateDB) applyTransfer(tx *common.Tx) error {
495 // get sender and receiver accounts from localStateDB
496 accSender, err := s.GetAccount(tx.FromIdx)
497 if err != nil {
498 return err
499 }
500 accReceiver, err := s.GetAccount(tx.ToIdx)
501 if err != nil {
502 return err
503 }
504
505 // increment nonce
506 accSender.Nonce++
507
508 // subtract amount to the sender
509 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
510 // add amount to the receiver
511 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
512
513 // update sender account in localStateDB
514 pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
515 if err != nil {
516 return err
517 }
518 if s.zki != nil {
519 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
520 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
521 if babyjub.PointCoordSign(accSender.PublicKey.X) {
522 s.zki.Sign1[s.i] = big.NewInt(1)
523 }
524 s.zki.Ay1[s.i] = accSender.PublicKey.Y
525 s.zki.Balance1[s.i] = accSender.Balance
526 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
527 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
528 }
529
530 // update receiver account in localStateDB
531 pReceiver, err := s.UpdateAccount(tx.ToIdx, accReceiver)
532 if err != nil {
533 return err
534 }
535 if s.zki != nil {
536 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
537 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
538 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
539 s.zki.Sign2[s.i] = big.NewInt(1)
540 }
541 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
542 s.zki.Balance2[s.i] = accReceiver.Balance
543 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
544 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
545 }
546
547 return nil
548}
549
550// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
551// makes a deposit, and performs a transfer to another account
552func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
553 accSender := &common.Account{
554 TokenID: tx.TokenID,
555 Nonce: 0,
556 Balance: tx.LoadAmount,
557 PublicKey: tx.FromBJJ,
558 EthAddr: tx.FromEthAddr,
559 }
560 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
561 accReceiver, err := s.GetAccount(tx.ToIdx)
562 if err != nil {
563 return err
564 }
565 // subtract amount to the sender
566 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
567 // add amount to the receiver
568 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
569
570 // create Account of the Sender
571 p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
572 if err != nil {
573 return err
574 }
575 if s.zki != nil {
576 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
577 s.zki.Nonce1[s.i] = big.NewInt(0)
578 if babyjub.PointCoordSign(tx.FromBJJ.X) {
579 s.zki.Sign1[s.i] = big.NewInt(1)
580 }
581 s.zki.Ay1[s.i] = tx.FromBJJ.Y
582 s.zki.Balance1[s.i] = tx.LoadAmount
583 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
584 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
585 if p.IsOld0 {
586 s.zki.IsOld0_1[s.i] = big.NewInt(1)
587 }
588 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
589 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
590 }
591
592 // update receiver account in localStateDB
593 p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
594 if err != nil {
595 return err
596 }
597 if s.zki != nil {
598 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
599 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
600 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
601 s.zki.Sign2[s.i] = big.NewInt(1)
602 }
603 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
604 s.zki.Balance2[s.i] = accReceiver.Balance
605 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
606 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
607 }
608
609 s.idx = s.idx + 1
610 return s.setIdx(s.idx)
611}
612
613// It returns the ExitAccount and a boolean determining if the Exit created a
614// new Leaf in the ExitTree.
615func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx *common.Tx) (*common.Account, bool, error) {
616 // 0. subtract tx.Amount from current Account in StateMT
617 // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
618 acc, err := s.GetAccount(tx.FromIdx)
619 if err != nil {
620 return nil, false, err
621 }
622 acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
623 p, err := s.UpdateAccount(tx.FromIdx, acc)
624 if err != nil {
625 return nil, false, err
626 }
627 if s.zki != nil {
628 s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
629 s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
630 if babyjub.PointCoordSign(acc.PublicKey.X) {
631 s.zki.Sign1[s.i] = big.NewInt(1)
632 }
633 s.zki.Ay1[s.i] = acc.PublicKey.Y
634 s.zki.Balance1[s.i] = acc.Balance
635 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
636 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
637 }
638
639 if exitTree == nil {
640 return nil, false, nil
641 }
642 exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
643 if err == db.ErrNotFound {
644 // 1a. if idx does not exist in exitTree:
645 // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
646 exitAccount := &common.Account{
647 TokenID: acc.TokenID,
648 Nonce: common.Nonce(1),
649 Balance: tx.Amount,
650 PublicKey: acc.PublicKey,
651 EthAddr: acc.EthAddr,
652 }
653 _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
654 return exitAccount, true, err
655 } else if err != nil {
656 return exitAccount, false, err
657 }
658
659 // 1b. if idx already exist in exitTree:
660 // update account, where account.Balance += exitAmount
661 exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
662 _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
663 return exitAccount, false, err
664}
665
666// getIdx returns the stored Idx from the localStateDB, which is the last Idx
667// used for an Account in the localStateDB.
668func (s *StateDB) getIdx() (common.Idx, error) {
669 idxBytes, err := s.DB().Get(keyidx)
670 if err == db.ErrNotFound {
671 return 0, nil
672 }
673 if err != nil {
674 return 0, err
675 }
676 return common.IdxFromBytes(idxBytes[:4])
677}
678
679// setIdx stores Idx in the localStateDB
680func (s *StateDB) setIdx(idx common.Idx) error {
681 tx, err := s.DB().NewTx()
682 if err != nil {
683 return err
684 }
685 err = tx.Put(keyidx, idx.Bytes())
686 if err != nil {
687 return err
688 }
689 if err := tx.Commit(); err != nil {
690 return err
691 }
692 return nil
693}