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("k: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			log.Error(err)
252			return nil, nil, false, err
253		}
254	case common.TxTypeCreateAccountDeposit:
255		// add new account to the MT, update balance of the MT account
256		err := s.applyCreateAccount(tx)
257		if err != nil {
258			log.Error(err)
259			return nil, nil, false, err
260		}
261		// TODO applyCreateAccount will return the created account,
262		// which in the case type==TypeSynchronizer will be added to an
263		// array of created accounts that will be returned
264
265		if s.zki != nil {
266			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
267			s.zki.NewAccount[s.i] = big.NewInt(1)
268		}
269	case common.TxTypeDeposit:
270		// update balance of the MT account
271		err := s.applyDeposit(tx, false)
272		if err != nil {
273			log.Error(err)
274			return nil, nil, false, err
275		}
276	case common.TxTypeDepositTransfer:
277		// update balance in MT account, update balance & nonce of sender
278		// & receiver
279		err := s.applyDeposit(tx, true)
280		if err != nil {
281			log.Error(err)
282			return nil, nil, false, err
283		}
284	case common.TxTypeCreateAccountDepositTransfer:
285		// add new account to the merkletree, update balance in MT account,
286		// update balance & nonce of sender & receiver
287		err := s.applyCreateAccountDepositTransfer(tx)
288		if err != nil {
289			log.Error(err)
290			return nil, nil, false, err
291		}
292
293		if s.zki != nil {
294			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
295			s.zki.NewAccount[s.i] = big.NewInt(1)
296		}
297	case common.TxTypeExit:
298		// execute exit flow
299		exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
300		if err != nil {
301			log.Error(err)
302			return nil, nil, false, err
303		}
304		return &tx.FromIdx, exitAccount, newExit, nil
305	default:
306	}
307
308	return nil, nil, false, nil
309}
310
311// processL2Tx process the given L2Tx applying the needed updates to the
312// StateDB depending on the transaction Type. It returns the 3 parameters
313// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
314// the Exit created a new Leaf in the ExitTree.
315func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
316	var err error
317	// if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
318	if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
319		tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
320		if err != nil {
321			log.Error(err)
322			return nil, nil, false, err
323		}
324	}
325
326	// ZKInputs
327	if s.zki != nil {
328		// Txs
329		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
330		// s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
331		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
332		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
333
334		// fill AuxToIdx if needed
335		if tx.ToIdx == 0 {
336			// use toIdx that can have been filled by tx.ToIdx or
337			// if tx.Idx==0 (this case), toIdx is filled by the Idx
338			// from db by ToEthAddr&ToBJJ
339			s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
340		}
341
342		if tx.ToBJJ != nil {
343			s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
344		}
345		s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
346
347		s.zki.OnChain[s.i] = big.NewInt(0)
348		s.zki.NewAccount[s.i] = big.NewInt(0)
349
350		// L2Txs
351		// s.zki.RqOffset[s.i] =  // TODO Rq once TxSelector is ready
352		// s.zki.RqTxCompressedDataV2[s.i] = // TODO
353		// s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
354		// s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
355		s.zki.S[s.i] = tx.Signature.S
356		s.zki.R8x[s.i] = tx.Signature.R8.X
357		s.zki.R8y[s.i] = tx.Signature.R8.Y
358	}
359
360	// if StateDB type==TypeSynchronizer, will need to add Nonce
361	if s.typ == TypeSynchronizer {
362		// as type==TypeSynchronizer, always tx.ToIdx!=0
363		acc, err := s.GetAccount(tx.FromIdx)
364		if err != nil {
365			log.Error(err)
366			return nil, nil, false, err
367		}
368		tx.Nonce = acc.Nonce
369		tx.TokenID = acc.TokenID
370	}
371
372	switch tx.Type {
373	case common.TxTypeTransfer:
374		// go to the MT account of sender and receiver, and update
375		// balance & nonce
376		err = s.applyTransfer(tx.Tx(), tx.AuxToIdx)
377		if err != nil {
378			log.Error(err)
379			return nil, nil, false, err
380		}
381	case common.TxTypeExit:
382		// execute exit flow
383		exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
384		if err != nil {
385			log.Error(err)
386			return nil, nil, false, err
387		}
388		return &tx.FromIdx, exitAccount, newExit, nil
389	default:
390	}
391	return nil, nil, false, nil
392}
393
394// applyCreateAccount creates a new account in the account of the depositer, it
395// stores the deposit value
396func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
397	account := &common.Account{
398		TokenID:   tx.TokenID,
399		Nonce:     0,
400		Balance:   tx.LoadAmount,
401		PublicKey: tx.FromBJJ,
402		EthAddr:   tx.FromEthAddr,
403	}
404
405	p, err := s.CreateAccount(common.Idx(s.idx+1), account)
406	if err != nil {
407		return err
408	}
409	if s.zki != nil {
410		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
411		s.zki.Nonce1[s.i] = big.NewInt(0)
412		if babyjub.PointCoordSign(tx.FromBJJ.X) {
413			s.zki.Sign1[s.i] = big.NewInt(1)
414		}
415		s.zki.Ay1[s.i] = tx.FromBJJ.Y
416		s.zki.Balance1[s.i] = tx.LoadAmount
417		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
418		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
419		if p.IsOld0 {
420			s.zki.IsOld0_1[s.i] = big.NewInt(1)
421		}
422		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
423		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
424	}
425
426	s.idx = s.idx + 1
427	return s.setIdx(s.idx)
428}
429
430// applyDeposit updates the balance in the account of the depositer, if
431// andTransfer parameter is set to true, the method will also apply the
432// Transfer of the L1Tx/DepositTransfer
433func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
434	// deposit the tx.LoadAmount into the sender account
435	accSender, err := s.GetAccount(tx.FromIdx)
436	if err != nil {
437		return err
438	}
439	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
440
441	// in case that the tx is a L1Tx>DepositTransfer
442	var accReceiver *common.Account
443	if transfer {
444		accReceiver, err = s.GetAccount(tx.ToIdx)
445		if err != nil {
446			return err
447		}
448		// subtract amount to the sender
449		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
450		// add amount to the receiver
451		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
452	}
453	// update sender account in localStateDB
454	p, err := s.UpdateAccount(tx.FromIdx, accSender)
455	if err != nil {
456		return err
457	}
458	if s.zki != nil {
459		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
460		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
461		if babyjub.PointCoordSign(accSender.PublicKey.X) {
462			s.zki.Sign1[s.i] = big.NewInt(1)
463		}
464		s.zki.Ay1[s.i] = accSender.PublicKey.Y
465		s.zki.Balance1[s.i] = accSender.Balance
466		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
467		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
468		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
469	}
470
471	// this is done after updating Sender Account (depositer)
472	if transfer {
473		// update receiver account in localStateDB
474		p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
475		if err != nil {
476			return err
477		}
478		if s.zki != nil {
479			s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
480			s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
481			if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
482				s.zki.Sign2[s.i] = big.NewInt(1)
483			}
484			s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
485			s.zki.Balance2[s.i] = accReceiver.Balance
486			s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
487			s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
488			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
489		}
490	}
491
492	return nil
493}
494
495// applyTransfer updates the balance & nonce in the account of the sender, and
496// the balance in the account of the receiver.
497// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
498// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
499// the receiver. This parameter is used when the tx.ToIdx is not specified and
500// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
501func (s *StateDB) applyTransfer(tx common.Tx, auxToIdx common.Idx) error {
502	if auxToIdx == common.Idx(0) {
503		auxToIdx = tx.ToIdx
504	}
505	// get sender and receiver accounts from localStateDB
506	accSender, err := s.GetAccount(tx.FromIdx)
507	if err != nil {
508		log.Error(err)
509		return err
510	}
511	accReceiver, err := s.GetAccount(auxToIdx)
512	if err != nil {
513		log.Error(err)
514		return err
515	}
516
517	// increment nonce
518	accSender.Nonce++
519
520	// subtract amount to the sender
521	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
522	// add amount to the receiver
523	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
524
525	// update sender account in localStateDB
526	pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
527	if err != nil {
528		log.Error(err)
529		return err
530	}
531	if s.zki != nil {
532		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
533		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
534		if babyjub.PointCoordSign(accSender.PublicKey.X) {
535			s.zki.Sign1[s.i] = big.NewInt(1)
536		}
537		s.zki.Ay1[s.i] = accSender.PublicKey.Y
538		s.zki.Balance1[s.i] = accSender.Balance
539		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
540		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
541	}
542
543	// update receiver account in localStateDB
544	pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
545	if err != nil {
546		return err
547	}
548	if s.zki != nil {
549		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
550		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
551		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
552			s.zki.Sign2[s.i] = big.NewInt(1)
553		}
554		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
555		s.zki.Balance2[s.i] = accReceiver.Balance
556		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
557		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
558	}
559
560	return nil
561}
562
563// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
564// makes a deposit, and performs a transfer to another account
565func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
566	accSender := &common.Account{
567		TokenID:   tx.TokenID,
568		Nonce:     0,
569		Balance:   tx.LoadAmount,
570		PublicKey: tx.FromBJJ,
571		EthAddr:   tx.FromEthAddr,
572	}
573	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
574	accReceiver, err := s.GetAccount(tx.ToIdx)
575	if err != nil {
576		return err
577	}
578	// subtract amount to the sender
579	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
580	// add amount to the receiver
581	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
582
583	// create Account of the Sender
584	p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
585	if err != nil {
586		return err
587	}
588	if s.zki != nil {
589		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
590		s.zki.Nonce1[s.i] = big.NewInt(0)
591		if babyjub.PointCoordSign(tx.FromBJJ.X) {
592			s.zki.Sign1[s.i] = big.NewInt(1)
593		}
594		s.zki.Ay1[s.i] = tx.FromBJJ.Y
595		s.zki.Balance1[s.i] = tx.LoadAmount
596		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
597		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
598		if p.IsOld0 {
599			s.zki.IsOld0_1[s.i] = big.NewInt(1)
600		}
601		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
602		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
603	}
604
605	// update receiver account in localStateDB
606	p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
607	if err != nil {
608		return err
609	}
610	if s.zki != nil {
611		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
612		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
613		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
614			s.zki.Sign2[s.i] = big.NewInt(1)
615		}
616		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
617		s.zki.Balance2[s.i] = accReceiver.Balance
618		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
619		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
620	}
621
622	s.idx = s.idx + 1
623	return s.setIdx(s.idx)
624}
625
626// It returns the ExitAccount and a boolean determining if the Exit created a
627// new Leaf in the ExitTree.
628func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
629	// 0. subtract tx.Amount from current Account in StateMT
630	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
631	acc, err := s.GetAccount(tx.FromIdx)
632	if err != nil {
633		return nil, false, err
634	}
635	acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
636	p, err := s.UpdateAccount(tx.FromIdx, acc)
637	if err != nil {
638		return nil, false, err
639	}
640	if s.zki != nil {
641		s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
642		s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
643		if babyjub.PointCoordSign(acc.PublicKey.X) {
644			s.zki.Sign1[s.i] = big.NewInt(1)
645		}
646		s.zki.Ay1[s.i] = acc.PublicKey.Y
647		s.zki.Balance1[s.i] = acc.Balance
648		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
649		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
650	}
651
652	if exitTree == nil {
653		return nil, false, nil
654	}
655	exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
656	if err == db.ErrNotFound {
657		// 1a. if idx does not exist in exitTree:
658		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
659		exitAccount := &common.Account{
660			TokenID:   acc.TokenID,
661			Nonce:     common.Nonce(1),
662			Balance:   tx.Amount,
663			PublicKey: acc.PublicKey,
664			EthAddr:   acc.EthAddr,
665		}
666		_, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
667		return exitAccount, true, err
668	} else if err != nil {
669		return exitAccount, false, err
670	}
671
672	// 1b. if idx already exist in exitTree:
673	// update account, where account.Balance += exitAmount
674	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
675	_, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
676	return exitAccount, false, err
677}
678
679// getIdx returns the stored Idx from the localStateDB, which is the last Idx
680// used for an Account in the localStateDB.
681func (s *StateDB) getIdx() (common.Idx, error) {
682	idxBytes, err := s.DB().Get(keyidx)
683	if err == db.ErrNotFound {
684		return 0, nil
685	}
686	if err != nil {
687		return 0, err
688	}
689	return common.IdxFromBytes(idxBytes[:4])
690}
691
692// setIdx stores Idx in the localStateDB
693func (s *StateDB) setIdx(idx common.Idx) error {
694	tx, err := s.DB().NewTx()
695	if err != nil {
696		return err
697	}
698	idxBytes, err := idx.Bytes()
699	if err != nil {
700		return err
701	}
702	err = tx.Put(keyidx, idxBytes[:])
703	if err != nil {
704		return err
705	}
706	if err := tx.Commit(); err != nil {
707		return err
708	}
709	return nil
710}