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("ToIdx %d not found: %s", l2txs[i].ToIdx, 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			log.Error(err)
401			return nil, nil, false, err
402		}
403	}
404
405	// ZKInputs
406	if s.zki != nil {
407		// Txs
408		// s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
409		// s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
410		s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
411		s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
412
413		// fill AuxToIdx if needed
414		if tx.ToIdx == 0 {
415			// use toIdx that can have been filled by tx.ToIdx or
416			// if tx.Idx==0 (this case), toIdx is filled by the Idx
417			// from db by ToEthAddr&ToBJJ
418			s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
419		}
420
421		if tx.ToBJJ != nil {
422			s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
423		}
424		s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
425
426		s.zki.OnChain[s.i] = big.NewInt(0)
427		s.zki.NewAccount[s.i] = big.NewInt(0)
428
429		// L2Txs
430		// s.zki.RqOffset[s.i] =  // TODO Rq once TxSelector is ready
431		// s.zki.RqTxCompressedDataV2[s.i] = // TODO
432		// s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
433		// s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
434		signature, err := tx.Signature.Decompress()
435		if err != nil {
436			log.Error(err)
437			return nil, nil, false, err
438		}
439		s.zki.S[s.i] = signature.S
440		s.zki.R8x[s.i] = signature.R8.X
441		s.zki.R8y[s.i] = signature.R8.Y
442	}
443
444	// if StateDB type==TypeSynchronizer, will need to add Nonce
445	if s.typ == TypeSynchronizer {
446		// as type==TypeSynchronizer, always tx.ToIdx!=0
447		acc, err := s.GetAccount(tx.FromIdx)
448		if err != nil {
449			log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
450			return nil, nil, false, err
451		}
452		tx.Nonce = acc.Nonce + 1
453		tx.TokenID = acc.TokenID
454	}
455
456	switch tx.Type {
457	case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
458		// go to the MT account of sender and receiver, and update
459		// balance & nonce
460		err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
461		if err != nil {
462			log.Error(err)
463			return nil, nil, false, err
464		}
465	case common.TxTypeExit:
466		// execute exit flow
467		exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
468		if err != nil {
469			log.Error(err)
470			return nil, nil, false, err
471		}
472		return &tx.FromIdx, exitAccount, newExit, nil
473	default:
474	}
475	return nil, nil, false, nil
476}
477
478// applyCreateAccount creates a new account in the account of the depositer, it
479// stores the deposit value
480func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
481	account := &common.Account{
482		TokenID:   tx.TokenID,
483		Nonce:     0,
484		Balance:   tx.LoadAmount,
485		PublicKey: tx.FromBJJ,
486		EthAddr:   tx.FromEthAddr,
487	}
488
489	p, err := s.CreateAccount(common.Idx(s.idx+1), account)
490	if err != nil {
491		return err
492	}
493	if s.zki != nil {
494		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
495		s.zki.Nonce1[s.i] = big.NewInt(0)
496		if babyjub.PointCoordSign(tx.FromBJJ.X) {
497			s.zki.Sign1[s.i] = big.NewInt(1)
498		}
499		s.zki.Ay1[s.i] = tx.FromBJJ.Y
500		s.zki.Balance1[s.i] = tx.LoadAmount
501		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
502		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
503		if p.IsOld0 {
504			s.zki.IsOld0_1[s.i] = big.NewInt(1)
505		}
506		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
507		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
508	}
509
510	s.idx = s.idx + 1
511	return s.setIdx(s.idx)
512}
513
514// applyDeposit updates the balance in the account of the depositer, if
515// andTransfer parameter is set to true, the method will also apply the
516// Transfer of the L1Tx/DepositTransfer
517func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
518	// deposit the tx.LoadAmount into the sender account
519	accSender, err := s.GetAccount(tx.FromIdx)
520	if err != nil {
521		return err
522	}
523	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
524
525	// in case that the tx is a L1Tx>DepositTransfer
526	var accReceiver *common.Account
527	if transfer {
528		accReceiver, err = s.GetAccount(tx.ToIdx)
529		if err != nil {
530			return err
531		}
532		// subtract amount to the sender
533		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
534		// add amount to the receiver
535		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
536	}
537	// update sender account in localStateDB
538	p, err := s.UpdateAccount(tx.FromIdx, accSender)
539	if err != nil {
540		return err
541	}
542	if s.zki != nil {
543		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
544		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
545		if babyjub.PointCoordSign(accSender.PublicKey.X) {
546			s.zki.Sign1[s.i] = big.NewInt(1)
547		}
548		s.zki.Ay1[s.i] = accSender.PublicKey.Y
549		s.zki.Balance1[s.i] = accSender.Balance
550		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
551		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
552		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
553	}
554
555	// this is done after updating Sender Account (depositer)
556	if transfer {
557		// update receiver account in localStateDB
558		p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
559		if err != nil {
560			return err
561		}
562		if s.zki != nil {
563			s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
564			s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
565			if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
566				s.zki.Sign2[s.i] = big.NewInt(1)
567			}
568			s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
569			s.zki.Balance2[s.i] = accReceiver.Balance
570			s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
571			s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
572			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
573		}
574	}
575
576	return nil
577}
578
579// applyTransfer updates the balance & nonce in the account of the sender, and
580// the balance in the account of the receiver.
581// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
582// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
583// the receiver. This parameter is used when the tx.ToIdx is not specified and
584// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
585func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
586	tx common.Tx, auxToIdx common.Idx) error {
587	if auxToIdx == common.Idx(0) {
588		auxToIdx = tx.ToIdx
589	}
590	// get sender and receiver accounts from localStateDB
591	accSender, err := s.GetAccount(tx.FromIdx)
592	if err != nil {
593		log.Error(err)
594		return err
595	}
596	accReceiver, err := s.GetAccount(auxToIdx)
597	if err != nil {
598		log.Error(err)
599		return err
600	}
601
602	// increment nonce
603	accSender.Nonce++
604
605	if !tx.IsL1 {
606		// compute fee and subtract it from the accSender
607		fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
608		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
609		accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
610		// send the fee to the Idx of the Coordinator for the TokenID
611		accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
612		if err != nil {
613			log.Debugw("No coord Idx to receive fee", "tx", tx)
614		} else {
615			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
616			_, err = s.UpdateAccount(coordIdxsMap[accSender.TokenID], accCoord)
617			if err != nil {
618				log.Error(err)
619				return err
620			}
621			if s.typ == TypeSynchronizer {
622				collected := collectedFees[accSender.TokenID]
623				collected.Add(collected, fee)
624			}
625		}
626	}
627
628	// add amount-feeAmount to the receiver
629	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
630
631	// update sender account in localStateDB
632	pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
633	if err != nil {
634		log.Error(err)
635		return err
636	}
637	if s.zki != nil {
638		s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
639		s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
640		if babyjub.PointCoordSign(accSender.PublicKey.X) {
641			s.zki.Sign1[s.i] = big.NewInt(1)
642		}
643		s.zki.Ay1[s.i] = accSender.PublicKey.Y
644		s.zki.Balance1[s.i] = accSender.Balance
645		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
646		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
647	}
648
649	// update receiver account in localStateDB
650	pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
651	if err != nil {
652		return err
653	}
654	if s.zki != nil {
655		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
656		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
657		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
658			s.zki.Sign2[s.i] = big.NewInt(1)
659		}
660		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
661		s.zki.Balance2[s.i] = accReceiver.Balance
662		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
663		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
664	}
665
666	return nil
667}
668
669// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
670// makes a deposit, and performs a transfer to another account
671func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
672	accSender := &common.Account{
673		TokenID:   tx.TokenID,
674		Nonce:     0,
675		Balance:   tx.LoadAmount,
676		PublicKey: tx.FromBJJ,
677		EthAddr:   tx.FromEthAddr,
678	}
679	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
680	accReceiver, err := s.GetAccount(tx.ToIdx)
681	if err != nil {
682		return err
683	}
684	// subtract amount to the sender
685	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
686	// add amount to the receiver
687	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
688
689	// create Account of the Sender
690	p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
691	if err != nil {
692		return err
693	}
694	if s.zki != nil {
695		s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
696		s.zki.Nonce1[s.i] = big.NewInt(0)
697		if babyjub.PointCoordSign(tx.FromBJJ.X) {
698			s.zki.Sign1[s.i] = big.NewInt(1)
699		}
700		s.zki.Ay1[s.i] = tx.FromBJJ.Y
701		s.zki.Balance1[s.i] = tx.LoadAmount
702		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
703		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
704		if p.IsOld0 {
705			s.zki.IsOld0_1[s.i] = big.NewInt(1)
706		}
707		s.zki.OldKey1[s.i] = p.OldKey.BigInt()
708		s.zki.OldValue1[s.i] = p.OldValue.BigInt()
709	}
710
711	// update receiver account in localStateDB
712	p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
713	if err != nil {
714		return err
715	}
716	if s.zki != nil {
717		s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
718		s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
719		if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
720			s.zki.Sign2[s.i] = big.NewInt(1)
721		}
722		s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
723		s.zki.Balance2[s.i] = accReceiver.Balance
724		s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
725		s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
726	}
727
728	s.idx = s.idx + 1
729	return s.setIdx(s.idx)
730}
731
732// It returns the ExitAccount and a boolean determining if the Exit created a
733// new Leaf in the ExitTree.
734func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
735	exitTree *merkletree.MerkleTree, tx common.Tx) (*common.Account, bool, error) {
736	// 0. subtract tx.Amount from current Account in StateMT
737	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
738	acc, err := s.GetAccount(tx.FromIdx)
739	if err != nil {
740		return nil, false, err
741	}
742
743	if !tx.IsL1 {
744		// compute fee and subtract it from the accSender
745		fee := common.CalcFeeAmount(tx.Amount, *tx.Fee)
746		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
747		acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
748
749		// send the fee to the Idx of the Coordinator for the TokenID
750		accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
751		if err != nil {
752			log.Debugw("No coord Idx to receive fee", "tx", tx)
753		} else {
754			accCoord.Balance = new(big.Int).Add(accCoord.Balance, fee)
755			_, err = s.UpdateAccount(coordIdxsMap[acc.TokenID], accCoord)
756			if err != nil {
757				log.Error(err)
758				return nil, false, err
759			}
760			if s.typ == TypeSynchronizer {
761				collected := collectedFees[acc.TokenID]
762				collected.Add(collected, fee)
763			}
764		}
765	}
766
767	p, err := s.UpdateAccount(tx.FromIdx, acc)
768	if err != nil {
769		return nil, false, err
770	}
771	if s.zki != nil {
772		s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
773		s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
774		if babyjub.PointCoordSign(acc.PublicKey.X) {
775			s.zki.Sign1[s.i] = big.NewInt(1)
776		}
777		s.zki.Ay1[s.i] = acc.PublicKey.Y
778		s.zki.Balance1[s.i] = acc.Balance
779		s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
780		s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
781	}
782
783	if exitTree == nil {
784		return nil, false, nil
785	}
786	exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
787	if err == db.ErrNotFound {
788		// 1a. if idx does not exist in exitTree:
789		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
790		exitAccount := &common.Account{
791			TokenID:   acc.TokenID,
792			Nonce:     common.Nonce(1),
793			Balance:   tx.Amount,
794			PublicKey: acc.PublicKey,
795			EthAddr:   acc.EthAddr,
796		}
797		_, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
798		return exitAccount, true, err
799	} else if err != nil {
800		return exitAccount, false, err
801	}
802
803	// 1b. if idx already exist in exitTree:
804	// update account, where account.Balance += exitAmount
805	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
806	_, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
807	return exitAccount, false, err
808}
809
810// getIdx returns the stored Idx from the localStateDB, which is the last Idx
811// used for an Account in the localStateDB.
812func (s *StateDB) getIdx() (common.Idx, error) {
813	idxBytes, err := s.DB().Get(keyidx)
814	if err == db.ErrNotFound {
815		return 0, nil
816	}
817	if err != nil {
818		return 0, err
819	}
820	return common.IdxFromBytes(idxBytes[:4])
821}
822
823// setIdx stores Idx in the localStateDB
824func (s *StateDB) setIdx(idx common.Idx) error {
825	tx, err := s.DB().NewTx()
826	if err != nil {
827		return err
828	}
829	idxBytes, err := idx.Bytes()
830	if err != nil {
831		return err
832	}
833	err = tx.Put(keyidx, idxBytes[:])
834	if err != nil {
835		return err
836	}
837	if err := tx.Commit(); err != nil {
838		return err
839	}
840	return nil
841}