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