hermez-node/db/statedb/txprocessors.go
db/statedb/txprocessors.goRaw
1package statedb
2
3import (
4 "errors"
5 "io/ioutil"
6 "math/big"
7 "os"
8
9 "github.com/hermeznetwork/hermez-node/common"
10 "github.com/hermeznetwork/hermez-node/log"
11 "github.com/iden3/go-iden3-crypto/babyjub"
12 "github.com/iden3/go-merkletree"
13 "github.com/iden3/go-merkletree/db"
14 "github.com/iden3/go-merkletree/db/pebble"
15)
16
17var (
18 // keyidx is used as key in the db to store the current Idx
19 keyidx = []byte("k:idx")
20)
21
22func (s *StateDB) resetZKInputs() {
23 s.zki = nil
24 s.i = 0 // initialize current transaction index in the ZKInputs generation
25}
26
27type processedExit struct {
28 exit bool
29 newExit bool
30 idx common.Idx
31 acc common.Account
32}
33
34// ProcessTxOutput contains the output of the ProcessTxs method
35type ProcessTxOutput struct {
36 ZKInputs *common.ZKInputs
37 ExitInfos []common.ExitInfo
38 CreatedAccounts []common.Account
39 CoordinatorIdxsMap map[common.TokenID]common.Idx
40 CollectedFees map[common.TokenID]*big.Int
41}
42
43// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
44// the StateDB depending on the transaction Type. If StateDB
45// type==TypeBatchBuilder, returns the common.ZKInputs to generate the
46// SnarkProof later used by the BatchBuilder. If StateDB
47// type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
48// returns common.ExitTreeLeaf that is later used by the Synchronizer to update
49// the HistoryDB, and adds Nonce & TokenID to the L2Txs.
50// And if TypeSynchronizer returns an array of common.Account with all the
51// created accounts.
52func (s *StateDB) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) (*ProcessTxOutput, error) {
53 var err error
54 var exitTree *merkletree.MerkleTree
55 var createdAccounts []common.Account
56
57 if s.zki != nil {
58 return nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
59 }
60 defer s.resetZKInputs()
61
62 nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
63 if nTx == 0 {
64 // TODO return ZKInputs of batch without txs
65 return &ProcessTxOutput{
66 ZKInputs: nil,
67 ExitInfos: nil,
68 CreatedAccounts: nil,
69 CoordinatorIdxsMap: nil,
70 CollectedFees: nil,
71 }, nil
72 }
73 exits := make([]processedExit, nTx)
74
75 // get TokenIDs of coordIdxs
76 coordIdxsMap, err := s.getTokenIDsFromIdxs(coordIdxs)
77 if err != nil {
78 return nil, err
79 }
80
81 var collectedFees map[common.TokenID]*big.Int
82 if s.typ == TypeSynchronizer {
83 collectedFees = make(map[common.TokenID]*big.Int)
84 for tokenID := range coordIdxsMap {
85 collectedFees[tokenID] = big.NewInt(0)
86 }
87 }
88
89 if s.typ == TypeBatchBuilder {
90 s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function, taken from config file/coordinator call
91 s.zki.OldLastIdx = (s.idx - 1).BigInt()
92 s.zki.OldStateRoot = s.mt.Root().BigInt()
93 }
94
95 // TBD if ExitTree is only in memory or stored in disk, for the moment
96 // only needed in memory
97 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
98 tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
99 if err != nil {
100 return nil, err
101 }
102 defer func() {
103 if err := os.RemoveAll(tmpDir); err != nil {
104 log.Errorw("Deleting statedb temp exit tree", "err", err)
105 }
106 }()
107 sto, err := pebble.NewPebbleStorage(tmpDir, false)
108 if err != nil {
109 return nil, err
110 }
111 exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels())
112 if err != nil {
113 return nil, err
114 }
115 }
116
117 // assumption: l1usertx are sorted by L1Tx.Position
118 for i := 0; i < len(l1usertxs); i++ {
119 exitIdx, exitAccount, newExit, createdAccount, err := s.processL1Tx(exitTree, &l1usertxs[i])
120 if err != nil {
121 return nil, err
122 }
123 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
124 if exitIdx != nil && exitTree != nil {
125 exits[s.i] = processedExit{
126 exit: true,
127 newExit: newExit,
128 idx: *exitIdx,
129 acc: *exitAccount,
130 }
131 }
132 s.i++
133 }
134 if s.typ == TypeSynchronizer && createdAccount != nil {
135 createdAccounts = append(createdAccounts, *createdAccount)
136 }
137 }
138 for i := 0; i < len(l1coordinatortxs); i++ {
139 exitIdx, _, _, createdAccount, err := s.processL1Tx(exitTree, &l1coordinatortxs[i])
140 if err != nil {
141 return nil, err
142 }
143 if exitIdx != nil {
144 log.Error("Unexpected Exit in L1CoordinatorTx")
145 }
146 if s.typ == TypeSynchronizer && createdAccount != nil {
147 createdAccounts = append(createdAccounts, *createdAccount)
148 }
149 }
150 for i := 0; i < len(l2txs); i++ {
151 exitIdx, exitAccount, newExit, err := s.processL2Tx(coordIdxsMap, collectedFees, exitTree, &l2txs[i])
152 if err != nil {
153 return nil, err
154 }
155 if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
156 if exitIdx != nil && exitTree != nil {
157 exits[s.i] = processedExit{
158 exit: true,
159 newExit: newExit,
160 idx: *exitIdx,
161 acc: *exitAccount,
162 }
163 }
164 s.i++
165 }
166 }
167
168 if s.typ == TypeTxSelector {
169 return nil, nil
170 }
171
172 // once all txs processed (exitTree root frozen), for each Exit,
173 // generate common.ExitInfo data
174 var exitInfos []common.ExitInfo
175 // exitInfos := []common.ExitInfo{}
176 for i := 0; i < nTx; i++ {
177 if !exits[i].exit {
178 continue
179 }
180 exitIdx := exits[i].idx
181 exitAccount := exits[i].acc
182
183 // 0. generate MerkleProof
184 p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
185 if err != nil {
186 return nil, err
187 }
188 // 1. generate common.ExitInfo
189 ei := common.ExitInfo{
190 AccountIdx: exitIdx,
191 MerkleProof: p,
192 Balance: exitAccount.Balance,
193 }
194 exitInfos = append(exitInfos, ei)
195
196 if s.zki != nil {
197 s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
198 s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
199 if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
200 s.zki.Sign2[i] = big.NewInt(1)
201 }
202 s.zki.Ay2[i] = exitAccount.PublicKey.Y
203 s.zki.Balance2[i] = exitAccount.Balance
204 s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
205 s.zki.Siblings2[i] = p.Siblings
206 if exits[i].newExit {
207 s.zki.NewExit[i] = big.NewInt(1)
208 }
209 if p.IsOld0 {
210 s.zki.IsOld0_2[i] = big.NewInt(1)
211 }
212 s.zki.OldKey2[i] = p.OldKey.BigInt()
213 s.zki.OldValue2[i] = p.OldValue.BigInt()
214 }
215 }
216 if s.typ == TypeSynchronizer {
217 // return exitInfos, createdAccounts and collectedFees, so Synchronizer will
218 // be able to store it into HistoryDB for the concrete BatchNum
219 return &ProcessTxOutput{
220 ZKInputs: nil,
221 ExitInfos: exitInfos,
222 CreatedAccounts: createdAccounts,
223 CoordinatorIdxsMap: coordIdxsMap,
224 CollectedFees: collectedFees,
225 }, nil
226 }
227
228 // compute last ZKInputs parameters
229 s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
230 // zki.FeeIdxs = ? // TODO, this will be get from the config file
231 tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
232 if err != nil {
233 log.Error(err)
234 return nil, err
235 }
236 s.zki.FeePlanTokens = tokenIDs
237
238 // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
239
240 // TODO once the Node Config sets the Accounts where to send the Fees
241 // compute fees & update ZKInputs
242
243 // return ZKInputs as the BatchBuilder will return it to forge the Batch
244 return &ProcessTxOutput{
245 ZKInputs: s.zki,
246 ExitInfos: nil,
247 CreatedAccounts: nil,
248 CoordinatorIdxsMap: coordIdxsMap,
249 CollectedFees: nil,
250 }, nil
251}
252
253// getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
254func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
255 tokenIDs := make(map[common.TokenID]bool)
256 for i := 0; i < len(l1usertxs); i++ {
257 tokenIDs[l1usertxs[i].TokenID] = true
258 }
259 for i := 0; i < len(l1coordinatortxs); i++ {
260 tokenIDs[l1coordinatortxs[i].TokenID] = true
261 }
262 for i := 0; i < len(l2txs); i++ {
263 // as L2Tx does not have parameter TokenID, get it from the
264 // AccountsDB (in the StateDB)
265 acc, err := s.GetAccount(l2txs[i].FromIdx)
266 if err != nil {
267 log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error())
268 return nil, err
269 }
270 tokenIDs[acc.TokenID] = true
271 }
272 var tBI []*big.Int
273 for t := range tokenIDs {
274 tBI = append(tBI, t.BigInt())
275 }
276 return tBI, nil
277}
278
279// processL1Tx process the given L1Tx applying the needed updates to the
280// StateDB depending on the transaction Type. It returns the 3 parameters
281// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
282// the Exit created a new Leaf in the ExitTree.
283// And another *common.Account parameter which contains the created account in
284// case that has been a new created account and that the StateDB is of type
285// TypeSynchronizer.
286func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
287 // ZKInputs
288 if s.zki != nil {
289 // Txs
290 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
291 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
292 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
293 s.zki.OnChain[s.i] = big.NewInt(1)
294
295 // L1Txs
296 s.zki.LoadAmountF[s.i] = tx.LoadAmount
297 s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
298 if tx.FromBJJ != nil {
299 s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
300 }
301
302 // Intermediate States, for all the transactions except for the last one
303 if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
304 s.zki.ISOnChain[s.i] = big.NewInt(1)
305 }
306 }
307
308 switch tx.Type {
309 case common.TxTypeForceTransfer:
310 // go to the MT account of sender and receiver, and update balance
311 // & nonce
312
313 // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
314 // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
315 err := s.applyTransfer(nil, nil, tx.Tx(), 0)
316 if err != nil {
317 log.Error(err)
318 return nil, nil, false, nil, err
319 }
320 case common.TxTypeCreateAccountDeposit:
321 // add new account to the MT, update balance of the MT account
322 err := s.applyCreateAccount(tx)
323 if err != nil {
324 log.Error(err)
325 return nil, nil, false, nil, err
326 }
327 // TODO applyCreateAccount will return the created account,
328 // which in the case type==TypeSynchronizer will be added to an
329 // array of created accounts that will be returned
330
331 if s.zki != nil {
332 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
333 s.zki.NewAccount[s.i] = big.NewInt(1)
334 }
335 case common.TxTypeDeposit:
336 // update balance of the MT account
337 err := s.applyDeposit(tx, false)
338 if err != nil {
339 log.Error(err)
340 return nil, nil, false, nil, err
341 }
342 case common.TxTypeDepositTransfer:
343 // update balance in MT account, update balance & nonce of sender
344 // & receiver
345 err := s.applyDeposit(tx, true)
346 if err != nil {
347 log.Error(err)
348 return nil, nil, false, nil, err
349 }
350 case common.TxTypeCreateAccountDepositTransfer:
351 // add new account to the merkletree, update balance in MT account,
352 // update balance & nonce of sender & receiver
353 err := s.applyCreateAccountDepositTransfer(tx)
354 if err != nil {
355 log.Error(err)
356 return nil, nil, false, nil, err
357 }
358
359 if s.zki != nil {
360 s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
361 s.zki.NewAccount[s.i] = big.NewInt(1)
362 }
363 case common.TxTypeForceExit:
364 // execute exit flow
365 // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
366 exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
367 if err != nil {
368 log.Error(err)
369 return nil, nil, false, nil, err
370 }
371 return &tx.FromIdx, exitAccount, newExit, nil, nil
372 default:
373 }
374
375 var createdAccount *common.Account
376 if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
377 var err error
378 createdAccount, err = s.GetAccount(s.idx)
379 if err != nil {
380 log.Error(err)
381 return nil, nil, false, nil, err
382 }
383 }
384
385 return nil, nil, false, createdAccount, nil
386}
387
388// processL2Tx process the given L2Tx applying the needed updates to the
389// StateDB depending on the transaction Type. It returns the 3 parameters
390// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
391// the Exit created a new Leaf in the ExitTree.
392func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
393 exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
394 var err error
395 // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
396 if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
397 // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
398 tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
399 if err != nil {
400 return nil, nil, false, err
401 }
402 }
403
404 // ZKInputs
405 if s.zki != nil {
406 // Txs
407 // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
408 // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
409 s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
410 s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
411
412 // fill AuxToIdx if needed
413 if tx.ToIdx == 0 {
414 // use toIdx that can have been filled by tx.ToIdx or
415 // if tx.Idx==0 (this case), toIdx is filled by the Idx
416 // from db by ToEthAddr&ToBJJ
417 s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
418 }
419
420 if tx.ToBJJ != nil {
421 s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
422 }
423 s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
424
425 s.zki.OnChain[s.i] = big.NewInt(0)
426 s.zki.NewAccount[s.i] = big.NewInt(0)
427
428 // L2Txs
429 // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
430 // s.zki.RqTxCompressedDataV2[s.i] = // TODO
431 // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
432 // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
433 signature, err := tx.Signature.Decompress()
434 if err != nil {
435 log.Error(err)
436 return nil, nil, false, err
437 }
438 s.zki.S[s.i] = signature.S
439 s.zki.R8x[s.i] = signature.R8.X
440 s.zki.R8y[s.i] = signature.R8.Y
441 }
442
443 // if StateDB type==TypeSynchronizer, will need to add Nonce
444 if s.typ == TypeSynchronizer {
445 // as type==TypeSynchronizer, always tx.ToIdx!=0
446 acc, err := s.GetAccount(tx.FromIdx)
447 if err != nil {
448 log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
449 return nil, nil, false, err
450 }
451 tx.Nonce = acc.Nonce + 1
452 tx.TokenID = acc.TokenID
453 }
454
455 switch tx.Type {
456 case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
457 // go to the MT account of sender and receiver, and update
458 // balance & nonce
459 err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
460 if err != nil {
461 log.Error(err)
462 return nil, nil, false, err
463 }
464 case common.TxTypeExit:
465 // execute exit flow
466 exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
467 if err != nil {
468 log.Error(err)
469 return nil, nil, false, err
470 }
471 return &tx.FromIdx, exitAccount, newExit, nil
472 default:
473 }
474 return nil, nil, false, nil
475}
476
477// applyCreateAccount creates a new account in the account of the depositer, it
478// stores the deposit value
479func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
480 account := &common.Account{
481 TokenID: tx.TokenID,
482 Nonce: 0,
483 Balance: tx.LoadAmount,
484 PublicKey: tx.FromBJJ,
485 EthAddr: tx.FromEthAddr,
486 }
487
488 p, err := s.CreateAccount(common.Idx(s.idx+1), account)
489 if err != nil {
490 return err
491 }
492 if s.zki != nil {
493 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
494 s.zki.Nonce1[s.i] = big.NewInt(0)
495 if babyjub.PointCoordSign(tx.FromBJJ.X) {
496 s.zki.Sign1[s.i] = big.NewInt(1)
497 }
498 s.zki.Ay1[s.i] = tx.FromBJJ.Y
499 s.zki.Balance1[s.i] = tx.LoadAmount
500 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
501 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
502 if p.IsOld0 {
503 s.zki.IsOld0_1[s.i] = big.NewInt(1)
504 }
505 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
506 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
507 }
508
509 s.idx = s.idx + 1
510 return s.setIdx(s.idx)
511}
512
513// applyDeposit updates the balance in the account of the depositer, if
514// andTransfer parameter is set to true, the method will also apply the
515// Transfer of the L1Tx/DepositTransfer
516func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
517 // deposit the tx.LoadAmount into the sender account
518 accSender, err := s.GetAccount(tx.FromIdx)
519 if err != nil {
520 return err
521 }
522 accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
523
524 // in case that the tx is a L1Tx>DepositTransfer
525 var accReceiver *common.Account
526 if transfer {
527 accReceiver, err = s.GetAccount(tx.ToIdx)
528 if err != nil {
529 return err
530 }
531 // subtract amount to the sender
532 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
533 // add amount to the receiver
534 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
535 }
536 // update sender account in localStateDB
537 p, err := s.UpdateAccount(tx.FromIdx, accSender)
538 if err != nil {
539 return err
540 }
541 if s.zki != nil {
542 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
543 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
544 if babyjub.PointCoordSign(accSender.PublicKey.X) {
545 s.zki.Sign1[s.i] = big.NewInt(1)
546 }
547 s.zki.Ay1[s.i] = accSender.PublicKey.Y
548 s.zki.Balance1[s.i] = accSender.Balance
549 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
550 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
551 // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
552 }
553
554 // this is done after updating Sender Account (depositer)
555 if transfer {
556 // update receiver account in localStateDB
557 p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
558 if err != nil {
559 return err
560 }
561 if s.zki != nil {
562 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
563 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
564 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
565 s.zki.Sign2[s.i] = big.NewInt(1)
566 }
567 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
568 s.zki.Balance2[s.i] = accReceiver.Balance
569 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
570 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
571 // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
572 }
573 }
574
575 return nil
576}
577
578// applyTransfer updates the balance & nonce in the account of the sender, and
579// the balance in the account of the receiver.
580// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
581// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
582// the receiver. This parameter is used when the tx.ToIdx is not specified and
583// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
584func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
585 tx common.Tx, auxToIdx common.Idx) error {
586 if auxToIdx == common.Idx(0) {
587 auxToIdx = tx.ToIdx
588 }
589 // get sender and receiver accounts from localStateDB
590 accSender, err := s.GetAccount(tx.FromIdx)
591 if err != nil {
592 log.Error(err)
593 return err
594 }
595 accReceiver, err := s.GetAccount(auxToIdx)
596 if err != nil {
597 log.Error(err)
598 return err
599 }
600
601 // increment nonce
602 accSender.Nonce++
603
604 if !tx.IsL1 {
605 // compute fee and subtract it from the accSender
606 fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
607 feeAndAmount := new(big.Int).Add(tx.Amount, fee)
608 accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
609
610 // send the fee to the Idx of the Coordinator for the TokenID
611 accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
612 if err != nil {
613 log.Debugw("No coord Idx to receive fee", "tx", tx)
614 } else {
615 accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
616 _, err = s.UpdateAccount(coordIdxsMap[accSender.TokenID], accCoord)
617 if err != nil {
618 log.Error(err)
619 return err
620 }
621 if s.typ == TypeSynchronizer {
622 collected := collectedFees[accSender.TokenID]
623 collected.Add(collected, fee)
624 }
625 }
626 } else {
627 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
628 }
629
630 // add amount-feeAmount to the receiver
631 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
632
633 // update sender account in localStateDB
634 pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
635 if err != nil {
636 log.Error(err)
637 return err
638 }
639 if s.zki != nil {
640 s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
641 s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
642 if babyjub.PointCoordSign(accSender.PublicKey.X) {
643 s.zki.Sign1[s.i] = big.NewInt(1)
644 }
645 s.zki.Ay1[s.i] = accSender.PublicKey.Y
646 s.zki.Balance1[s.i] = accSender.Balance
647 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
648 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
649 }
650
651 // update receiver account in localStateDB
652 pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
653 if err != nil {
654 return err
655 }
656 if s.zki != nil {
657 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
658 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
659 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
660 s.zki.Sign2[s.i] = big.NewInt(1)
661 }
662 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
663 s.zki.Balance2[s.i] = accReceiver.Balance
664 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
665 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
666 }
667
668 return nil
669}
670
671// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
672// makes a deposit, and performs a transfer to another account
673func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
674 accSender := &common.Account{
675 TokenID: tx.TokenID,
676 Nonce: 0,
677 Balance: tx.LoadAmount,
678 PublicKey: tx.FromBJJ,
679 EthAddr: tx.FromEthAddr,
680 }
681 accReceiver, err := s.GetAccount(tx.ToIdx)
682 if err != nil {
683 return err
684 }
685 // subtract amount to the sender
686 accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
687 // add amount to the receiver
688 accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
689
690 // create Account of the Sender
691 p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
692 if err != nil {
693 return err
694 }
695 if s.zki != nil {
696 s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
697 s.zki.Nonce1[s.i] = big.NewInt(0)
698 if babyjub.PointCoordSign(tx.FromBJJ.X) {
699 s.zki.Sign1[s.i] = big.NewInt(1)
700 }
701 s.zki.Ay1[s.i] = tx.FromBJJ.Y
702 s.zki.Balance1[s.i] = tx.LoadAmount
703 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
704 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
705 if p.IsOld0 {
706 s.zki.IsOld0_1[s.i] = big.NewInt(1)
707 }
708 s.zki.OldKey1[s.i] = p.OldKey.BigInt()
709 s.zki.OldValue1[s.i] = p.OldValue.BigInt()
710 }
711
712 // update receiver account in localStateDB
713 p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
714 if err != nil {
715 return err
716 }
717 if s.zki != nil {
718 s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
719 s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
720 if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
721 s.zki.Sign2[s.i] = big.NewInt(1)
722 }
723 s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
724 s.zki.Balance2[s.i] = accReceiver.Balance
725 s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
726 s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
727 }
728
729 s.idx = s.idx + 1
730 return s.setIdx(s.idx)
731}
732
733// It returns the ExitAccount and a boolean determining if the Exit created a
734// new Leaf in the ExitTree.
735func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
736 exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
737 // 0. subtract tx.Amount from current Account in StateMT
738 // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
739 acc, err := s.GetAccount(tx.FromIdx)
740 if err != nil {
741 return nil, false, err
742 }
743
744 if !tx.IsL1 {
745 // compute fee and subtract it from the accSender
746 fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
747 feeAndAmount := new(big.Int).Add(tx.Amount, fee)
748 acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
749
750 // send the fee to the Idx of the Coordinator for the TokenID
751 accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
752 if err != nil {
753 log.Debugw("No coord Idx to receive fee", "tx", tx)
754 } else {
755 accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
756 _, err = s.UpdateAccount(coordIdxsMap[acc.TokenID], accCoord)
757 if err != nil {
758 log.Error(err)
759 return nil, false, err
760 }
761 if s.typ == TypeSynchronizer {
762 collected := collectedFees[acc.TokenID]
763 collected.Add(collected, fee)
764 }
765 }
766 } else {
767 acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
768 }
769
770 p, err := s.UpdateAccount(tx.FromIdx, acc)
771 if err != nil {
772 return nil, false, err
773 }
774 if s.zki != nil {
775 s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
776 s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
777 if babyjub.PointCoordSign(acc.PublicKey.X) {
778 s.zki.Sign1[s.i] = big.NewInt(1)
779 }
780 s.zki.Ay1[s.i] = acc.PublicKey.Y
781 s.zki.Balance1[s.i] = acc.Balance
782 s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
783 s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
784 }
785
786 if exitTree == nil {
787 return nil, false, nil
788 }
789 exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
790 if err == db.ErrNotFound {
791 // 1a. if idx does not exist in exitTree:
792 // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
793 exitAccount := &common.Account{
794 TokenID: acc.TokenID,
795 Nonce: common.Nonce(1),
796 Balance: tx.Amount,
797 PublicKey: acc.PublicKey,
798 EthAddr: acc.EthAddr,
799 }
800 _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
801 return exitAccount, true, err
802 } else if err != nil {
803 return exitAccount, false, err
804 }
805
806 // 1b. if idx already exist in exitTree:
807 // update account, where account.Balance += exitAmount
808 exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
809 _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
810 return exitAccount, false, err
811}
812
813// getIdx returns the stored Idx from the localStateDB, which is the last Idx
814// used for an Account in the localStateDB.
815func (s *StateDB) getIdx() (common.Idx, error) {
816 idxBytes, err := s.DB().Get(keyidx)
817 if err == db.ErrNotFound {
818 return 0, nil
819 }
820 if err != nil {
821 return 0, err
822 }
823 return common.IdxFromBytes(idxBytes[:4])
824}
825
826// setIdx stores Idx in the localStateDB
827func (s *StateDB) setIdx(idx common.Idx) error {
828 tx, err := s.DB().NewTx()
829 if err != nil {
830 return err
831 }
832 idxBytes, err := idx.Bytes()
833 if err != nil {
834 return err
835 }
836 err = tx.Put(keyidx, idxBytes[:])
837 if err != nil {
838 return err
839 }
840 if err := tx.Commit(); err != nil {
841 return err
842 }
843 return nil
844}