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