arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/statedb/txprocessors.go
db/statedb/txprocessors.goRaw
  1package statedb
  2
  3import (
  4	"errors"
  5	"io/ioutil"
  6	"math/big"
  7	"os"
  8
  9	"github.com/hermeznetwork/hermez-node/common"
 10	"github.com/hermeznetwork/hermez-node/log"
 11	"github.com/iden3/go-iden3-crypto/babyjub"
 12	"github.com/iden3/go-merkletree"
 13	"github.com/iden3/go-merkletree/db"
 14	"github.com/iden3/go-merkletree/db/pebble"
 15)
 16
 17var (
 18	// keyidx is used as key in the db to store the current Idx
 19	keyidx = []byte("k:idx")
 20)
 21
 22func (s *StateDB) resetZKInputs() {
 23	s.zki = nil
 24	s.i = 0 // initialize current transaction index in the ZKInputs generation
 25}
 26
 27type processedExit struct {
 28	exit    bool
 29	newExit bool
 30	idx     common.Idx
 31	acc     common.Account
 32}
 33
 34// ProcessTxOutput contains the output of the ProcessTxs method
 35type ProcessTxOutput struct {
 36	ZKInputs           *common.ZKInputs
 37	ExitInfos          []common.ExitInfo
 38	CreatedAccounts    []common.Account
 39	CoordinatorIdxsMap map[common.TokenID]common.Idx
 40	CollectedFees      map[common.TokenID]*big.Int
 41}
 42
 43// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
 44// the StateDB depending on the transaction Type.  If StateDB
 45// type==TypeBatchBuilder, returns the common.ZKInputs to generate the
 46// SnarkProof later used by the BatchBuilder.  If StateDB
 47// type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
 48// returns common.ExitTreeLeaf that is later used by the Synchronizer to update
 49// the HistoryDB, and adds Nonce & TokenID to the L2Txs.
 50// And if TypeSynchronizer returns an array of common.Account with all the
 51// created accounts.
 52func (s *StateDB) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) (*ProcessTxOutput, error) {
 53	var err error
 54	var exitTree *merkletree.MerkleTree
 55	var createdAccounts []common.Account
 56
 57	if s.zki != nil {
 58		return nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
 59	}
 60	defer s.resetZKInputs()
 61
 62	nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
 63	if nTx == 0 {
 64		// TODO return ZKInputs of batch without txs
 65		return &ProcessTxOutput{
 66			ZKInputs:           nil,
 67			ExitInfos:          nil,
 68			CreatedAccounts:    nil,
 69			CoordinatorIdxsMap: nil,
 70			CollectedFees:      nil,
 71		}, nil
 72	}
 73	exits := make([]processedExit, nTx)
 74
 75	// get TokenIDs of coordIdxs
 76	coordIdxsMap, err := s.getTokenIDsFromIdxs(coordIdxs)
 77	if err != nil {
 78		return nil, err
 79	}
 80
 81	var collectedFees map[common.TokenID]*big.Int
 82	if s.typ == TypeSynchronizer {
 83		collectedFees = make(map[common.TokenID]*big.Int)
 84		for tokenID := range coordIdxsMap {
 85			collectedFees[tokenID] = big.NewInt(0)
 86		}
 87	}
 88
 89	if s.typ == TypeBatchBuilder {
 90		maxFeeTx := 2 // TODO this value will be a parameter
 91		s.zki = common.NewZKInputs(nTx, maxFeeTx, s.mt.MaxLevels())
 92		s.zki.OldLastIdx = (s.idx - 1).BigInt()
 93		s.zki.OldStateRoot = s.mt.Root().BigInt()
 94	}
 95
 96	// TBD if ExitTree is only in memory or stored in disk, for the moment
 97	// only needed in memory
 98	if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
 99		tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
100		if err != nil {
101			return nil, err
102		}
103		defer func() {
104			if err := os.RemoveAll(tmpDir); err != nil {
105				log.Errorw("Deleting statedb temp exit tree", "err", err)
106			}
107		}()
108		sto, err := pebble.NewPebbleStorage(tmpDir, false)
109		if err != nil {
110			return nil, err
111		}
112		exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels())
113		if err != nil {
114			return nil, err
115		}
116	}
117
118	// assumption: l1usertx are sorted by L1Tx.Position
119	for i := 0; i < len(l1usertxs); i++ {
120		exitIdx, exitAccount, newExit, createdAccount, err := s.processL1Tx(exitTree, &l1usertxs[i])
121		if err != nil {
122			return nil, err
123		}
124		if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
125			if exitIdx != nil && exitTree != nil {
126				exits[s.i] = processedExit{
127					exit:    true,
128					newExit: newExit,
129					idx:     *exitIdx,
130					acc:     *exitAccount,
131				}
132			}
133			s.i++
134		}
135		if s.typ == TypeSynchronizer && createdAccount != nil {
136			createdAccounts = append(createdAccounts, *createdAccount)
137		}
138	}
139	for i := 0; i < len(l1coordinatortxs); i++ {
140		exitIdx, _, _, createdAccount, err := s.processL1Tx(exitTree, &l1coordinatortxs[i])
141		if err != nil {
142			return nil, err
143		}
144		if exitIdx != nil {
145			log.Error("Unexpected Exit in L1CoordinatorTx")
146		}
147		if s.typ == TypeSynchronizer && createdAccount != nil {
148			createdAccounts = append(createdAccounts, *createdAccount)
149		}
150	}
151	for i := 0; i < len(l2txs); i++ {
152		exitIdx, exitAccount, newExit, err := s.processL2Tx(coordIdxsMap, collectedFees, exitTree, &l2txs[i])
153		if err != nil {
154			return nil, err
155		}
156		if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
157			if exitIdx != nil && exitTree != nil {
158				exits[s.i] = processedExit{
159					exit:    true,
160					newExit: newExit,
161					idx:     *exitIdx,
162					acc:     *exitAccount,
163				}
164			}
165			s.i++
166		}
167	}
168
169	if s.typ == TypeTxSelector {
170		return nil, nil
171	}
172
173	// once all txs processed (exitTree root frozen), for each Exit,
174	// generate common.ExitInfo data
175	var exitInfos []common.ExitInfo
176	// exitInfos := []common.ExitInfo{}
177	for i := 0; i < nTx; i++ {
178		if !exits[i].exit {
179			continue
180		}
181		exitIdx := exits[i].idx
182		exitAccount := exits[i].acc
183
184		// 0. generate MerkleProof
185		p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
186		if err != nil {
187			return nil, err
188		}
189		// 1. generate common.ExitInfo
190		ei := common.ExitInfo{
191			AccountIdx:  exitIdx,
192			MerkleProof: p,
193			Balance:     exitAccount.Balance,
194		}
195		exitInfos = append(exitInfos, ei)
196
197		if s.zki != nil {
198			s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
199			s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
200			if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
201				s.zki.Sign2[i] = big.NewInt(1)
202			}
203			s.zki.Ay2[i] = exitAccount.PublicKey.Y
204			s.zki.Balance2[i] = exitAccount.Balance
205			s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
206			for j := 0; j < len(p.Siblings); j++ {
207				s.zki.Siblings2[i][j] = p.Siblings[j].BigInt()
208			}
209			if exits[i].newExit {
210				s.zki.NewExit[i] = big.NewInt(1)
211			}
212			if p.IsOld0 {
213				s.zki.IsOld0_2[i] = big.NewInt(1)
214			}
215			s.zki.OldKey2[i] = p.OldKey.BigInt()
216			s.zki.OldValue2[i] = p.OldValue.BigInt()
217		}
218	}
219	if s.typ == TypeSynchronizer {
220		// return exitInfos, createdAccounts and collectedFees, so Synchronizer will
221		// be able to store it into HistoryDB for the concrete BatchNum
222		return &ProcessTxOutput{
223			ZKInputs:           nil,
224			ExitInfos:          exitInfos,
225			CreatedAccounts:    createdAccounts,
226			CoordinatorIdxsMap: coordIdxsMap,
227			CollectedFees:      collectedFees,
228		}, nil
229	}
230
231	// compute last ZKInputs parameters
232	s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
233	// zki.FeeIdxs = ? // TODO, this will be get from the config file
234	tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
235	if err != nil {
236		log.Error(err)
237		return nil, err
238	}
239	s.zki.FeePlanTokens = tokenIDs
240
241	// s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
242
243	// TODO once the Node Config sets the Accounts where to send the Fees
244	// compute fees & update ZKInputs
245
246	// return ZKInputs as the BatchBuilder will return it to forge the Batch
247	return &ProcessTxOutput{
248		ZKInputs:           s.zki,
249		ExitInfos:          nil,
250		CreatedAccounts:    nil,
251		CoordinatorIdxsMap: coordIdxsMap,
252		CollectedFees:      nil,
253	}, nil
254}
255
256// getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
257func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
258	tokenIDs := make(map[common.TokenID]bool)
259	for i := 0; i < len(l1usertxs); i++ {
260		tokenIDs[l1usertxs[i].TokenID] = true
261	}
262	for i := 0; i < len(l1coordinatortxs); i++ {
263		tokenIDs[l1coordinatortxs[i].TokenID] = true
264	}
265	for i := 0; i < len(l2txs); i++ {
266		// as L2Tx does not have parameter TokenID, get it from the
267		// AccountsDB (in the StateDB)
268		acc, err := s.GetAccount(l2txs[i].FromIdx)
269		if err != nil {
270			log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error())
271			return nil, err
272		}
273		tokenIDs[acc.TokenID] = true
274	}
275	var tBI []*big.Int
276	for t := range tokenIDs {
277		tBI = append(tBI, t.BigInt())
278	}
279	return tBI, nil
280}
281
282// processL1Tx process the given L1Tx applying the needed updates to the
283// StateDB depending on the transaction Type. It returns the 3 parameters
284// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
285// the Exit created a new Leaf in the ExitTree.
286// And another *common.Account parameter which contains the created account in
287// case that has been a new created account and that the StateDB is of type
288// TypeSynchronizer.
289func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
290	// ZKInputs
291	if s.zki != nil {
292		// Txs
293		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
294		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
295		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
296		s.zki.OnChain[s.i] = big.NewInt(1)
297
298		// L1Txs
299		s.zki.LoadAmountF[s.i] = tx.LoadAmount
300		s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
301		if tx.FromBJJ != nil {
302			s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
303		}
304
305		// Intermediate States, for all the transactions except for the last one
306		if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
307			s.zki.ISOnChain[s.i] = big.NewInt(1)
308		}
309	}
310
311	switch tx.Type {
312	case common.TxTypeForceTransfer:
313		// go to the MT account of sender and receiver, and update balance
314		// & nonce
315
316		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
317		// 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
318		err := s.applyTransfer(nil, nil, tx.Tx(), 0)
319		if err != nil {
320			log.Error(err)
321			return nil, nil, false, nil, err
322		}
323	case common.TxTypeCreateAccountDeposit:
324		// add new account to the MT, update balance of the MT account
325		err := s.applyCreateAccount(tx)
326		if err != nil {
327			log.Error(err)
328			return nil, nil, false, nil, err
329		}
330		// TODO applyCreateAccount will return the created account,
331		// which in the case type==TypeSynchronizer will be added to an
332		// array of created accounts that will be returned
333
334		if s.zki != nil {
335			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
336			s.zki.NewAccount[s.i] = big.NewInt(1)
337		}
338	case common.TxTypeDeposit:
339		// update balance of the MT account
340		err := s.applyDeposit(tx, false)
341		if err != nil {
342			log.Error(err)
343			return nil, nil, false, nil, err
344		}
345	case common.TxTypeDepositTransfer:
346		// update balance in MT account, update balance & nonce of sender
347		// & receiver
348		err := s.applyDeposit(tx, true)
349		if err != nil {
350			log.Error(err)
351			return nil, nil, false, nil, err
352		}
353	case common.TxTypeCreateAccountDepositTransfer:
354		// add new account to the merkletree, update balance in MT account,
355		// update balance & nonce of sender & receiver
356		err := s.applyCreateAccountDepositTransfer(tx)
357		if err != nil {
358			log.Error(err)
359			return nil, nil, false, nil, err
360		}
361
362		if s.zki != nil {
363			s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
364			s.zki.NewAccount[s.i] = big.NewInt(1)
365		}
366	case common.TxTypeForceExit:
367		// execute exit flow
368		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
369		exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
370		if err != nil {
371			log.Error(err)
372			return nil, nil, false, nil, err
373		}
374		return &tx.FromIdx, exitAccount, newExit, nil, nil
375	default:
376	}
377
378	var createdAccount *common.Account
379	if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
380		var err error
381		createdAccount, err = s.GetAccount(s.idx)
382		if err != nil {
383			log.Error(err)
384			return nil, nil, false, nil, err
385		}
386	}
387
388	return nil, nil, false, createdAccount, nil
389}
390
391// processL2Tx process the given L2Tx applying the needed updates to the
392// StateDB depending on the transaction Type. It returns the 3 parameters
393// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
394// the Exit created a new Leaf in the ExitTree.
395func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
396	exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
397	var err error
398	// if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
399	if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
400		// case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
401		tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
402		if err != nil {
403			return nil, nil, false, err
404		}
405	}
406
407	// ZKInputs
408	if s.zki != nil {
409		// Txs
410		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
411		// s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
412		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
413		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
414
415		// fill AuxToIdx if needed
416		if tx.ToIdx == 0 {
417			// use toIdx that can have been filled by tx.ToIdx or
418			// if tx.Idx==0 (this case), toIdx is filled by the Idx
419			// from db by ToEthAddr&ToBJJ
420			s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
421		}
422
423		if tx.ToBJJ != nil {
424			s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
425		}
426		s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
427
428		s.zki.OnChain[s.i] = big.NewInt(0)
429		s.zki.NewAccount[s.i] = big.NewInt(0)
430
431		// L2Txs
432		// s.zki.RqOffset[s.i] =  // TODO Rq once TxSelector is ready
433		// s.zki.RqTxCompressedDataV2[s.i] = // TODO
434		// s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
435		// s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
436		signature, err := tx.Signature.Decompress()
437		if err != nil {
438			log.Error(err)
439			return nil, nil, false, err
440		}
441		s.zki.S[s.i] = signature.S
442		s.zki.R8x[s.i] = signature.R8.X
443		s.zki.R8y[s.i] = signature.R8.Y
444	}
445
446	// if StateDB type==TypeSynchronizer, will need to add Nonce
447	if s.typ == TypeSynchronizer {
448		// as type==TypeSynchronizer, always tx.ToIdx!=0
449		acc, err := s.GetAccount(tx.FromIdx)
450		if err != nil {
451			log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
452			return nil, nil, false, err
453		}
454		tx.Nonce = acc.Nonce + 1
455		tx.TokenID = acc.TokenID
456	}
457
458	switch tx.Type {
459	case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
460		// go to the MT account of sender and receiver, and update
461		// balance & nonce
462		err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
463		if err != nil {
464			log.Error(err)
465			return nil, nil, false, err
466		}
467	case common.TxTypeExit:
468		// execute exit flow
469		exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
470		if err != nil {
471			log.Error(err)
472			return nil, nil, false, err
473		}
474		return &tx.FromIdx, exitAccount, newExit, nil
475	default:
476	}
477	return nil, nil, false, nil
478}
479
480// applyCreateAccount creates a new account in the account of the depositer, it
481// stores the deposit value
482func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
483	account := &common.Account{
484		TokenID:   tx.TokenID,
485		Nonce:     0,
486		Balance:   tx.LoadAmount,
487		PublicKey: tx.FromBJJ,
488		EthAddr:   tx.FromEthAddr,
489	}
490
491	p, err := s.CreateAccount(common.Idx(s.idx+1), account)
492	if err != nil {
493		return err
494	}
495	if s.zki != nil {
496		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
497		s.zki.Nonce1[s.i] = big.NewInt(0)
498		if babyjub.PointCoordSign(tx.FromBJJ.X) {
499			s.zki.Sign1[s.i] = big.NewInt(1)
500		}
501		s.zki.Ay1[s.i] = tx.FromBJJ.Y
502		s.zki.Balance1[s.i] = tx.LoadAmount
503		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
504		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
505		if p.IsOld0 {
506			s.zki.IsOld0_1[s.i] = big.NewInt(1)
507		}
508		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
509		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
510	}
511
512	s.idx = s.idx + 1
513	return s.setIdx(s.idx)
514}
515
516// applyDeposit updates the balance in the account of the depositer, if
517// andTransfer parameter is set to true, the method will also apply the
518// Transfer of the L1Tx/DepositTransfer
519func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
520	// deposit the tx.LoadAmount into the sender account
521	accSender, err := s.GetAccount(tx.FromIdx)
522	if err != nil {
523		return err
524	}
525	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
526
527	// in case that the tx is a L1Tx>DepositTransfer
528	var accReceiver *common.Account
529	if transfer {
530		accReceiver, err = s.GetAccount(tx.ToIdx)
531		if err != nil {
532			return err
533		}
534		// subtract amount to the sender
535		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
536		// add amount to the receiver
537		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
538	}
539	// update sender account in localStateDB
540	p, err := s.UpdateAccount(tx.FromIdx, accSender)
541	if err != nil {
542		return err
543	}
544	if s.zki != nil {
545		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
546		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
547		if babyjub.PointCoordSign(accSender.PublicKey.X) {
548			s.zki.Sign1[s.i] = big.NewInt(1)
549		}
550		s.zki.Ay1[s.i] = accSender.PublicKey.Y
551		s.zki.Balance1[s.i] = accSender.Balance
552		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
553		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
554		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
555	}
556
557	// this is done after updating Sender Account (depositer)
558	if transfer {
559		// update receiver account in localStateDB
560		p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
561		if err != nil {
562			return err
563		}
564		if s.zki != nil {
565			s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
566			s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
567			if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
568				s.zki.Sign2[s.i] = big.NewInt(1)
569			}
570			s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
571			s.zki.Balance2[s.i] = accReceiver.Balance
572			s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
573			s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
574			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
575		}
576	}
577
578	return nil
579}
580
581// applyTransfer updates the balance & nonce in the account of the sender, and
582// the balance in the account of the receiver.
583// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
584// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
585// the receiver. This parameter is used when the tx.ToIdx is not specified and
586// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
587func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
588	tx common.Tx, auxToIdx common.Idx) error {
589	if auxToIdx == common.Idx(0) {
590		auxToIdx = tx.ToIdx
591	}
592	// get sender and receiver accounts from localStateDB
593	accSender, err := s.GetAccount(tx.FromIdx)
594	if err != nil {
595		log.Error(err)
596		return err
597	}
598	accReceiver, err := s.GetAccount(auxToIdx)
599	if err != nil {
600		log.Error(err)
601		return err
602	}
603
604	// increment nonce
605	accSender.Nonce++
606
607	if !tx.IsL1 {
608		// compute fee and subtract it from the accSender
609		fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
610		if err != nil {
611			return err
612		}
613		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
614		accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
615
616		// send the fee to the Idx of the Coordinator for the TokenID
617		accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
618		if err != nil {
619			log.Debugw("No coord Idx to receive fee", "tx", tx)
620		} else {
621			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
622			_, err = s.UpdateAccount(coordIdxsMap[accSender.TokenID], accCoord)
623			if err != nil {
624				log.Error(err)
625				return err
626			}
627			if s.typ == TypeSynchronizer {
628				collected := collectedFees[accSender.TokenID]
629				collected.Add(collected, fee)
630			}
631		}
632	} else {
633		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
634	}
635
636	// add amount-feeAmount to the receiver
637	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
638
639	// update sender account in localStateDB
640	pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
641	if err != nil {
642		log.Error(err)
643		return err
644	}
645	if s.zki != nil {
646		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
647		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
648		if babyjub.PointCoordSign(accSender.PublicKey.X) {
649			s.zki.Sign1[s.i] = big.NewInt(1)
650		}
651		s.zki.Ay1[s.i] = accSender.PublicKey.Y
652		s.zki.Balance1[s.i] = accSender.Balance
653		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
654		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
655	}
656
657	// update receiver account in localStateDB
658	pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
659	if err != nil {
660		return err
661	}
662	if s.zki != nil {
663		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
664		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
665		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
666			s.zki.Sign2[s.i] = big.NewInt(1)
667		}
668		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
669		s.zki.Balance2[s.i] = accReceiver.Balance
670		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
671		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
672	}
673
674	return nil
675}
676
677// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
678// makes a deposit, and performs a transfer to another account
679func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
680	accSender := &common.Account{
681		TokenID:   tx.TokenID,
682		Nonce:     0,
683		Balance:   tx.LoadAmount,
684		PublicKey: tx.FromBJJ,
685		EthAddr:   tx.FromEthAddr,
686	}
687	accReceiver, err := s.GetAccount(tx.ToIdx)
688	if err != nil {
689		return err
690	}
691	// subtract amount to the sender
692	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
693	// add amount to the receiver
694	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
695
696	// create Account of the Sender
697	p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
698	if err != nil {
699		return err
700	}
701	if s.zki != nil {
702		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
703		s.zki.Nonce1[s.i] = big.NewInt(0)
704		if babyjub.PointCoordSign(tx.FromBJJ.X) {
705			s.zki.Sign1[s.i] = big.NewInt(1)
706		}
707		s.zki.Ay1[s.i] = tx.FromBJJ.Y
708		s.zki.Balance1[s.i] = tx.LoadAmount
709		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
710		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
711		if p.IsOld0 {
712			s.zki.IsOld0_1[s.i] = big.NewInt(1)
713		}
714		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
715		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
716	}
717
718	// update receiver account in localStateDB
719	p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
720	if err != nil {
721		return err
722	}
723	if s.zki != nil {
724		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
725		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
726		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
727			s.zki.Sign2[s.i] = big.NewInt(1)
728		}
729		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
730		s.zki.Balance2[s.i] = accReceiver.Balance
731		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
732		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
733	}
734
735	s.idx = s.idx + 1
736	return s.setIdx(s.idx)
737}
738
739// It returns the ExitAccount and a boolean determining if the Exit created a
740// new Leaf in the ExitTree.
741func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
742	exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
743	// 0. subtract tx.Amount from current Account in StateMT
744	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
745	acc, err := s.GetAccount(tx.FromIdx)
746	if err != nil {
747		return nil, false, err
748	}
749
750	if !tx.IsL1 {
751		// compute fee and subtract it from the accSender
752		fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
753		if err != nil {
754			return nil, false, err
755		}
756		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
757		acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
758
759		// send the fee to the Idx of the Coordinator for the TokenID
760		accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
761		if err != nil {
762			log.Debugw("No coord Idx to receive fee", "tx", tx)
763		} else {
764			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
765			_, err = s.UpdateAccount(coordIdxsMap[acc.TokenID], accCoord)
766			if err != nil {
767				log.Error(err)
768				return nil, false, err
769			}
770			if s.typ == TypeSynchronizer {
771				collected := collectedFees[acc.TokenID]
772				collected.Add(collected, fee)
773			}
774		}
775	} else {
776		acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
777	}
778
779	p, err := s.UpdateAccount(tx.FromIdx, acc)
780	if err != nil {
781		return nil, false, err
782	}
783	if s.zki != nil {
784		s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
785		s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
786		if babyjub.PointCoordSign(acc.PublicKey.X) {
787			s.zki.Sign1[s.i] = big.NewInt(1)
788		}
789		s.zki.Ay1[s.i] = acc.PublicKey.Y
790		s.zki.Balance1[s.i] = acc.Balance
791		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
792		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
793	}
794
795	if exitTree == nil {
796		return nil, false, nil
797	}
798	exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
799	if err == db.ErrNotFound {
800		// 1a. if idx does not exist in exitTree:
801		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
802		exitAccount := &common.Account{
803			TokenID:   acc.TokenID,
804			Nonce:     common.Nonce(1),
805			Balance:   tx.Amount,
806			PublicKey: acc.PublicKey,
807			EthAddr:   acc.EthAddr,
808		}
809		_, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
810		return exitAccount, true, err
811	} else if err != nil {
812		return exitAccount, false, err
813	}
814
815	// 1b. if idx already exist in exitTree:
816	// update account, where account.Balance += exitAmount
817	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
818	_, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
819	return exitAccount, false, err
820}
821
822// getIdx returns the stored Idx from the localStateDB, which is the last Idx
823// used for an Account in the localStateDB.
824func (s *StateDB) getIdx() (common.Idx, error) {
825	idxBytes, err := s.DB().Get(keyidx)
826	if err == db.ErrNotFound {
827		return 0, nil
828	}
829	if err != nil {
830		return 0, err
831	}
832	return common.IdxFromBytes(idxBytes[:4])
833}
834
835// setIdx stores Idx in the localStateDB
836func (s *StateDB) setIdx(idx common.Idx) error {
837	tx, err := s.DB().NewTx()
838	if err != nil {
839		return err
840	}
841	idxBytes, err := idx.Bytes()
842	if err != nil {
843		return err
844	}
845	err = tx.Put(keyidx, idxBytes[:])
846	if err != nil {
847		return err
848	}
849	if err := tx.Commit(); err != nil {
850		return err
851	}
852	return nil
853}