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