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