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