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