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			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		// TokenID is also not set in the L2Txs from the blockchain
370		// that the Synchronizer works with, but does not need to be
371		// defined because is not used later for the L2Txs processing
372		// (Transfer & Exit)
373	}
374
375	switch tx.Type {
376	case common.TxTypeTransfer:
377		// go to the MT account of sender and receiver, and update
378		// balance & nonce
379		err = s.applyTransfer(tx.Tx(), tx.AuxToIdx)
380		if err != nil {
381			log.Error(err)
382			return nil, nil, false, err
383		}
384	case common.TxTypeExit:
385		// execute exit flow
386		exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
387		if err != nil {
388			log.Error(err)
389			return nil, nil, false, err
390		}
391		return &tx.FromIdx, exitAccount, newExit, nil
392	default:
393	}
394	return nil, nil, false, nil
395}
396
397// applyCreateAccount creates a new account in the account of the depositer, it
398// stores the deposit value
399func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
400	account := &common.Account{
401		TokenID:   tx.TokenID,
402		Nonce:     0,
403		Balance:   tx.LoadAmount,
404		PublicKey: tx.FromBJJ,
405		EthAddr:   tx.FromEthAddr,
406	}
407
408	p, err := s.CreateAccount(common.Idx(s.idx+1), account)
409	if err != nil {
410		return err
411	}
412	if s.zki != nil {
413		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
414		s.zki.Nonce1[s.i] = big.NewInt(0)
415		if babyjub.PointCoordSign(tx.FromBJJ.X) {
416			s.zki.Sign1[s.i] = big.NewInt(1)
417		}
418		s.zki.Ay1[s.i] = tx.FromBJJ.Y
419		s.zki.Balance1[s.i] = tx.LoadAmount
420		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
421		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
422		if p.IsOld0 {
423			s.zki.IsOld0_1[s.i] = big.NewInt(1)
424		}
425		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
426		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
427	}
428
429	s.idx = s.idx + 1
430	return s.setIdx(s.idx)
431}
432
433// applyDeposit updates the balance in the account of the depositer, if
434// andTransfer parameter is set to true, the method will also apply the
435// Transfer of the L1Tx/DepositTransfer
436func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
437	// deposit the tx.LoadAmount into the sender account
438	accSender, err := s.GetAccount(tx.FromIdx)
439	if err != nil {
440		return err
441	}
442	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
443
444	// in case that the tx is a L1Tx>DepositTransfer
445	var accReceiver *common.Account
446	if transfer {
447		accReceiver, err = s.GetAccount(tx.ToIdx)
448		if err != nil {
449			return err
450		}
451		// subtract amount to the sender
452		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
453		// add amount to the receiver
454		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
455	}
456	// update sender account in localStateDB
457	p, err := s.UpdateAccount(tx.FromIdx, accSender)
458	if err != nil {
459		return err
460	}
461	if s.zki != nil {
462		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
463		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
464		if babyjub.PointCoordSign(accSender.PublicKey.X) {
465			s.zki.Sign1[s.i] = big.NewInt(1)
466		}
467		s.zki.Ay1[s.i] = accSender.PublicKey.Y
468		s.zki.Balance1[s.i] = accSender.Balance
469		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
470		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
471		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
472	}
473
474	// this is done after updating Sender Account (depositer)
475	if transfer {
476		// update receiver account in localStateDB
477		p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
478		if err != nil {
479			return err
480		}
481		if s.zki != nil {
482			s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
483			s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
484			if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
485				s.zki.Sign2[s.i] = big.NewInt(1)
486			}
487			s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
488			s.zki.Balance2[s.i] = accReceiver.Balance
489			s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
490			s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
491			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
492		}
493	}
494
495	return nil
496}
497
498// applyTransfer updates the balance & nonce in the account of the sender, and
499// the balance in the account of the receiver.
500// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
501// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
502// the receiver. This parameter is used when the tx.ToIdx is not specified and
503// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
504func (s *StateDB) applyTransfer(tx common.Tx, auxToIdx common.Idx) error {
505	if auxToIdx == common.Idx(0) {
506		auxToIdx = tx.ToIdx
507	}
508	// get sender and receiver accounts from localStateDB
509	accSender, err := s.GetAccount(tx.FromIdx)
510	if err != nil {
511		log.Error(err)
512		return err
513	}
514	accReceiver, err := s.GetAccount(auxToIdx)
515	if err != nil {
516		log.Error(err)
517		return err
518	}
519
520	// increment nonce
521	accSender.Nonce++
522
523	// subtract amount to the sender
524	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
525	// add amount to the receiver
526	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
527
528	// update sender account in localStateDB
529	pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
530	if err != nil {
531		log.Error(err)
532		return err
533	}
534	if s.zki != nil {
535		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
536		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
537		if babyjub.PointCoordSign(accSender.PublicKey.X) {
538			s.zki.Sign1[s.i] = big.NewInt(1)
539		}
540		s.zki.Ay1[s.i] = accSender.PublicKey.Y
541		s.zki.Balance1[s.i] = accSender.Balance
542		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
543		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
544	}
545
546	// update receiver account in localStateDB
547	pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
548	if err != nil {
549		return err
550	}
551	if s.zki != nil {
552		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
553		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
554		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
555			s.zki.Sign2[s.i] = big.NewInt(1)
556		}
557		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
558		s.zki.Balance2[s.i] = accReceiver.Balance
559		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
560		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
561	}
562
563	return nil
564}
565
566// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
567// makes a deposit, and performs a transfer to another account
568func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
569	accSender := &common.Account{
570		TokenID:   tx.TokenID,
571		Nonce:     0,
572		Balance:   tx.LoadAmount,
573		PublicKey: tx.FromBJJ,
574		EthAddr:   tx.FromEthAddr,
575	}
576	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
577	accReceiver, err := s.GetAccount(tx.ToIdx)
578	if err != nil {
579		return err
580	}
581	// subtract amount to the sender
582	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
583	// add amount to the receiver
584	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
585
586	// create Account of the Sender
587	p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
588	if err != nil {
589		return err
590	}
591	if s.zki != nil {
592		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
593		s.zki.Nonce1[s.i] = big.NewInt(0)
594		if babyjub.PointCoordSign(tx.FromBJJ.X) {
595			s.zki.Sign1[s.i] = big.NewInt(1)
596		}
597		s.zki.Ay1[s.i] = tx.FromBJJ.Y
598		s.zki.Balance1[s.i] = tx.LoadAmount
599		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
600		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
601		if p.IsOld0 {
602			s.zki.IsOld0_1[s.i] = big.NewInt(1)
603		}
604		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
605		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
606	}
607
608	// update receiver account in localStateDB
609	p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
610	if err != nil {
611		return err
612	}
613	if s.zki != nil {
614		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
615		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
616		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
617			s.zki.Sign2[s.i] = big.NewInt(1)
618		}
619		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
620		s.zki.Balance2[s.i] = accReceiver.Balance
621		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
622		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
623	}
624
625	s.idx = s.idx + 1
626	return s.setIdx(s.idx)
627}
628
629// It returns the ExitAccount and a boolean determining if the Exit created a
630// new Leaf in the ExitTree.
631func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
632	// 0. subtract tx.Amount from current Account in StateMT
633	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
634	acc, err := s.GetAccount(tx.FromIdx)
635	if err != nil {
636		return nil, false, err
637	}
638	acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
639	p, err := s.UpdateAccount(tx.FromIdx, acc)
640	if err != nil {
641		return nil, false, err
642	}
643	if s.zki != nil {
644		s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
645		s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
646		if babyjub.PointCoordSign(acc.PublicKey.X) {
647			s.zki.Sign1[s.i] = big.NewInt(1)
648		}
649		s.zki.Ay1[s.i] = acc.PublicKey.Y
650		s.zki.Balance1[s.i] = acc.Balance
651		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
652		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
653	}
654
655	if exitTree == nil {
656		return nil, false, nil
657	}
658	exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
659	if err == db.ErrNotFound {
660		// 1a. if idx does not exist in exitTree:
661		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
662		exitAccount := &common.Account{
663			TokenID:   acc.TokenID,
664			Nonce:     common.Nonce(1),
665			Balance:   tx.Amount,
666			PublicKey: acc.PublicKey,
667			EthAddr:   acc.EthAddr,
668		}
669		_, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
670		return exitAccount, true, err
671	} else if err != nil {
672		return exitAccount, false, err
673	}
674
675	// 1b. if idx already exist in exitTree:
676	// update account, where account.Balance += exitAmount
677	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
678	_, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
679	return exitAccount, false, err
680}
681
682// getIdx returns the stored Idx from the localStateDB, which is the last Idx
683// used for an Account in the localStateDB.
684func (s *StateDB) getIdx() (common.Idx, error) {
685	idxBytes, err := s.DB().Get(keyidx)
686	if err == db.ErrNotFound {
687		return 0, nil
688	}
689	if err != nil {
690		return 0, err
691	}
692	return common.IdxFromBytes(idxBytes[:4])
693}
694
695// setIdx stores Idx in the localStateDB
696func (s *StateDB) setIdx(idx common.Idx) error {
697	tx, err := s.DB().NewTx()
698	if err != nil {
699		return err
700	}
701	idxBytes, err := idx.Bytes()
702	if err != nil {
703		return err
704	}
705	err = tx.Put(keyidx, idxBytes[:])
706	if err != nil {
707		return err
708	}
709	if err := tx.Commit(); err != nil {
710		return err
711	}
712	return nil
713}