arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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 and createdAccounts, 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		return nil, err
234	}
235	s.zki.FeePlanTokens = tokenIDs
236
237	// s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
238
239	// TODO once the Node Config sets the Accounts where to send the Fees
240	// compute fees & update ZKInputs
241
242	// return ZKInputs as the BatchBuilder will return it to forge the Batch
243	return &ProcessTxOutput{
244		ZKInputs:           s.zki,
245		ExitInfos:          nil,
246		CreatedAccounts:    nil,
247		CoordinatorIdxsMap: coordIdxsMap,
248		CollectedFees:      nil,
249	}, nil
250}
251
252// getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
253func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
254	tokenIDs := make(map[common.TokenID]bool)
255	for i := 0; i < len(l1usertxs); i++ {
256		tokenIDs[l1usertxs[i].TokenID] = true
257	}
258	for i := 0; i < len(l1coordinatortxs); i++ {
259		tokenIDs[l1coordinatortxs[i].TokenID] = true
260	}
261	for i := 0; i < len(l2txs); i++ {
262		// as L2Tx does not have parameter TokenID, get it from the
263		// AccountsDB (in the StateDB)
264		acc, err := s.GetAccount(l2txs[i].ToIdx)
265		if err != nil {
266			return nil, err
267		}
268		tokenIDs[acc.TokenID] = true
269	}
270	var tBI []*big.Int
271	for t := range tokenIDs {
272		tBI = append(tBI, t.BigInt())
273	}
274	return tBI, nil
275}
276
277// processL1Tx process the given L1Tx applying the needed updates to the
278// StateDB depending on the transaction Type. It returns the 3 parameters
279// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
280// the Exit created a new Leaf in the ExitTree.
281// And another *common.Account parameter which contains the created account in
282// case that has been a new created account and that the StateDB is of type
283// TypeSynchronizer.
284func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
285	// ZKInputs
286	if s.zki != nil {
287		// Txs
288		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
289		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
290		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
291		s.zki.OnChain[s.i] = big.NewInt(1)
292
293		// L1Txs
294		s.zki.LoadAmountF[s.i] = tx.LoadAmount
295		s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
296		if tx.FromBJJ != nil {
297			s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
298		}
299
300		// Intermediate States
301		s.zki.ISOnChain[s.i] = big.NewInt(1)
302	}
303
304	switch tx.Type {
305	case common.TxTypeForceTransfer:
306		// go to the MT account of sender and receiver, and update balance
307		// & nonce
308
309		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
310		// 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
311		err := s.applyTransfer(nil, nil, tx.Tx(), 0)
312		if err != nil {
313			log.Error(err)
314			return nil, nil, false, nil, err
315		}
316	case common.TxTypeCreateAccountDeposit:
317		// add new account to the MT, update balance of the MT account
318		err := s.applyCreateAccount(tx)
319		if err != nil {
320			log.Error(err)
321			return nil, nil, false, nil, err
322		}
323		// TODO applyCreateAccount will return the created account,
324		// which in the case type==TypeSynchronizer will be added to an
325		// array of created accounts that will be returned
326
327		if s.zki != nil {
328			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
329			s.zki.NewAccount[s.i] = big.NewInt(1)
330		}
331	case common.TxTypeDeposit:
332		// update balance of the MT account
333		err := s.applyDeposit(tx, false)
334		if err != nil {
335			log.Error(err)
336			return nil, nil, false, nil, err
337		}
338	case common.TxTypeDepositTransfer:
339		// update balance in MT account, update balance & nonce of sender
340		// & receiver
341		err := s.applyDeposit(tx, true)
342		if err != nil {
343			log.Error(err)
344			return nil, nil, false, nil, err
345		}
346	case common.TxTypeCreateAccountDepositTransfer:
347		// add new account to the merkletree, update balance in MT account,
348		// update balance & nonce of sender & receiver
349		err := s.applyCreateAccountDepositTransfer(tx)
350		if err != nil {
351			log.Error(err)
352			return nil, nil, false, nil, err
353		}
354
355		if s.zki != nil {
356			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
357			s.zki.NewAccount[s.i] = big.NewInt(1)
358		}
359	case common.TxTypeForceExit:
360		// execute exit flow
361		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
362		exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
363		if err != nil {
364			log.Error(err)
365			return nil, nil, false, nil, err
366		}
367		return &tx.FromIdx, exitAccount, newExit, nil, nil
368	default:
369	}
370
371	var createdAccount *common.Account
372	if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
373		var err error
374		createdAccount, err = s.GetAccount(s.idx)
375		if err != nil {
376			log.Error(err)
377			return nil, nil, false, nil, err
378		}
379	}
380
381	return nil, nil, false, createdAccount, nil
382}
383
384// processL2Tx process the given L2Tx applying the needed updates to the
385// StateDB depending on the transaction Type. It returns the 3 parameters
386// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
387// the Exit created a new Leaf in the ExitTree.
388func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
389	exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
390	var err error
391	// if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
392	if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
393		// case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
394		tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
395		if err != nil {
396			log.Error(err)
397			return nil, nil, false, err
398		}
399	}
400
401	// ZKInputs
402	if s.zki != nil {
403		// Txs
404		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
405		// s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
406		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
407		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
408
409		// fill AuxToIdx if needed
410		if tx.ToIdx == 0 {
411			// use toIdx that can have been filled by tx.ToIdx or
412			// if tx.Idx==0 (this case), toIdx is filled by the Idx
413			// from db by ToEthAddr&ToBJJ
414			s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
415		}
416
417		if tx.ToBJJ != nil {
418			s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
419		}
420		s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
421
422		s.zki.OnChain[s.i] = big.NewInt(0)
423		s.zki.NewAccount[s.i] = big.NewInt(0)
424
425		// L2Txs
426		// s.zki.RqOffset[s.i] =  // TODO Rq once TxSelector is ready
427		// s.zki.RqTxCompressedDataV2[s.i] = // TODO
428		// s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
429		// s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
430		signature, err := tx.Signature.Decompress()
431		if err != nil {
432			log.Error(err)
433			return nil, nil, false, err
434		}
435		s.zki.S[s.i] = signature.S
436		s.zki.R8x[s.i] = signature.R8.X
437		s.zki.R8y[s.i] = signature.R8.Y
438	}
439
440	// if StateDB type==TypeSynchronizer, will need to add Nonce
441	if s.typ == TypeSynchronizer {
442		// as type==TypeSynchronizer, always tx.ToIdx!=0
443		acc, err := s.GetAccount(tx.FromIdx)
444		if err != nil {
445			log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
446			return nil, nil, false, err
447		}
448		tx.Nonce = acc.Nonce + 1
449		tx.TokenID = acc.TokenID
450	}
451
452	switch tx.Type {
453	case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
454		// go to the MT account of sender and receiver, and update
455		// balance & nonce
456		err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
457		if err != nil {
458			log.Error(err)
459			return nil, nil, false, err
460		}
461	case common.TxTypeExit:
462		// execute exit flow
463		exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
464		if err != nil {
465			log.Error(err)
466			return nil, nil, false, err
467		}
468		return &tx.FromIdx, exitAccount, newExit, nil
469	default:
470	}
471	return nil, nil, false, nil
472}
473
474// applyCreateAccount creates a new account in the account of the depositer, it
475// stores the deposit value
476func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
477	account := &common.Account{
478		TokenID:   tx.TokenID,
479		Nonce:     0,
480		Balance:   tx.LoadAmount,
481		PublicKey: tx.FromBJJ,
482		EthAddr:   tx.FromEthAddr,
483	}
484
485	p, err := s.CreateAccount(common.Idx(s.idx+1), account)
486	if err != nil {
487		return err
488	}
489	if s.zki != nil {
490		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
491		s.zki.Nonce1[s.i] = big.NewInt(0)
492		if babyjub.PointCoordSign(tx.FromBJJ.X) {
493			s.zki.Sign1[s.i] = big.NewInt(1)
494		}
495		s.zki.Ay1[s.i] = tx.FromBJJ.Y
496		s.zki.Balance1[s.i] = tx.LoadAmount
497		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
498		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
499		if p.IsOld0 {
500			s.zki.IsOld0_1[s.i] = big.NewInt(1)
501		}
502		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
503		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
504	}
505
506	s.idx = s.idx + 1
507	return s.setIdx(s.idx)
508}
509
510// applyDeposit updates the balance in the account of the depositer, if
511// andTransfer parameter is set to true, the method will also apply the
512// Transfer of the L1Tx/DepositTransfer
513func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
514	// deposit the tx.LoadAmount into the sender account
515	accSender, err := s.GetAccount(tx.FromIdx)
516	if err != nil {
517		return err
518	}
519	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
520
521	// in case that the tx is a L1Tx>DepositTransfer
522	var accReceiver *common.Account
523	if transfer {
524		accReceiver, err = s.GetAccount(tx.ToIdx)
525		if err != nil {
526			return err
527		}
528		// subtract amount to the sender
529		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
530		// add amount to the receiver
531		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
532	}
533	// update sender account in localStateDB
534	p, err := s.UpdateAccount(tx.FromIdx, accSender)
535	if err != nil {
536		return err
537	}
538	if s.zki != nil {
539		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
540		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
541		if babyjub.PointCoordSign(accSender.PublicKey.X) {
542			s.zki.Sign1[s.i] = big.NewInt(1)
543		}
544		s.zki.Ay1[s.i] = accSender.PublicKey.Y
545		s.zki.Balance1[s.i] = accSender.Balance
546		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
547		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
548		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
549	}
550
551	// this is done after updating Sender Account (depositer)
552	if transfer {
553		// update receiver account in localStateDB
554		p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
555		if err != nil {
556			return err
557		}
558		if s.zki != nil {
559			s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
560			s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
561			if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
562				s.zki.Sign2[s.i] = big.NewInt(1)
563			}
564			s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
565			s.zki.Balance2[s.i] = accReceiver.Balance
566			s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
567			s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
568			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
569		}
570	}
571
572	return nil
573}
574
575// applyTransfer updates the balance & nonce in the account of the sender, and
576// the balance in the account of the receiver.
577// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
578// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
579// the receiver. This parameter is used when the tx.ToIdx is not specified and
580// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
581func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
582	tx common.Tx, auxToIdx common.Idx) error {
583	if auxToIdx == common.Idx(0) {
584		auxToIdx = tx.ToIdx
585	}
586	// get sender and receiver accounts from localStateDB
587	accSender, err := s.GetAccount(tx.FromIdx)
588	if err != nil {
589		log.Error(err)
590		return err
591	}
592	accReceiver, err := s.GetAccount(auxToIdx)
593	if err != nil {
594		log.Error(err)
595		return err
596	}
597
598	// increment nonce
599	accSender.Nonce++
600
601	if !tx.IsL1 {
602		// compute fee and subtract it from the accSender
603		fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
604		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
605		accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
606		// send the fee to the Idx of the Coordinator for the TokenID
607		accCoord, err := s.GetAccount(coordIdxsMap[tx.TokenID])
608		if err != nil {
609			log.Debugw("No coord Idx to receive fee", "tx", tx)
610		} else {
611			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
612			_, err = s.UpdateAccount(coordIdxsMap[tx.TokenID], accCoord)
613			if err != nil {
614				log.Error(err)
615				return err
616			}
617			if s.typ == TypeSynchronizer {
618				collected := collectedFees[tx.TokenID]
619				collected.Add(collected, fee)
620			}
621		}
622	}
623
624	// add amount-feeAmount to the receiver
625	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
626
627	// update sender account in localStateDB
628	pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
629	if err != nil {
630		log.Error(err)
631		return err
632	}
633	if s.zki != nil {
634		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
635		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
636		if babyjub.PointCoordSign(accSender.PublicKey.X) {
637			s.zki.Sign1[s.i] = big.NewInt(1)
638		}
639		s.zki.Ay1[s.i] = accSender.PublicKey.Y
640		s.zki.Balance1[s.i] = accSender.Balance
641		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
642		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
643	}
644
645	// update receiver account in localStateDB
646	pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
647	if err != nil {
648		return err
649	}
650	if s.zki != nil {
651		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
652		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
653		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
654			s.zki.Sign2[s.i] = big.NewInt(1)
655		}
656		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
657		s.zki.Balance2[s.i] = accReceiver.Balance
658		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
659		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
660	}
661
662	return nil
663}
664
665// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
666// makes a deposit, and performs a transfer to another account
667func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
668	accSender := &common.Account{
669		TokenID:   tx.TokenID,
670		Nonce:     0,
671		Balance:   tx.LoadAmount,
672		PublicKey: tx.FromBJJ,
673		EthAddr:   tx.FromEthAddr,
674	}
675	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
676	accReceiver, err := s.GetAccount(tx.ToIdx)
677	if err != nil {
678		return err
679	}
680	// subtract amount to the sender
681	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
682	// add amount to the receiver
683	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
684
685	// create Account of the Sender
686	p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
687	if err != nil {
688		return err
689	}
690	if s.zki != nil {
691		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
692		s.zki.Nonce1[s.i] = big.NewInt(0)
693		if babyjub.PointCoordSign(tx.FromBJJ.X) {
694			s.zki.Sign1[s.i] = big.NewInt(1)
695		}
696		s.zki.Ay1[s.i] = tx.FromBJJ.Y
697		s.zki.Balance1[s.i] = tx.LoadAmount
698		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
699		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
700		if p.IsOld0 {
701			s.zki.IsOld0_1[s.i] = big.NewInt(1)
702		}
703		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
704		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
705	}
706
707	// update receiver account in localStateDB
708	p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
709	if err != nil {
710		return err
711	}
712	if s.zki != nil {
713		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
714		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
715		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
716			s.zki.Sign2[s.i] = big.NewInt(1)
717		}
718		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
719		s.zki.Balance2[s.i] = accReceiver.Balance
720		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
721		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
722	}
723
724	s.idx = s.idx + 1
725	return s.setIdx(s.idx)
726}
727
728// It returns the ExitAccount and a boolean determining if the Exit created a
729// new Leaf in the ExitTree.
730func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
731	exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
732	// 0. subtract tx.Amount from current Account in StateMT
733	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
734	acc, err := s.GetAccount(tx.FromIdx)
735	if err != nil {
736		return nil, false, err
737	}
738
739	if !tx.IsL1 {
740		// compute fee and subtract it from the accSender
741		fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
742		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
743		acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
744
745		// send the fee to the Idx of the Coordinator for the TokenID
746		accCoord, err := s.GetAccount(coordIdxsMap[tx.TokenID])
747		if err != nil {
748			log.Debugw("No coord Idx to receive fee", "tx", tx)
749		} else {
750			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
751			_, err = s.UpdateAccount(coordIdxsMap[tx.TokenID], accCoord)
752			if err != nil {
753				log.Error(err)
754				return nil, false, err
755			}
756			if s.typ == TypeSynchronizer {
757				collected := collectedFees[tx.TokenID]
758				collected.Add(collected, fee)
759			}
760		}
761	}
762
763	p, err := s.UpdateAccount(tx.FromIdx, acc)
764	if err != nil {
765		return nil, false, err
766	}
767	if s.zki != nil {
768		s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
769		s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
770		if babyjub.PointCoordSign(acc.PublicKey.X) {
771			s.zki.Sign1[s.i] = big.NewInt(1)
772		}
773		s.zki.Ay1[s.i] = acc.PublicKey.Y
774		s.zki.Balance1[s.i] = acc.Balance
775		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
776		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
777	}
778
779	if exitTree == nil {
780		return nil, false, nil
781	}
782	exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
783	if err == db.ErrNotFound {
784		// 1a. if idx does not exist in exitTree:
785		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
786		exitAccount := &common.Account{
787			TokenID:   acc.TokenID,
788			Nonce:     common.Nonce(1),
789			Balance:   tx.Amount,
790			PublicKey: acc.PublicKey,
791			EthAddr:   acc.EthAddr,
792		}
793		_, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
794		return exitAccount, true, err
795	} else if err != nil {
796		return exitAccount, false, err
797	}
798
799	// 1b. if idx already exist in exitTree:
800	// update account, where account.Balance += exitAmount
801	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
802	_, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
803	return exitAccount, false, err
804}
805
806// getIdx returns the stored Idx from the localStateDB, which is the last Idx
807// used for an Account in the localStateDB.
808func (s *StateDB) getIdx() (common.Idx, error) {
809	idxBytes, err := s.DB().Get(keyidx)
810	if err == db.ErrNotFound {
811		return 0, nil
812	}
813	if err != nil {
814		return 0, err
815	}
816	return common.IdxFromBytes(idxBytes[:4])
817}
818
819// setIdx stores Idx in the localStateDB
820func (s *StateDB) setIdx(idx common.Idx) error {
821	tx, err := s.DB().NewTx()
822	if err != nil {
823		return err
824	}
825	idxBytes, err := idx.Bytes()
826	if err != nil {
827		return err
828	}
829	err = tx.Put(keyidx, idxBytes[:])
830	if err != nil {
831		return err
832	}
833	if err := tx.Commit(); err != nil {
834		return err
835	}
836	return nil
837}