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