hermez-node/txprocessor/txprocessor.go
txprocessor/txprocessor.goRaw
1package txprocessor
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io/ioutil"
8 "math/big"
9 "os"
10
11 "github.com/hermeznetwork/hermez-node/common"
12 "github.com/hermeznetwork/hermez-node/db/statedb"
13 "github.com/hermeznetwork/hermez-node/log"
14 "github.com/hermeznetwork/tracerr"
15 "github.com/iden3/go-iden3-crypto/babyjub"
16 "github.com/iden3/go-merkletree"
17 "github.com/iden3/go-merkletree/db"
18 "github.com/iden3/go-merkletree/db/pebble"
19)
20
21// TxProcessor represents the TxProcessor object
22type TxProcessor struct {
23 s *statedb.StateDB
24 zki *common.ZKInputs
25 // i is the current transaction index in the ZKInputs generation (zki)
26 i int
27 // AccumulatedFees contains the accumulated fees for each token (Coord
28 // Idx) in the processed batch
29 AccumulatedFees map[common.Idx]*big.Int
30 config Config
31}
32
33// Config contains the TxProcessor configuration parameters
34type Config struct {
35 NLevels uint32
36 MaxFeeTx uint32
37 MaxTx uint32
38 MaxL1Tx uint32
39 ChainID uint16
40}
41
42type processedExit struct {
43 exit bool
44 newExit bool
45 idx common.Idx
46 acc common.Account
47}
48
49// ProcessTxOutput contains the output of the ProcessTxs method
50type ProcessTxOutput struct {
51 ZKInputs *common.ZKInputs
52 ExitInfos []common.ExitInfo
53 CreatedAccounts []common.Account
54 CoordinatorIdxsMap map[common.TokenID]common.Idx
55 CollectedFees map[common.TokenID]*big.Int
56}
57
58// NewTxProcessor returns a new TxProcessor with the given *StateDB & Config
59func NewTxProcessor(sdb *statedb.StateDB, config Config) *TxProcessor {
60 return &TxProcessor{
61 s: sdb,
62 zki: nil,
63 i: 0,
64 config: config,
65 }
66}
67
68// StateDB returns a pointer to the StateDB of the TxProcessor
69func (tp *TxProcessor) StateDB() *statedb.StateDB {
70 return tp.s
71}
72
73func (tp *TxProcessor) resetZKInputs() {
74 tp.zki = nil
75 tp.i = 0 // initialize current transaction index in the ZKInputs generation
76}
77
78// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
79// the StateDB depending on the transaction Type. If StateDB
80// type==TypeBatchBuilder, returns the common.ZKInputs to generate the
81// SnarkProof later used by the BatchBuilder. If StateDB
82// type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
83// returns common.ExitTreeLeaf that is later used by the Synchronizer to update
84// the HistoryDB, and adds Nonce & TokenID to the L2Txs.
85// And if TypeSynchronizer returns an array of common.Account with all the
86// created accounts.
87func (tp *TxProcessor) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx,
88 l2txs []common.PoolL2Tx) (ptOut *ProcessTxOutput, err error) {
89 defer func() {
90 if err == nil {
91 err = tp.s.MakeCheckpoint()
92 }
93 }()
94
95 var exitTree *merkletree.MerkleTree
96 var createdAccounts []common.Account
97
98 if tp.zki != nil {
99 return nil, tracerr.Wrap(errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty"))
100 }
101 defer tp.resetZKInputs()
102
103 if len(coordIdxs) >= int(tp.config.MaxFeeTx) {
104 return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), tp.config.MaxFeeTx))
105 }
106
107 nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
108
109 if nTx > int(tp.config.MaxTx) {
110 return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx + L2Tx (%d) can not be bigger than MaxTx (%d)", nTx, tp.config.MaxTx))
111 }
112 if len(l1usertxs)+len(l1coordinatortxs) > int(tp.config.MaxL1Tx) {
113 return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx (%d) can not be bigger than MaxL1Tx (%d)", len(l1usertxs)+len(l1coordinatortxs), tp.config.MaxTx))
114 }
115
116 exits := make([]processedExit, nTx)
117
118 if tp.s.Typ == statedb.TypeBatchBuilder {
119 tp.zki = common.NewZKInputs(tp.config.ChainID, tp.config.MaxTx, tp.config.MaxL1Tx,
120 tp.config.MaxFeeTx, tp.config.NLevels, (tp.s.CurrentBatch() + 1).BigInt())
121 tp.zki.OldLastIdx = tp.s.CurrentIdx().BigInt()
122 tp.zki.OldStateRoot = tp.s.MT.Root().BigInt()
123 tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx()
124 }
125
126 // TBD if ExitTree is only in memory or stored in disk, for the moment
127 // is only needed in memory
128 if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
129 tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
130 if err != nil {
131 return nil, tracerr.Wrap(err)
132 }
133 defer func() {
134 if err := os.RemoveAll(tmpDir); err != nil {
135 log.Errorw("Deleting statedb temp exit tree", "err", err)
136 }
137 }()
138 sto, err := pebble.NewPebbleStorage(tmpDir, false)
139 if err != nil {
140 return nil, tracerr.Wrap(err)
141 }
142 defer sto.Close()
143 exitTree, err = merkletree.NewMerkleTree(sto, tp.s.MT.MaxLevels())
144 if err != nil {
145 return nil, tracerr.Wrap(err)
146 }
147 }
148
149 // Process L1UserTxs
150 for i := 0; i < len(l1usertxs); i++ {
151 // assumption: l1usertx are sorted by L1Tx.Position
152 exitIdx, exitAccount, newExit, createdAccount, err := tp.ProcessL1Tx(exitTree,
153 &l1usertxs[i])
154 if err != nil {
155 return nil, tracerr.Wrap(err)
156 }
157 if tp.s.Typ == statedb.TypeSynchronizer {
158 if createdAccount != nil {
159 createdAccounts = append(createdAccounts, *createdAccount)
160 l1usertxs[i].EffectiveFromIdx = createdAccount.Idx
161 } else {
162 l1usertxs[i].EffectiveFromIdx = l1usertxs[i].FromIdx
163 }
164 }
165 if tp.zki != nil {
166 l1TxData, err := l1usertxs[i].BytesGeneric()
167 if err != nil {
168 return nil, tracerr.Wrap(err)
169 }
170 tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
171
172 l1TxDataAvailability, err :=
173 l1usertxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
174 if err != nil {
175 return nil, tracerr.Wrap(err)
176 }
177 tp.zki.Metadata.L1TxsDataAvailability =
178 append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
179
180 tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
181 tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
182 if exitIdx == nil {
183 tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
184 }
185 }
186 if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
187 if exitIdx != nil && exitTree != nil {
188 exits[tp.i] = processedExit{
189 exit: true,
190 newExit: newExit,
191 idx: *exitIdx,
192 acc: *exitAccount,
193 }
194 }
195 tp.i++
196 }
197 }
198
199 // Process L1CoordinatorTxs
200 for i := 0; i < len(l1coordinatortxs); i++ {
201 exitIdx, _, _, createdAccount, err := tp.ProcessL1Tx(exitTree, &l1coordinatortxs[i])
202 if err != nil {
203 return nil, tracerr.Wrap(err)
204 }
205 if exitIdx != nil {
206 log.Error("Unexpected Exit in L1CoordinatorTx")
207 }
208 if tp.s.Typ == statedb.TypeSynchronizer {
209 if createdAccount != nil {
210 createdAccounts = append(createdAccounts, *createdAccount)
211 l1coordinatortxs[i].EffectiveFromIdx = createdAccount.Idx
212 } else {
213 l1coordinatortxs[i].EffectiveFromIdx = l1coordinatortxs[i].FromIdx
214 }
215 }
216 if tp.zki != nil {
217 l1TxData, err := l1coordinatortxs[i].BytesGeneric()
218 if err != nil {
219 return nil, tracerr.Wrap(err)
220 }
221 tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
222 l1TxDataAvailability, err :=
223 l1coordinatortxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
224 if err != nil {
225 return nil, tracerr.Wrap(err)
226 }
227 tp.zki.Metadata.L1TxsDataAvailability =
228 append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
229
230 tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
231 tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
232 tp.i++
233 }
234 }
235
236 // remove repeated CoordIdxs that are for the same TokenID (use the
237 // first occurrence)
238 usedCoordTokenIDs := make(map[common.TokenID]bool)
239 var filteredCoordIdxs []common.Idx
240 for i := 0; i < len(coordIdxs); i++ {
241 accCoord, err := tp.s.GetAccount(coordIdxs[i])
242 if err != nil {
243 return nil, tracerr.Wrap(err)
244 }
245 if !usedCoordTokenIDs[accCoord.TokenID] {
246 usedCoordTokenIDs[accCoord.TokenID] = true
247 filteredCoordIdxs = append(filteredCoordIdxs, coordIdxs[i])
248 }
249 }
250 coordIdxs = filteredCoordIdxs
251
252 tp.AccumulatedFees = make(map[common.Idx]*big.Int)
253 for _, idx := range coordIdxs {
254 tp.AccumulatedFees[idx] = big.NewInt(0)
255 }
256
257 // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
258 // coordIdxs. In this way, if a coordIdx uses an Idx that is being
259 // created in the current batch, at this point the Idx will be created
260 coordIdxsMap, err := tp.s.GetTokenIDsFromIdxs(coordIdxs)
261 if err != nil {
262 return nil, tracerr.Wrap(err)
263 }
264 // collectedFees will contain the amount of fee collected for each
265 // TokenID
266 var collectedFees map[common.TokenID]*big.Int
267 if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
268 collectedFees = make(map[common.TokenID]*big.Int)
269 for tokenID := range coordIdxsMap {
270 collectedFees[tokenID] = big.NewInt(0)
271 }
272 }
273
274 if tp.zki != nil {
275 // get the feePlanTokens
276 feePlanTokens, err := tp.getFeePlanTokens(coordIdxs)
277 if err != nil {
278 log.Error(err)
279 return nil, tracerr.Wrap(err)
280 }
281 copy(tp.zki.FeePlanTokens, feePlanTokens)
282 }
283
284 // Process L2Txs
285 for i := 0; i < len(l2txs); i++ {
286 exitIdx, exitAccount, newExit, err := tp.ProcessL2Tx(coordIdxsMap, collectedFees,
287 exitTree, &l2txs[i])
288 if err != nil {
289 return nil, tracerr.Wrap(err)
290 }
291 if tp.zki != nil {
292 l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(tp.zki.Metadata.NLevels)
293 if err != nil {
294 return nil, tracerr.Wrap(err)
295 }
296 tp.zki.Metadata.L2TxsData = append(tp.zki.Metadata.L2TxsData, l2TxData)
297
298 // Intermediate States
299 if tp.i < nTx-1 {
300 tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
301 tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
302 tp.zki.ISAccFeeOut[tp.i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
303 if exitIdx == nil {
304 tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
305 }
306 }
307 }
308 if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
309 if exitIdx != nil && exitTree != nil {
310 exits[tp.i] = processedExit{
311 exit: true,
312 newExit: newExit,
313 idx: *exitIdx,
314 acc: *exitAccount,
315 }
316 }
317 tp.i++
318 }
319 }
320
321 if tp.zki != nil {
322 txCompressedDataEmpty := common.TxCompressedDataEmpty(tp.config.ChainID)
323 last := tp.i - 1
324 if tp.i == 0 {
325 last = 0
326 }
327 for i := last; i < int(tp.config.MaxTx); i++ {
328 if i < int(tp.config.MaxTx)-1 {
329 tp.zki.ISOutIdx[i] = tp.s.CurrentIdx().BigInt()
330 tp.zki.ISStateRoot[i] = tp.s.MT.Root().BigInt()
331 tp.zki.ISAccFeeOut[i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
332 tp.zki.ISExitRoot[i] = exitTree.Root().BigInt()
333 }
334 if i >= tp.i {
335 tp.zki.TxCompressedData[i] = txCompressedDataEmpty
336 }
337 }
338 isFinalAccFee := formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
339 copy(tp.zki.ISFinalAccFee, isFinalAccFee)
340 // before computing the Fees txs, set the ISInitStateRootFee
341 tp.zki.ISInitStateRootFee = tp.s.MT.Root().BigInt()
342 }
343
344 // distribute the AccumulatedFees from the processed L2Txs into the
345 // Coordinator Idxs
346 iFee := 0
347 for _, idx := range coordIdxs {
348 accumulatedFee := tp.AccumulatedFees[idx]
349
350 cmp := accumulatedFee.Cmp(big.NewInt(0))
351 if cmp == 1 { // accumulatedFee>0
352 // send the fee to the Idx of the Coordinator for the TokenID
353 accCoord, err := tp.s.GetAccount(idx)
354 if err != nil {
355 log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx)
356 return nil, tracerr.Wrap(err)
357 }
358 if tp.zki != nil {
359 tp.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
360 tp.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
361 coordBJJSign, coordBJJY := babyjub.UnpackSignY(accCoord.BJJ)
362 if coordBJJSign {
363 tp.zki.Sign3[iFee] = big.NewInt(1)
364 }
365 tp.zki.Ay3[iFee] = coordBJJY
366 tp.zki.Balance3[iFee] = accCoord.Balance
367 tp.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
368 }
369 accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
370 pFee, err := tp.s.UpdateAccount(idx, accCoord)
371 if err != nil {
372 log.Error(err)
373 return nil, tracerr.Wrap(err)
374 }
375 if tp.zki != nil {
376 tp.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
377 tp.zki.ISStateRootFee[iFee] = tp.s.MT.Root().BigInt()
378 }
379 }
380 iFee++
381 }
382 if tp.zki != nil {
383 for i := len(tp.AccumulatedFees); i < int(tp.config.MaxFeeTx)-1; i++ {
384 tp.zki.ISStateRootFee[i] = tp.s.MT.Root().BigInt()
385 }
386 // add Coord Idx to ZKInputs.FeeTxsData
387 for i := 0; i < len(coordIdxs); i++ {
388 tp.zki.FeeIdxs[i] = coordIdxs[i].BigInt()
389 }
390 }
391
392 if tp.s.Typ == statedb.TypeTxSelector {
393 return nil, nil
394 }
395
396 // once all txs processed (exitTree root frozen), for each Exit,
397 // generate common.ExitInfo data
398 var exitInfos []common.ExitInfo
399 for i := 0; i < nTx; i++ {
400 if !exits[i].exit {
401 continue
402 }
403 exitIdx := exits[i].idx
404 exitAccount := exits[i].acc
405
406 // 0. generate MerkleProof
407 p, err := exitTree.GenerateSCVerifierProof(exitIdx.BigInt(), nil)
408 if err != nil {
409 return nil, tracerr.Wrap(err)
410 }
411
412 // 1. generate common.ExitInfo
413 ei := common.ExitInfo{
414 AccountIdx: exitIdx,
415 MerkleProof: p,
416 Balance: exitAccount.Balance,
417 }
418 exitInfos = append(exitInfos, ei)
419 }
420
421 if tp.s.Typ == statedb.TypeSynchronizer {
422 // return exitInfos, createdAccounts and collectedFees, so Synchronizer will
423 // be able to store it into HistoryDB for the concrete BatchNum
424 return &ProcessTxOutput{
425 ZKInputs: nil,
426 ExitInfos: exitInfos,
427 CreatedAccounts: createdAccounts,
428 CoordinatorIdxsMap: coordIdxsMap,
429 CollectedFees: collectedFees,
430 }, nil
431 }
432
433 // compute last ZKInputs parameters
434 tp.zki.GlobalChainID = big.NewInt(int64(tp.config.ChainID))
435 tp.zki.Metadata.NewStateRootRaw = tp.s.MT.Root()
436 tp.zki.Metadata.NewExitRootRaw = exitTree.Root()
437
438 // return ZKInputs as the BatchBuilder will return it to forge the Batch
439 return &ProcessTxOutput{
440 ZKInputs: tp.zki,
441 ExitInfos: nil,
442 CreatedAccounts: nil,
443 CoordinatorIdxsMap: coordIdxsMap,
444 CollectedFees: nil,
445 }, nil
446}
447
448// getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
449// corresponding to the given CoordIdxs and the processed L2Txs
450func (tp *TxProcessor) getFeePlanTokens(coordIdxs []common.Idx) ([]*big.Int, error) {
451 var tBI []*big.Int
452 for i := 0; i < len(coordIdxs); i++ {
453 acc, err := tp.s.GetAccount(coordIdxs[i])
454 if err != nil {
455 log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
456 return nil, tracerr.Wrap(err)
457 }
458 tBI = append(tBI, acc.TokenID.BigInt())
459 }
460 return tBI, nil
461}
462
463// ProcessL1Tx process the given L1Tx applying the needed updates to the
464// StateDB depending on the transaction Type. It returns the 3 parameters
465// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
466// the Exit created a new Leaf in the ExitTree.
467// And another *common.Account parameter which contains the created account in
468// case that has been a new created account and that the StateDB is of type
469// TypeSynchronizer.
470func (tp *TxProcessor) ProcessL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx,
471 *common.Account, bool, *common.Account, error) {
472 // ZKInputs
473 if tp.zki != nil {
474 // Txs
475 var err error
476 tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
477 if err != nil {
478 log.Error(err)
479 return nil, nil, false, nil, tracerr.Wrap(err)
480 }
481 tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
482 tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
483 tp.zki.OnChain[tp.i] = big.NewInt(1)
484
485 // L1Txs
486 depositAmountF16, err := common.NewFloat16(tx.DepositAmount)
487 if err != nil {
488 return nil, nil, false, nil, tracerr.Wrap(err)
489 }
490 tp.zki.DepositAmountF[tp.i] = big.NewInt(int64(depositAmountF16))
491 tp.zki.FromEthAddr[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
492 if tx.FromBJJ != common.EmptyBJJComp {
493 tp.zki.FromBJJCompressed[tp.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
494 }
495
496 // Intermediate States, for all the transactions except for the last one
497 if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
498 tp.zki.ISOnChain[tp.i] = big.NewInt(1)
499 }
500 }
501
502 switch tx.Type {
503 case common.TxTypeForceTransfer:
504 tp.computeEffectiveAmounts(tx)
505
506 // go to the MT account of sender and receiver, and update balance
507 // & nonce
508
509 // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees.
510 // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in
511 // the Deposit type case.
512 err := tp.applyTransfer(nil, nil, tx.Tx(), 0)
513 if err != nil {
514 log.Error(err)
515 return nil, nil, false, nil, tracerr.Wrap(err)
516 }
517 case common.TxTypeCreateAccountDeposit:
518 tp.computeEffectiveAmounts(tx)
519
520 // add new account to the MT, update balance of the MT account
521 err := tp.applyCreateAccount(tx)
522 if err != nil {
523 log.Error(err)
524 return nil, nil, false, nil, tracerr.Wrap(err)
525 }
526 // TODO applyCreateAccount will return the created account,
527 // which in the case type==TypeSynchronizer will be added to an
528 // array of created accounts that will be returned
529 case common.TxTypeDeposit:
530 tp.computeEffectiveAmounts(tx)
531
532 // update balance of the MT account
533 err := tp.applyDeposit(tx, false)
534 if err != nil {
535 log.Error(err)
536 return nil, nil, false, nil, tracerr.Wrap(err)
537 }
538 case common.TxTypeDepositTransfer:
539 tp.computeEffectiveAmounts(tx)
540
541 // update balance in MT account, update balance & nonce of sender
542 // & receiver
543 err := tp.applyDeposit(tx, true)
544 if err != nil {
545 log.Error(err)
546 return nil, nil, false, nil, tracerr.Wrap(err)
547 }
548 case common.TxTypeCreateAccountDepositTransfer:
549 tp.computeEffectiveAmounts(tx)
550
551 // add new account to the merkletree, update balance in MT account,
552 // update balance & nonce of sender & receiver
553 err := tp.applyCreateAccountDepositTransfer(tx)
554 if err != nil {
555 log.Error(err)
556 return nil, nil, false, nil, tracerr.Wrap(err)
557 }
558 case common.TxTypeForceExit:
559 tp.computeEffectiveAmounts(tx)
560
561 // execute exit flow
562 // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
563 exitAccount, newExit, err := tp.applyExit(nil, nil, exitTree, tx.Tx())
564 if err != nil {
565 log.Error(err)
566 return nil, nil, false, nil, tracerr.Wrap(err)
567 }
568 return &tx.FromIdx, exitAccount, newExit, nil, nil
569 default:
570 }
571
572 var createdAccount *common.Account
573 if tp.s.Typ == statedb.TypeSynchronizer &&
574 (tx.Type == common.TxTypeCreateAccountDeposit ||
575 tx.Type == common.TxTypeCreateAccountDepositTransfer) {
576 var err error
577 createdAccount, err = tp.s.GetAccount(tp.s.CurrentIdx())
578 if err != nil {
579 log.Error(err)
580 return nil, nil, false, nil, tracerr.Wrap(err)
581 }
582 }
583
584 return nil, nil, false, createdAccount, nil
585}
586
587// ProcessL2Tx process the given L2Tx applying the needed updates to the
588// StateDB depending on the transaction Type. It returns the 3 parameters
589// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
590// the Exit created a new Leaf in the ExitTree.
591func (tp *TxProcessor) ProcessL2Tx(coordIdxsMap map[common.TokenID]common.Idx,
592 collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
593 tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
594 var err error
595 // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
596 if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
597 if tp.s.Typ == statedb.TypeSynchronizer {
598 // this should never be reached
599 log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
600 return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
601 }
602 // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
603
604 accSender, err := tp.s.GetAccount(tx.FromIdx)
605 if err != nil {
606 return nil, nil, false, tracerr.Wrap(err)
607 }
608 tx.AuxToIdx, err = tp.s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, accSender.TokenID)
609 if err != nil {
610 return nil, nil, false, tracerr.Wrap(err)
611 }
612 }
613
614 // ZKInputs
615 if tp.zki != nil {
616 // Txs
617 tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
618 if err != nil {
619 return nil, nil, false, tracerr.Wrap(err)
620 }
621 tp.zki.TxCompressedDataV2[tp.i], err = tx.TxCompressedDataV2()
622 if err != nil {
623 return nil, nil, false, tracerr.Wrap(err)
624 }
625 tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
626 tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
627
628 // fill AuxToIdx if needed
629 if tx.ToIdx == 0 {
630 // use toIdx that can have been filled by tx.ToIdx or
631 // if tx.Idx==0 (this case), toIdx is filled by the Idx
632 // from db by ToEthAddr&ToBJJ
633 tp.zki.AuxToIdx[tp.i] = tx.AuxToIdx.BigInt()
634 }
635
636 if tx.ToBJJ != common.EmptyBJJComp {
637 _, tp.zki.ToBJJAy[tp.i] = babyjub.UnpackSignY(tx.ToBJJ)
638 }
639 tp.zki.ToEthAddr[tp.i] = common.EthAddrToBigInt(tx.ToEthAddr)
640
641 tp.zki.OnChain[tp.i] = big.NewInt(0)
642 tp.zki.NewAccount[tp.i] = big.NewInt(0)
643
644 // L2Txs
645 // tp.zki.RqOffset[tp.i] = // TODO Rq once TxSelector is ready
646 // tp.zki.RqTxCompressedDataV2[tp.i] = // TODO
647 // tp.zki.RqToEthAddr[tp.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
648 // tp.zki.RqToBJJAy[tp.i] = tx.ToBJJ.Y // TODO
649
650 signature, err := tx.Signature.Decompress()
651 if err != nil {
652 log.Error(err)
653 return nil, nil, false, tracerr.Wrap(err)
654 }
655 tp.zki.S[tp.i] = signature.S
656 tp.zki.R8x[tp.i] = signature.R8.X
657 tp.zki.R8y[tp.i] = signature.R8.Y
658 }
659
660 // if StateDB type==TypeSynchronizer, will need to add Nonce
661 if tp.s.Typ == statedb.TypeSynchronizer {
662 // as type==TypeSynchronizer, always tx.ToIdx!=0
663 acc, err := tp.s.GetAccount(tx.FromIdx)
664 if err != nil {
665 log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
666 return nil, nil, false, tracerr.Wrap(err)
667 }
668 tx.Nonce = acc.Nonce
669 tx.TokenID = acc.TokenID
670 }
671
672 switch tx.Type {
673 case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
674 // go to the MT account of sender and receiver, and update
675 // balance & nonce
676 err = tp.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
677 if err != nil {
678 log.Error(err)
679 return nil, nil, false, tracerr.Wrap(err)
680 }
681 case common.TxTypeExit:
682 // execute exit flow
683 exitAccount, newExit, err := tp.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
684 if err != nil {
685 log.Error(err)
686 return nil, nil, false, tracerr.Wrap(err)
687 }
688 return &tx.FromIdx, exitAccount, newExit, nil
689 default:
690 }
691 return nil, nil, false, nil
692}
693
694// applyCreateAccount creates a new account in the account of the depositer, it
695// stores the deposit value
696func (tp *TxProcessor) applyCreateAccount(tx *common.L1Tx) error {
697 account := &common.Account{
698 TokenID: tx.TokenID,
699 Nonce: 0,
700 Balance: tx.EffectiveDepositAmount,
701 BJJ: tx.FromBJJ,
702 EthAddr: tx.FromEthAddr,
703 }
704
705 p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), account)
706 if err != nil {
707 return tracerr.Wrap(err)
708 }
709 if tp.zki != nil {
710 tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
711 tp.zki.Nonce1[tp.i] = big.NewInt(0)
712 fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
713 if fromBJJSign {
714 tp.zki.Sign1[tp.i] = big.NewInt(1)
715 }
716 tp.zki.Ay1[tp.i] = fromBJJY
717 tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
718 tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
719 tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
720 if p.IsOld0 {
721 tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
722 }
723 tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
724 tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
725
726 tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
727
728 tp.zki.AuxFromIdx[tp.i] = common.Idx(tp.s.CurrentIdx() + 1).BigInt()
729 tp.zki.NewAccount[tp.i] = big.NewInt(1)
730
731 if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
732 // intermediate states
733 tp.zki.ISOnChain[tp.i] = big.NewInt(1)
734 }
735 }
736
737 return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
738}
739
740// applyDeposit updates the balance in the account of the depositer, if
741// andTransfer parameter is set to true, the method will also apply the
742// Transfer of the L1Tx/DepositTransfer
743func (tp *TxProcessor) applyDeposit(tx *common.L1Tx, transfer bool) error {
744 accSender, err := tp.s.GetAccount(tx.FromIdx)
745 if err != nil {
746 return tracerr.Wrap(err)
747 }
748
749 if tp.zki != nil {
750 tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
751 tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
752 senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
753 if senderBJJSign {
754 tp.zki.Sign1[tp.i] = big.NewInt(1)
755 }
756 tp.zki.Ay1[tp.i] = senderBJJY
757 tp.zki.Balance1[tp.i] = accSender.Balance
758 tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
759 }
760
761 // add the deposit to the sender
762 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
763 // subtract amount to the sender
764 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
765
766 // update sender account in localStateDB
767 p, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
768 if err != nil {
769 return tracerr.Wrap(err)
770 }
771 if tp.zki != nil {
772 tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
773 // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
774 }
775
776 // in case that the tx is a L1Tx>DepositTransfer
777 var accReceiver *common.Account
778 if transfer {
779 if tx.ToIdx == tx.FromIdx {
780 accReceiver = accSender
781 } else {
782 accReceiver, err = tp.s.GetAccount(tx.ToIdx)
783 if err != nil {
784 return tracerr.Wrap(err)
785 }
786 }
787
788 if tp.zki != nil {
789 tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
790 tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
791 receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
792 if receiverBJJSign {
793 tp.zki.Sign2[tp.i] = big.NewInt(1)
794 }
795 tp.zki.Ay2[tp.i] = receiverBJJY
796 tp.zki.Balance2[tp.i] = accReceiver.Balance
797 tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
798 }
799
800 // add amount to the receiver
801 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
802
803 // update receiver account in localStateDB
804 p, err := tp.s.UpdateAccount(tx.ToIdx, accReceiver)
805 if err != nil {
806 return tracerr.Wrap(err)
807 }
808 if tp.zki != nil {
809 tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
810 // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
811 }
812 }
813
814 return nil
815}
816
817// applyTransfer updates the balance & nonce in the account of the sender, and
818// the balance in the account of the receiver.
819// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
820// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
821// the receiver. This parameter is used when the tx.ToIdx is not specified and
822// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
823func (tp *TxProcessor) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
824 collectedFees map[common.TokenID]*big.Int, tx common.Tx, auxToIdx common.Idx) error {
825 if auxToIdx == common.Idx(0) {
826 auxToIdx = tx.ToIdx
827 }
828 // get sender and receiver accounts from localStateDB
829 accSender, err := tp.s.GetAccount(tx.FromIdx)
830 if err != nil {
831 log.Error(err)
832 return tracerr.Wrap(err)
833 }
834
835 if tp.zki != nil {
836 // Set the State1 before updating the Sender leaf
837 tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
838 tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
839 senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
840 if senderBJJSign {
841 tp.zki.Sign1[tp.i] = big.NewInt(1)
842 }
843 tp.zki.Ay1[tp.i] = senderBJJY
844 tp.zki.Balance1[tp.i] = accSender.Balance
845 tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
846 }
847 if !tx.IsL1 { // L2
848 // increment nonce
849 accSender.Nonce++
850
851 // compute fee and subtract it from the accSender
852 fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
853 if err != nil {
854 return tracerr.Wrap(err)
855 }
856 feeAndAmount := new(big.Int).Add(tx.Amount, fee)
857 accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
858
859 if _, ok := coordIdxsMap[accSender.TokenID]; ok {
860 accCoord, err := tp.s.GetAccount(coordIdxsMap[accSender.TokenID])
861 if err != nil {
862 return tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", accSender.TokenID, coordIdxsMap[accSender.TokenID]))
863 }
864 // accumulate the fee for the Coord account
865 accumulated := tp.AccumulatedFees[accCoord.Idx]
866 accumulated.Add(accumulated, fee)
867
868 if tp.s.Typ == statedb.TypeSynchronizer ||
869 tp.s.Typ == statedb.TypeBatchBuilder {
870 collected := collectedFees[accCoord.TokenID]
871 collected.Add(collected, fee)
872 }
873 } else {
874 log.Debugw("No coord Idx to receive fee", "tx", tx)
875 }
876 } else {
877 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
878 }
879
880 // update sender account in localStateDB
881 pSender, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
882 if err != nil {
883 log.Error(err)
884 return tracerr.Wrap(err)
885 }
886 if tp.zki != nil {
887 tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(pSender.Siblings)
888 }
889
890 var accReceiver *common.Account
891 if auxToIdx == tx.FromIdx {
892 // if Sender is the Receiver, reuse 'accSender' pointer,
893 // because in the DB the account for 'auxToIdx' won't be
894 // updated yet
895 accReceiver = accSender
896 } else {
897 accReceiver, err = tp.s.GetAccount(auxToIdx)
898 if err != nil {
899 log.Error(err, auxToIdx)
900 return tracerr.Wrap(err)
901 }
902 }
903 if tp.zki != nil {
904 // Set the State2 before updating the Receiver leaf
905 tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
906 tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
907 receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
908 if receiverBJJSign {
909 tp.zki.Sign2[tp.i] = big.NewInt(1)
910 }
911 tp.zki.Ay2[tp.i] = receiverBJJY
912 tp.zki.Balance2[tp.i] = accReceiver.Balance
913 tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
914 }
915
916 // add amount-feeAmount to the receiver
917 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
918
919 // update receiver account in localStateDB
920 pReceiver, err := tp.s.UpdateAccount(auxToIdx, accReceiver)
921 if err != nil {
922 return tracerr.Wrap(err)
923 }
924 if tp.zki != nil {
925 tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(pReceiver.Siblings)
926 }
927
928 return nil
929}
930
931// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
932// makes a deposit, and performs a transfer to another account
933func (tp *TxProcessor) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
934 auxFromIdx := common.Idx(tp.s.CurrentIdx() + 1)
935 accSender := &common.Account{
936 TokenID: tx.TokenID,
937 Nonce: 0,
938 Balance: tx.EffectiveDepositAmount,
939 BJJ: tx.FromBJJ,
940 EthAddr: tx.FromEthAddr,
941 }
942
943 if tp.zki != nil {
944 // Set the State1 before updating the Sender leaf
945 tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
946 tp.zki.Nonce1[tp.i] = big.NewInt(0)
947 fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
948 if fromBJJSign {
949 tp.zki.Sign1[tp.i] = big.NewInt(1)
950 }
951 tp.zki.Ay1[tp.i] = fromBJJY
952 tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
953 tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
954 }
955
956 // subtract amount to the sender
957 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
958
959 // create Account of the Sender
960 p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), accSender)
961 if err != nil {
962 return tracerr.Wrap(err)
963 }
964 if tp.zki != nil {
965 tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
966 if p.IsOld0 {
967 tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
968 }
969 tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
970 tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
971
972 tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
973
974 tp.zki.AuxFromIdx[tp.i] = auxFromIdx.BigInt()
975 tp.zki.NewAccount[tp.i] = big.NewInt(1)
976
977 // intermediate states
978 tp.zki.ISOnChain[tp.i] = big.NewInt(1)
979 }
980 var accReceiver *common.Account
981 if tx.ToIdx == auxFromIdx {
982 accReceiver = accSender
983 } else {
984 accReceiver, err = tp.s.GetAccount(tx.ToIdx)
985 if err != nil {
986 log.Error(err)
987 return tracerr.Wrap(err)
988 }
989 }
990
991 if tp.zki != nil {
992 // Set the State2 before updating the Receiver leaf
993 tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
994 tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
995 receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
996 if receiverBJJSign {
997 tp.zki.Sign2[tp.i] = big.NewInt(1)
998 }
999 tp.zki.Ay2[tp.i] = receiverBJJY
1000 tp.zki.Balance2[tp.i] = accReceiver.Balance
1001 tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
1002 }
1003
1004 // add amount to the receiver
1005 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
1006
1007 // update receiver account in localStateDB
1008 p, err = tp.s.UpdateAccount(tx.ToIdx, accReceiver)
1009 if err != nil {
1010 return tracerr.Wrap(err)
1011 }
1012 if tp.zki != nil {
1013 tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
1014 }
1015
1016 return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
1017}
1018
1019// It returns the ExitAccount and a boolean determining if the Exit created a
1020// new Leaf in the ExitTree.
1021func (tp *TxProcessor) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
1022 collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
1023 tx common.Tx) (*common.Account, bool, error) {
1024 // 0. subtract tx.Amount from current Account in StateMT
1025 // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
1026 acc, err := tp.s.GetAccount(tx.FromIdx)
1027 if err != nil {
1028 return nil, false, tracerr.Wrap(err)
1029 }
1030 if tp.zki != nil {
1031 tp.zki.TokenID1[tp.i] = acc.TokenID.BigInt()
1032 tp.zki.Nonce1[tp.i] = acc.Nonce.BigInt()
1033 accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1034 if accBJJSign {
1035 tp.zki.Sign1[tp.i] = big.NewInt(1)
1036 }
1037 tp.zki.Ay1[tp.i] = accBJJY
1038 tp.zki.Balance1[tp.i] = acc.Balance
1039 tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1040 }
1041
1042 if !tx.IsL1 {
1043 // increment nonce
1044 acc.Nonce++
1045
1046 // compute fee and subtract it from the accSender
1047 fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
1048 if err != nil {
1049 return nil, false, tracerr.Wrap(err)
1050 }
1051 feeAndAmount := new(big.Int).Add(tx.Amount, fee)
1052 acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
1053
1054 if _, ok := coordIdxsMap[acc.TokenID]; ok {
1055 accCoord, err := tp.s.GetAccount(coordIdxsMap[acc.TokenID])
1056 if err != nil {
1057 return nil, false, tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", acc.TokenID, coordIdxsMap[acc.TokenID]))
1058 }
1059
1060 // accumulate the fee for the Coord account
1061 accumulated := tp.AccumulatedFees[accCoord.Idx]
1062 accumulated.Add(accumulated, fee)
1063
1064 if tp.s.Typ == statedb.TypeSynchronizer ||
1065 tp.s.Typ == statedb.TypeBatchBuilder {
1066 collected := collectedFees[accCoord.TokenID]
1067 collected.Add(collected, fee)
1068 }
1069 } else {
1070 log.Debugw("No coord Idx to receive fee", "tx", tx)
1071 }
1072 } else {
1073 acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
1074 }
1075
1076 p, err := tp.s.UpdateAccount(tx.FromIdx, acc)
1077 if err != nil {
1078 return nil, false, tracerr.Wrap(err)
1079 }
1080 if tp.zki != nil {
1081 tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
1082 }
1083
1084 if exitTree == nil {
1085 return nil, false, nil
1086 }
1087 exitAccount, err := statedb.GetAccountInTreeDB(exitTree.DB(), tx.FromIdx)
1088 if tracerr.Unwrap(err) == db.ErrNotFound {
1089 // 1a. if idx does not exist in exitTree:
1090 // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance =
1091 // exitAmount (exitAmount=tx.Amount)
1092 exitAccount := &common.Account{
1093 TokenID: acc.TokenID,
1094 Nonce: common.Nonce(0),
1095 Balance: tx.Amount,
1096 BJJ: acc.BJJ,
1097 EthAddr: acc.EthAddr,
1098 }
1099 if tp.zki != nil {
1100 // Set the State2 before creating the Exit leaf
1101 tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
1102 tp.zki.Nonce2[tp.i] = big.NewInt(0)
1103 accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1104 if accBJJSign {
1105 tp.zki.Sign2[tp.i] = big.NewInt(1)
1106 }
1107 tp.zki.Ay2[tp.i] = accBJJY
1108 tp.zki.Balance2[tp.i] = tx.Amount
1109 tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1110 // as Leaf didn't exist in the ExitTree, set NewExit[i]=1
1111 tp.zki.NewExit[tp.i] = big.NewInt(1)
1112 }
1113 p, err = statedb.CreateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
1114 if err != nil {
1115 return nil, false, tracerr.Wrap(err)
1116 }
1117 if tp.zki != nil {
1118 tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
1119 if p.IsOld0 {
1120 tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
1121 }
1122 tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
1123 tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
1124 tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
1125 }
1126 return exitAccount, true, nil
1127 } else if err != nil {
1128 return exitAccount, false, tracerr.Wrap(err)
1129 }
1130 exitAccount.Nonce = exitAccount.Nonce + 1
1131
1132 // 1b. if idx already exist in exitTree:
1133 if tp.zki != nil {
1134 // Set the State2 before updating the Exit leaf
1135 tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
1136 // increment nonce from existing ExitLeaf
1137 tp.zki.Nonce2[tp.i] = exitAccount.Nonce.BigInt()
1138 accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1139 if accBJJSign {
1140 tp.zki.Sign2[tp.i] = big.NewInt(1)
1141 }
1142 tp.zki.Ay2[tp.i] = accBJJY
1143 tp.zki.Balance2[tp.i] = tx.Amount
1144 tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1145 }
1146
1147 // update account, where account.Balance += exitAmount
1148 exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
1149 p, err = statedb.UpdateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
1150 if err != nil {
1151 return nil, false, tracerr.Wrap(err)
1152 }
1153
1154 if tp.zki != nil {
1155 tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
1156 if p.IsOld0 {
1157 tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
1158 }
1159 tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
1160 tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
1161 }
1162
1163 return exitAccount, false, nil
1164}
1165
1166// computeEffectiveAmounts checks that the L1Tx data is correct
1167func (tp *TxProcessor) computeEffectiveAmounts(tx *common.L1Tx) {
1168 tx.EffectiveAmount = tx.Amount
1169 tx.EffectiveDepositAmount = tx.DepositAmount
1170
1171 if !tx.UserOrigin {
1172 // case where the L1Tx is generated by the Coordinator
1173 tx.EffectiveAmount = big.NewInt(0)
1174 tx.EffectiveDepositAmount = big.NewInt(0)
1175 return
1176 }
1177
1178 if tx.Type == common.TxTypeCreateAccountDeposit {
1179 return
1180 }
1181
1182 if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
1183 // CreateAccountDepositTransfer case
1184 cmp := tx.DepositAmount.Cmp(tx.Amount)
1185 if cmp == -1 { // DepositAmount<Amount
1186 tx.EffectiveAmount = big.NewInt(0)
1187 return
1188 }
1189
1190 // check if tx.TokenID==receiver.TokenID
1191 accReceiver, err := tp.s.GetAccount(tx.ToIdx)
1192 if err != nil {
1193 log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
1194 tx.EffectiveDepositAmount = big.NewInt(0)
1195 tx.EffectiveAmount = big.NewInt(0)
1196 return
1197 }
1198 if tx.TokenID != accReceiver.TokenID {
1199 log.Debugf("EffectiveAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
1200 tx.EffectiveAmount = big.NewInt(0)
1201 return
1202 }
1203 return
1204 }
1205
1206 accSender, err := tp.s.GetAccount(tx.FromIdx)
1207 if err != nil {
1208 log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
1209 tx.EffectiveDepositAmount = big.NewInt(0)
1210 tx.EffectiveAmount = big.NewInt(0)
1211 return
1212 }
1213
1214 // check that tx.TokenID corresponds to the Sender account TokenID
1215 if tx.TokenID != accSender.TokenID {
1216 log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
1217 tx.EffectiveDepositAmount = big.NewInt(0)
1218 tx.EffectiveAmount = big.NewInt(0)
1219 return
1220 }
1221
1222 // check that Sender has enough balance
1223 bal := accSender.Balance
1224 if tx.DepositAmount != nil {
1225 bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
1226 }
1227 cmp := bal.Cmp(tx.Amount)
1228 if cmp == -1 {
1229 log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
1230 tx.EffectiveAmount = big.NewInt(0)
1231 return
1232 }
1233
1234 // check that the tx.FromEthAddr is the same than the EthAddress of the
1235 // Sender
1236 if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
1237 log.Debugf("EffectiveAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of the sender account by the Idx (%s)", tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
1238 tx.EffectiveAmount = big.NewInt(0)
1239 }
1240
1241 if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
1242 // if transfer is Exit type, there are no more checks
1243 return
1244 }
1245
1246 // check that TokenID is the same for Sender & Receiver account
1247 accReceiver, err := tp.s.GetAccount(tx.ToIdx)
1248 if err != nil {
1249 log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
1250 tx.EffectiveDepositAmount = big.NewInt(0)
1251 tx.EffectiveAmount = big.NewInt(0)
1252 return
1253 }
1254 if accSender.TokenID != accReceiver.TokenID {
1255 log.Debugf("EffectiveAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", accSender.TokenID, accReceiver.TokenID)
1256 tx.EffectiveAmount = big.NewInt(0)
1257 return
1258 }
1259 if tx.TokenID != accReceiver.TokenID {
1260 log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
1261 tx.EffectiveAmount = big.NewInt(0)
1262 return
1263 }
1264}