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