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