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