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