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