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