arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/txprocessor/txprocessor.go
txprocessor/txprocessor.goRaw
   1package txprocessor
   2
   3import (
   4	"bytes"
   5	"errors"
   6	"fmt"
   7	"io/ioutil"
   8	"math/big"
   9	"os"
  10
  11	"github.com/hermeznetwork/hermez-node/common"
  12	"github.com/hermeznetwork/hermez-node/db/statedb"
  13	"github.com/hermeznetwork/hermez-node/log"
  14	"github.com/hermeznetwork/tracerr"
  15	"github.com/iden3/go-iden3-crypto/babyjub"
  16	"github.com/iden3/go-merkletree"
  17	"github.com/iden3/go-merkletree/db"
  18	"github.com/iden3/go-merkletree/db/pebble"
  19)
  20
  21// TxProcessor represents the TxProcessor object
  22type TxProcessor struct {
  23	s   *statedb.StateDB
  24	zki *common.ZKInputs
  25	// i is the current transaction index in the ZKInputs generation (zki)
  26	i int
  27	// AccumulatedFees contains the accumulated fees for each token (Coord
  28	// Idx) in the processed batch
  29	AccumulatedFees map[common.Idx]*big.Int
  30	config          Config
  31}
  32
  33// Config contains the TxProcessor configuration parameters
  34type Config struct {
  35	NLevels  uint32
  36	MaxFeeTx uint32
  37	MaxTx    uint32
  38	MaxL1Tx  uint32
  39	ChainID  uint16
  40}
  41
  42type processedExit struct {
  43	exit    bool
  44	newExit bool
  45	idx     common.Idx
  46	acc     common.Account
  47}
  48
  49// ProcessTxOutput contains the output of the ProcessTxs method
  50type ProcessTxOutput struct {
  51	ZKInputs           *common.ZKInputs
  52	ExitInfos          []common.ExitInfo
  53	CreatedAccounts    []common.Account
  54	CoordinatorIdxsMap map[common.TokenID]common.Idx
  55	CollectedFees      map[common.TokenID]*big.Int
  56}
  57
  58// NewTxProcessor returns a new TxProcessor with the given *StateDB & Config
  59func NewTxProcessor(sdb *statedb.StateDB, config Config) *TxProcessor {
  60	return &TxProcessor{
  61		s:      sdb,
  62		zki:    nil,
  63		i:      0,
  64		config: config,
  65	}
  66}
  67
  68// StateDB returns a pointer to the StateDB of the TxProcessor
  69func (tp *TxProcessor) StateDB() *statedb.StateDB {
  70	return tp.s
  71}
  72
  73func (tp *TxProcessor) resetZKInputs() {
  74	tp.zki = nil
  75	tp.i = 0 // initialize current transaction index in the ZKInputs generation
  76}
  77
  78// ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  79// the StateDB depending on the transaction Type.  If StateDB
  80// type==TypeBatchBuilder, returns the common.ZKInputs to generate the
  81// SnarkProof later used by the BatchBuilder.  If StateDB
  82// type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
  83// returns common.ExitTreeLeaf that is later used by the Synchronizer to update
  84// the HistoryDB, and adds Nonce & TokenID to the L2Txs.
  85// And if TypeSynchronizer returns an array of common.Account with all the
  86// created accounts.
  87func (tp *TxProcessor) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx,
  88	l2txs []common.PoolL2Tx) (ptOut *ProcessTxOutput, err error) {
  89	defer func() {
  90		if err == nil {
  91			err = tp.s.MakeCheckpoint()
  92		}
  93	}()
  94
  95	var exitTree *merkletree.MerkleTree
  96	var createdAccounts []common.Account
  97
  98	if tp.zki != nil {
  99		return nil, tracerr.Wrap(errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty"))
 100	}
 101	defer tp.resetZKInputs()
 102
 103	if len(coordIdxs) >= int(tp.config.MaxFeeTx) {
 104		return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), tp.config.MaxFeeTx))
 105	}
 106
 107	nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
 108
 109	if nTx > int(tp.config.MaxTx) {
 110		return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx + L2Tx (%d) can not be bigger than MaxTx (%d)", nTx, tp.config.MaxTx))
 111	}
 112	if len(l1usertxs)+len(l1coordinatortxs) > int(tp.config.MaxL1Tx) {
 113		return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx (%d) can not be bigger than MaxL1Tx (%d)", len(l1usertxs)+len(l1coordinatortxs), tp.config.MaxTx))
 114	}
 115
 116	exits := make([]processedExit, nTx)
 117
 118	if tp.s.Typ == statedb.TypeBatchBuilder {
 119		tp.zki = common.NewZKInputs(tp.config.ChainID, tp.config.MaxTx, tp.config.MaxL1Tx,
 120			tp.config.MaxFeeTx, tp.config.NLevels, (tp.s.CurrentBatch() + 1).BigInt())
 121		tp.zki.OldLastIdx = tp.s.CurrentIdx().BigInt()
 122		tp.zki.OldStateRoot = tp.s.MT.Root().BigInt()
 123		tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx()
 124	}
 125
 126	// TBD if ExitTree is only in memory or stored in disk, for the moment
 127	// is only needed in memory
 128	if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
 129		tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
 130		if err != nil {
 131			return nil, tracerr.Wrap(err)
 132		}
 133		defer func() {
 134			if err := os.RemoveAll(tmpDir); err != nil {
 135				log.Errorw("Deleting statedb temp exit tree", "err", err)
 136			}
 137		}()
 138		sto, err := pebble.NewPebbleStorage(tmpDir, false)
 139		if err != nil {
 140			return nil, tracerr.Wrap(err)
 141		}
 142		defer sto.Close()
 143		exitTree, err = merkletree.NewMerkleTree(sto, tp.s.MT.MaxLevels())
 144		if err != nil {
 145			return nil, tracerr.Wrap(err)
 146		}
 147	}
 148
 149	// Process L1UserTxs
 150	for i := 0; i < len(l1usertxs); i++ {
 151		// assumption: l1usertx are sorted by L1Tx.Position
 152		exitIdx, exitAccount, newExit, createdAccount, err := tp.ProcessL1Tx(exitTree,
 153			&l1usertxs[i])
 154		if err != nil {
 155			return nil, tracerr.Wrap(err)
 156		}
 157		if tp.s.Typ == statedb.TypeSynchronizer {
 158			if createdAccount != nil {
 159				createdAccounts = append(createdAccounts, *createdAccount)
 160				l1usertxs[i].EffectiveFromIdx = createdAccount.Idx
 161			} else {
 162				l1usertxs[i].EffectiveFromIdx = l1usertxs[i].FromIdx
 163			}
 164		}
 165		if tp.zki != nil {
 166			l1TxData, err := l1usertxs[i].BytesGeneric()
 167			if err != nil {
 168				return nil, tracerr.Wrap(err)
 169			}
 170			tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
 171
 172			l1TxDataAvailability, err :=
 173				l1usertxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
 174			if err != nil {
 175				return nil, tracerr.Wrap(err)
 176			}
 177			tp.zki.Metadata.L1TxsDataAvailability =
 178				append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
 179
 180			tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
 181			tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
 182			if exitIdx == nil {
 183				tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
 184			}
 185		}
 186		if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
 187			if exitIdx != nil && exitTree != nil {
 188				exits[tp.i] = processedExit{
 189					exit:    true,
 190					newExit: newExit,
 191					idx:     *exitIdx,
 192					acc:     *exitAccount,
 193				}
 194			}
 195			tp.i++
 196		}
 197	}
 198
 199	// Process L1CoordinatorTxs
 200	for i := 0; i < len(l1coordinatortxs); i++ {
 201		exitIdx, _, _, createdAccount, err := tp.ProcessL1Tx(exitTree, &l1coordinatortxs[i])
 202		if err != nil {
 203			return nil, tracerr.Wrap(err)
 204		}
 205		if exitIdx != nil {
 206			log.Error("Unexpected Exit in L1CoordinatorTx")
 207		}
 208		if tp.s.Typ == statedb.TypeSynchronizer {
 209			if createdAccount != nil {
 210				createdAccounts = append(createdAccounts, *createdAccount)
 211				l1coordinatortxs[i].EffectiveFromIdx = createdAccount.Idx
 212			} else {
 213				l1coordinatortxs[i].EffectiveFromIdx = l1coordinatortxs[i].FromIdx
 214			}
 215		}
 216		if tp.zki != nil {
 217			l1TxData, err := l1coordinatortxs[i].BytesGeneric()
 218			if err != nil {
 219				return nil, tracerr.Wrap(err)
 220			}
 221			tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
 222			l1TxDataAvailability, err :=
 223				l1coordinatortxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
 224			if err != nil {
 225				return nil, tracerr.Wrap(err)
 226			}
 227			tp.zki.Metadata.L1TxsDataAvailability =
 228				append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
 229
 230			tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
 231			tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
 232			tp.i++
 233		}
 234	}
 235
 236	tp.AccumulatedFees = make(map[common.Idx]*big.Int)
 237	for _, idx := range coordIdxs {
 238		tp.AccumulatedFees[idx] = big.NewInt(0)
 239	}
 240
 241	// once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
 242	// coordIdxs. In this way, if a coordIdx uses an Idx that is being
 243	// created in the current batch, at this point the Idx will be created
 244	coordIdxsMap, err := tp.s.GetTokenIDsFromIdxs(coordIdxs)
 245	if err != nil {
 246		return nil, tracerr.Wrap(err)
 247	}
 248	// collectedFees will contain the amount of fee collected for each
 249	// TokenID
 250	var collectedFees map[common.TokenID]*big.Int
 251	if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
 252		collectedFees = make(map[common.TokenID]*big.Int)
 253		for tokenID := range coordIdxsMap {
 254			collectedFees[tokenID] = big.NewInt(0)
 255		}
 256	}
 257
 258	if tp.zki != nil {
 259		// get the feePlanTokens
 260		feePlanTokens, err := tp.getFeePlanTokens(coordIdxs)
 261		if err != nil {
 262			log.Error(err)
 263			return nil, tracerr.Wrap(err)
 264		}
 265		copy(tp.zki.FeePlanTokens, feePlanTokens)
 266	}
 267
 268	// Process L2Txs
 269	for i := 0; i < len(l2txs); i++ {
 270		exitIdx, exitAccount, newExit, err := tp.ProcessL2Tx(coordIdxsMap, collectedFees,
 271			exitTree, &l2txs[i])
 272		if err != nil {
 273			return nil, tracerr.Wrap(err)
 274		}
 275		if tp.zki != nil {
 276			l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(tp.zki.Metadata.NLevels)
 277			if err != nil {
 278				return nil, tracerr.Wrap(err)
 279			}
 280			tp.zki.Metadata.L2TxsData = append(tp.zki.Metadata.L2TxsData, l2TxData)
 281
 282			// Intermediate States
 283			if tp.i < nTx-1 {
 284				tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
 285				tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
 286				tp.zki.ISAccFeeOut[tp.i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
 287				if exitIdx == nil {
 288					tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
 289				}
 290			}
 291		}
 292		if tp.s.Typ == statedb.TypeSynchronizer || tp.s.Typ == statedb.TypeBatchBuilder {
 293			if exitIdx != nil && exitTree != nil {
 294				exits[tp.i] = processedExit{
 295					exit:    true,
 296					newExit: newExit,
 297					idx:     *exitIdx,
 298					acc:     *exitAccount,
 299				}
 300			}
 301			tp.i++
 302		}
 303	}
 304
 305	if tp.zki != nil {
 306		txCompressedDataEmpty := common.TxCompressedDataEmpty(tp.config.ChainID)
 307		last := tp.i - 1
 308		if tp.i == 0 {
 309			last = 0
 310		}
 311		for i := last; i < int(tp.config.MaxTx); i++ {
 312			if i < int(tp.config.MaxTx)-1 {
 313				tp.zki.ISOutIdx[i] = tp.s.CurrentIdx().BigInt()
 314				tp.zki.ISStateRoot[i] = tp.s.MT.Root().BigInt()
 315				tp.zki.ISAccFeeOut[i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
 316				tp.zki.ISExitRoot[i] = exitTree.Root().BigInt()
 317			}
 318			if i >= tp.i {
 319				tp.zki.TxCompressedData[i] = txCompressedDataEmpty
 320			}
 321		}
 322		isFinalAccFee := formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
 323		copy(tp.zki.ISFinalAccFee, isFinalAccFee)
 324		// before computing the Fees txs, set the ISInitStateRootFee
 325		tp.zki.ISInitStateRootFee = tp.s.MT.Root().BigInt()
 326	}
 327
 328	// distribute the AccumulatedFees from the processed L2Txs into the
 329	// Coordinator Idxs
 330	iFee := 0
 331	for _, idx := range coordIdxs {
 332		accumulatedFee := tp.AccumulatedFees[idx]
 333
 334		cmp := accumulatedFee.Cmp(big.NewInt(0))
 335		if cmp == 1 { // accumulatedFee>0
 336			// send the fee to the Idx of the Coordinator for the TokenID
 337			accCoord, err := tp.s.GetAccount(idx)
 338			if err != nil {
 339				log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx)
 340				return nil, tracerr.Wrap(err)
 341			}
 342			if tp.zki != nil {
 343				tp.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
 344				tp.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
 345				coordBJJSign, coordBJJY := babyjub.UnpackSignY(accCoord.BJJ)
 346				if coordBJJSign {
 347					tp.zki.Sign3[iFee] = big.NewInt(1)
 348				}
 349				tp.zki.Ay3[iFee] = coordBJJY
 350				tp.zki.Balance3[iFee] = accCoord.Balance
 351				tp.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
 352			}
 353			accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
 354			pFee, err := tp.s.UpdateAccount(idx, accCoord)
 355			if err != nil {
 356				log.Error(err)
 357				return nil, tracerr.Wrap(err)
 358			}
 359			if tp.zki != nil {
 360				tp.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
 361				tp.zki.ISStateRootFee[iFee] = tp.s.MT.Root().BigInt()
 362			}
 363		}
 364		iFee++
 365	}
 366	if tp.zki != nil {
 367		for i := len(tp.AccumulatedFees); i < int(tp.config.MaxFeeTx)-1; i++ {
 368			tp.zki.ISStateRootFee[i] = tp.s.MT.Root().BigInt()
 369		}
 370		// add Coord Idx to ZKInputs.FeeTxsData
 371		for i := 0; i < len(coordIdxs); i++ {
 372			tp.zki.FeeIdxs[i] = coordIdxs[i].BigInt()
 373		}
 374	}
 375
 376	if tp.s.Typ == statedb.TypeTxSelector {
 377		return nil, nil
 378	}
 379
 380	// once all txs processed (exitTree root frozen), for each Exit,
 381	// generate common.ExitInfo data
 382	var exitInfos []common.ExitInfo
 383	for i := 0; i < nTx; i++ {
 384		if !exits[i].exit {
 385			continue
 386		}
 387		exitIdx := exits[i].idx
 388		exitAccount := exits[i].acc
 389
 390		// 0. generate MerkleProof
 391		p, err := exitTree.GenerateSCVerifierProof(exitIdx.BigInt(), nil)
 392		if err != nil {
 393			return nil, tracerr.Wrap(err)
 394		}
 395
 396		// 1. generate common.ExitInfo
 397		ei := common.ExitInfo{
 398			AccountIdx:  exitIdx,
 399			MerkleProof: p,
 400			Balance:     exitAccount.Balance,
 401		}
 402		exitInfos = append(exitInfos, ei)
 403	}
 404
 405	if tp.s.Typ == statedb.TypeSynchronizer {
 406		// return exitInfos, createdAccounts and collectedFees, so Synchronizer will
 407		// be able to store it into HistoryDB for the concrete BatchNum
 408		return &ProcessTxOutput{
 409			ZKInputs:           nil,
 410			ExitInfos:          exitInfos,
 411			CreatedAccounts:    createdAccounts,
 412			CoordinatorIdxsMap: coordIdxsMap,
 413			CollectedFees:      collectedFees,
 414		}, nil
 415	}
 416
 417	// compute last ZKInputs parameters
 418	tp.zki.GlobalChainID = big.NewInt(int64(tp.config.ChainID))
 419	tp.zki.Metadata.NewStateRootRaw = tp.s.MT.Root()
 420	tp.zki.Metadata.NewExitRootRaw = exitTree.Root()
 421
 422	// return ZKInputs as the BatchBuilder will return it to forge the Batch
 423	return &ProcessTxOutput{
 424		ZKInputs:           tp.zki,
 425		ExitInfos:          nil,
 426		CreatedAccounts:    nil,
 427		CoordinatorIdxsMap: coordIdxsMap,
 428		CollectedFees:      nil,
 429	}, nil
 430}
 431
 432// getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
 433// corresponding to the given CoordIdxs and the processed L2Txs
 434func (tp *TxProcessor) getFeePlanTokens(coordIdxs []common.Idx) ([]*big.Int, error) {
 435	var tBI []*big.Int
 436	for i := 0; i < len(coordIdxs); i++ {
 437		acc, err := tp.s.GetAccount(coordIdxs[i])
 438		if err != nil {
 439			log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
 440			return nil, tracerr.Wrap(err)
 441		}
 442		tBI = append(tBI, acc.TokenID.BigInt())
 443	}
 444	return tBI, nil
 445}
 446
 447// ProcessL1Tx process the given L1Tx applying the needed updates to the
 448// StateDB depending on the transaction Type. It returns the 3 parameters
 449// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
 450// the Exit created a new Leaf in the ExitTree.
 451// And another *common.Account parameter which contains the created account in
 452// case that has been a new created account and that the StateDB is of type
 453// TypeSynchronizer.
 454func (tp *TxProcessor) ProcessL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx,
 455	*common.Account, bool, *common.Account, error) {
 456	// ZKInputs
 457	if tp.zki != nil {
 458		// Txs
 459		var err error
 460		tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
 461		if err != nil {
 462			log.Error(err)
 463			return nil, nil, false, nil, tracerr.Wrap(err)
 464		}
 465		tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
 466		tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
 467		tp.zki.OnChain[tp.i] = big.NewInt(1)
 468
 469		// L1Txs
 470		depositAmountF16, err := common.NewFloat16(tx.DepositAmount)
 471		if err != nil {
 472			return nil, nil, false, nil, tracerr.Wrap(err)
 473		}
 474		tp.zki.DepositAmountF[tp.i] = big.NewInt(int64(depositAmountF16))
 475		tp.zki.FromEthAddr[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
 476		if tx.FromBJJ != common.EmptyBJJComp {
 477			tp.zki.FromBJJCompressed[tp.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
 478		}
 479
 480		// Intermediate States, for all the transactions except for the last one
 481		if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
 482			tp.zki.ISOnChain[tp.i] = big.NewInt(1)
 483		}
 484	}
 485
 486	switch tx.Type {
 487	case common.TxTypeForceTransfer:
 488		tp.computeEffectiveAmounts(tx)
 489
 490		// go to the MT account of sender and receiver, and update balance
 491		// & nonce
 492
 493		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees.
 494		// 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in
 495		// the Deposit type case.
 496		err := tp.applyTransfer(nil, nil, tx.Tx(), 0)
 497		if err != nil {
 498			log.Error(err)
 499			return nil, nil, false, nil, tracerr.Wrap(err)
 500		}
 501	case common.TxTypeCreateAccountDeposit:
 502		tp.computeEffectiveAmounts(tx)
 503
 504		// add new account to the MT, update balance of the MT account
 505		err := tp.applyCreateAccount(tx)
 506		if err != nil {
 507			log.Error(err)
 508			return nil, nil, false, nil, tracerr.Wrap(err)
 509		}
 510		// TODO applyCreateAccount will return the created account,
 511		// which in the case type==TypeSynchronizer will be added to an
 512		// array of created accounts that will be returned
 513	case common.TxTypeDeposit:
 514		tp.computeEffectiveAmounts(tx)
 515
 516		// update balance of the MT account
 517		err := tp.applyDeposit(tx, false)
 518		if err != nil {
 519			log.Error(err)
 520			return nil, nil, false, nil, tracerr.Wrap(err)
 521		}
 522	case common.TxTypeDepositTransfer:
 523		tp.computeEffectiveAmounts(tx)
 524
 525		// update balance in MT account, update balance & nonce of sender
 526		// & receiver
 527		err := tp.applyDeposit(tx, true)
 528		if err != nil {
 529			log.Error(err)
 530			return nil, nil, false, nil, tracerr.Wrap(err)
 531		}
 532	case common.TxTypeCreateAccountDepositTransfer:
 533		tp.computeEffectiveAmounts(tx)
 534
 535		// add new account to the merkletree, update balance in MT account,
 536		// update balance & nonce of sender & receiver
 537		err := tp.applyCreateAccountDepositTransfer(tx)
 538		if err != nil {
 539			log.Error(err)
 540			return nil, nil, false, nil, tracerr.Wrap(err)
 541		}
 542	case common.TxTypeForceExit:
 543		tp.computeEffectiveAmounts(tx)
 544
 545		// execute exit flow
 546		// coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
 547		exitAccount, newExit, err := tp.applyExit(nil, nil, exitTree, tx.Tx())
 548		if err != nil {
 549			log.Error(err)
 550			return nil, nil, false, nil, tracerr.Wrap(err)
 551		}
 552		return &tx.FromIdx, exitAccount, newExit, nil, nil
 553	default:
 554	}
 555
 556	var createdAccount *common.Account
 557	if tp.s.Typ == statedb.TypeSynchronizer &&
 558		(tx.Type == common.TxTypeCreateAccountDeposit ||
 559			tx.Type == common.TxTypeCreateAccountDepositTransfer) {
 560		var err error
 561		createdAccount, err = tp.s.GetAccount(tp.s.CurrentIdx())
 562		if err != nil {
 563			log.Error(err)
 564			return nil, nil, false, nil, tracerr.Wrap(err)
 565		}
 566	}
 567
 568	return nil, nil, false, createdAccount, nil
 569}
 570
 571// ProcessL2Tx process the given L2Tx applying the needed updates to the
 572// StateDB depending on the transaction Type. It returns the 3 parameters
 573// related to the Exit (in case of): Idx, ExitAccount, boolean determining if
 574// the Exit created a new Leaf in the ExitTree.
 575func (tp *TxProcessor) ProcessL2Tx(coordIdxsMap map[common.TokenID]common.Idx,
 576	collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
 577	tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
 578	var err error
 579	// if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
 580	if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
 581		if tp.s.Typ == statedb.TypeSynchronizer {
 582			// this should never be reached
 583			log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
 584			return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
 585		}
 586		// case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
 587
 588		accSender, err := tp.s.GetAccount(tx.FromIdx)
 589		if err != nil {
 590			return nil, nil, false, tracerr.Wrap(err)
 591		}
 592		tx.AuxToIdx, err = tp.s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, accSender.TokenID)
 593		if err != nil {
 594			return nil, nil, false, tracerr.Wrap(err)
 595		}
 596	}
 597
 598	// ZKInputs
 599	if tp.zki != nil {
 600		// Txs
 601		tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
 602		if err != nil {
 603			return nil, nil, false, tracerr.Wrap(err)
 604		}
 605		tp.zki.TxCompressedDataV2[tp.i], err = tx.TxCompressedDataV2()
 606		if err != nil {
 607			return nil, nil, false, tracerr.Wrap(err)
 608		}
 609		tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
 610		tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
 611
 612		// fill AuxToIdx if needed
 613		if tx.ToIdx == 0 {
 614			// use toIdx that can have been filled by tx.ToIdx or
 615			// if tx.Idx==0 (this case), toIdx is filled by the Idx
 616			// from db by ToEthAddr&ToBJJ
 617			tp.zki.AuxToIdx[tp.i] = tx.AuxToIdx.BigInt()
 618		}
 619
 620		if tx.ToBJJ != common.EmptyBJJComp {
 621			_, tp.zki.ToBJJAy[tp.i] = babyjub.UnpackSignY(tx.ToBJJ)
 622		}
 623		tp.zki.ToEthAddr[tp.i] = common.EthAddrToBigInt(tx.ToEthAddr)
 624
 625		tp.zki.OnChain[tp.i] = big.NewInt(0)
 626		tp.zki.NewAccount[tp.i] = big.NewInt(0)
 627
 628		// L2Txs
 629		// tp.zki.RqOffset[tp.i] =  // TODO Rq once TxSelector is ready
 630		// tp.zki.RqTxCompressedDataV2[tp.i] = // TODO
 631		// tp.zki.RqToEthAddr[tp.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
 632		// tp.zki.RqToBJJAy[tp.i] = tx.ToBJJ.Y // TODO
 633
 634		signature, err := tx.Signature.Decompress()
 635		if err != nil {
 636			log.Error(err)
 637			return nil, nil, false, tracerr.Wrap(err)
 638		}
 639		tp.zki.S[tp.i] = signature.S
 640		tp.zki.R8x[tp.i] = signature.R8.X
 641		tp.zki.R8y[tp.i] = signature.R8.Y
 642	}
 643
 644	// if StateDB type==TypeSynchronizer, will need to add Nonce
 645	if tp.s.Typ == statedb.TypeSynchronizer {
 646		// as type==TypeSynchronizer, always tx.ToIdx!=0
 647		acc, err := tp.s.GetAccount(tx.FromIdx)
 648		if err != nil {
 649			log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
 650			return nil, nil, false, tracerr.Wrap(err)
 651		}
 652		tx.Nonce = acc.Nonce
 653		tx.TokenID = acc.TokenID
 654	}
 655
 656	switch tx.Type {
 657	case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
 658		// go to the MT account of sender and receiver, and update
 659		// balance & nonce
 660		err = tp.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
 661		if err != nil {
 662			log.Error(err)
 663			return nil, nil, false, tracerr.Wrap(err)
 664		}
 665	case common.TxTypeExit:
 666		// execute exit flow
 667		exitAccount, newExit, err := tp.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
 668		if err != nil {
 669			log.Error(err)
 670			return nil, nil, false, tracerr.Wrap(err)
 671		}
 672		return &tx.FromIdx, exitAccount, newExit, nil
 673	default:
 674	}
 675	return nil, nil, false, nil
 676}
 677
 678// applyCreateAccount creates a new account in the account of the depositer, it
 679// stores the deposit value
 680func (tp *TxProcessor) applyCreateAccount(tx *common.L1Tx) error {
 681	account := &common.Account{
 682		TokenID: tx.TokenID,
 683		Nonce:   0,
 684		Balance: tx.EffectiveDepositAmount,
 685		BJJ:     tx.FromBJJ,
 686		EthAddr: tx.FromEthAddr,
 687	}
 688
 689	p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), account)
 690	if err != nil {
 691		return tracerr.Wrap(err)
 692	}
 693	if tp.zki != nil {
 694		tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
 695		tp.zki.Nonce1[tp.i] = big.NewInt(0)
 696		fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
 697		if fromBJJSign {
 698			tp.zki.Sign1[tp.i] = big.NewInt(1)
 699		}
 700		tp.zki.Ay1[tp.i] = fromBJJY
 701		tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
 702		tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
 703		tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
 704		if p.IsOld0 {
 705			tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
 706		}
 707		tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
 708		tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
 709
 710		tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
 711
 712		tp.zki.AuxFromIdx[tp.i] = common.Idx(tp.s.CurrentIdx() + 1).BigInt()
 713		tp.zki.NewAccount[tp.i] = big.NewInt(1)
 714
 715		if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
 716			// intermediate states
 717			tp.zki.ISOnChain[tp.i] = big.NewInt(1)
 718		}
 719	}
 720
 721	return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
 722}
 723
 724// applyDeposit updates the balance in the account of the depositer, if
 725// andTransfer parameter is set to true, the method will also apply the
 726// Transfer of the L1Tx/DepositTransfer
 727func (tp *TxProcessor) applyDeposit(tx *common.L1Tx, transfer bool) error {
 728	accSender, err := tp.s.GetAccount(tx.FromIdx)
 729	if err != nil {
 730		return tracerr.Wrap(err)
 731	}
 732
 733	if tp.zki != nil {
 734		tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
 735		tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
 736		senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
 737		if senderBJJSign {
 738			tp.zki.Sign1[tp.i] = big.NewInt(1)
 739		}
 740		tp.zki.Ay1[tp.i] = senderBJJY
 741		tp.zki.Balance1[tp.i] = accSender.Balance
 742		tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
 743	}
 744
 745	// add the deposit to the sender
 746	accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
 747	// subtract amount to the sender
 748	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
 749
 750	// update sender account in localStateDB
 751	p, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
 752	if err != nil {
 753		return tracerr.Wrap(err)
 754	}
 755	if tp.zki != nil {
 756		tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
 757		// IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
 758	}
 759
 760	// in case that the tx is a L1Tx>DepositTransfer
 761	var accReceiver *common.Account
 762	if transfer {
 763		if tx.ToIdx == tx.FromIdx {
 764			accReceiver = accSender
 765		} else {
 766			accReceiver, err = tp.s.GetAccount(tx.ToIdx)
 767			if err != nil {
 768				return tracerr.Wrap(err)
 769			}
 770		}
 771
 772		if tp.zki != nil {
 773			tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
 774			tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
 775			receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
 776			if receiverBJJSign {
 777				tp.zki.Sign2[tp.i] = big.NewInt(1)
 778			}
 779			tp.zki.Ay2[tp.i] = receiverBJJY
 780			tp.zki.Balance2[tp.i] = accReceiver.Balance
 781			tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
 782		}
 783
 784		// add amount to the receiver
 785		accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
 786
 787		// update receiver account in localStateDB
 788		p, err := tp.s.UpdateAccount(tx.ToIdx, accReceiver)
 789		if err != nil {
 790			return tracerr.Wrap(err)
 791		}
 792		if tp.zki != nil {
 793			tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
 794			// IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
 795		}
 796	}
 797
 798	return nil
 799}
 800
 801// applyTransfer updates the balance & nonce in the account of the sender, and
 802// the balance in the account of the receiver.
 803// Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
 804// tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
 805// the receiver. This parameter is used when the tx.ToIdx is not specified and
 806// the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
 807func (tp *TxProcessor) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
 808	collectedFees map[common.TokenID]*big.Int, tx common.Tx, auxToIdx common.Idx) error {
 809	if auxToIdx == common.Idx(0) {
 810		auxToIdx = tx.ToIdx
 811	}
 812	// get sender and receiver accounts from localStateDB
 813	accSender, err := tp.s.GetAccount(tx.FromIdx)
 814	if err != nil {
 815		log.Error(err)
 816		return tracerr.Wrap(err)
 817	}
 818
 819	if tp.zki != nil {
 820		// Set the State1 before updating the Sender leaf
 821		tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
 822		tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
 823		senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
 824		if senderBJJSign {
 825			tp.zki.Sign1[tp.i] = big.NewInt(1)
 826		}
 827		tp.zki.Ay1[tp.i] = senderBJJY
 828		tp.zki.Balance1[tp.i] = accSender.Balance
 829		tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
 830	}
 831	if !tx.IsL1 { // L2
 832		// increment nonce
 833		accSender.Nonce++
 834
 835		// compute fee and subtract it from the accSender
 836		fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
 837		if err != nil {
 838			return tracerr.Wrap(err)
 839		}
 840		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
 841		accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
 842
 843		if _, ok := coordIdxsMap[accSender.TokenID]; ok {
 844			accCoord, err := tp.s.GetAccount(coordIdxsMap[accSender.TokenID])
 845			if err != nil {
 846				return tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", accSender.TokenID, coordIdxsMap[accSender.TokenID]))
 847			}
 848			// accumulate the fee for the Coord account
 849			accumulated := tp.AccumulatedFees[accCoord.Idx]
 850			accumulated.Add(accumulated, fee)
 851
 852			if tp.s.Typ == statedb.TypeSynchronizer ||
 853				tp.s.Typ == statedb.TypeBatchBuilder {
 854				collected := collectedFees[accCoord.TokenID]
 855				collected.Add(collected, fee)
 856			}
 857		} else {
 858			log.Debugw("No coord Idx to receive fee", "tx", tx)
 859		}
 860	} else {
 861		accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
 862	}
 863
 864	// update sender account in localStateDB
 865	pSender, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
 866	if err != nil {
 867		log.Error(err)
 868		return tracerr.Wrap(err)
 869	}
 870	if tp.zki != nil {
 871		tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(pSender.Siblings)
 872	}
 873
 874	var accReceiver *common.Account
 875	if auxToIdx == tx.FromIdx {
 876		// if Sender is the Receiver, reuse 'accSender' pointer,
 877		// because in the DB the account for 'auxToIdx' won't be
 878		// updated yet
 879		accReceiver = accSender
 880	} else {
 881		accReceiver, err = tp.s.GetAccount(auxToIdx)
 882		if err != nil {
 883			log.Error(err, auxToIdx)
 884			return tracerr.Wrap(err)
 885		}
 886	}
 887	if tp.zki != nil {
 888		// Set the State2 before updating the Receiver leaf
 889		tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
 890		tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
 891		receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
 892		if receiverBJJSign {
 893			tp.zki.Sign2[tp.i] = big.NewInt(1)
 894		}
 895		tp.zki.Ay2[tp.i] = receiverBJJY
 896		tp.zki.Balance2[tp.i] = accReceiver.Balance
 897		tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
 898	}
 899
 900	// add amount-feeAmount to the receiver
 901	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
 902
 903	// update receiver account in localStateDB
 904	pReceiver, err := tp.s.UpdateAccount(auxToIdx, accReceiver)
 905	if err != nil {
 906		return tracerr.Wrap(err)
 907	}
 908	if tp.zki != nil {
 909		tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(pReceiver.Siblings)
 910	}
 911
 912	return nil
 913}
 914
 915// applyCreateAccountDepositTransfer, in a single tx, creates a new account,
 916// makes a deposit, and performs a transfer to another account
 917func (tp *TxProcessor) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
 918	auxFromIdx := common.Idx(tp.s.CurrentIdx() + 1)
 919	accSender := &common.Account{
 920		TokenID: tx.TokenID,
 921		Nonce:   0,
 922		Balance: tx.EffectiveDepositAmount,
 923		BJJ:     tx.FromBJJ,
 924		EthAddr: tx.FromEthAddr,
 925	}
 926
 927	if tp.zki != nil {
 928		// Set the State1 before updating the Sender leaf
 929		tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
 930		tp.zki.Nonce1[tp.i] = big.NewInt(0)
 931		fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
 932		if fromBJJSign {
 933			tp.zki.Sign1[tp.i] = big.NewInt(1)
 934		}
 935		tp.zki.Ay1[tp.i] = fromBJJY
 936		tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
 937		tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
 938	}
 939
 940	// subtract amount to the sender
 941	accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
 942
 943	// create Account of the Sender
 944	p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), accSender)
 945	if err != nil {
 946		return tracerr.Wrap(err)
 947	}
 948	if tp.zki != nil {
 949		tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
 950		if p.IsOld0 {
 951			tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
 952		}
 953		tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
 954		tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
 955
 956		tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
 957
 958		tp.zki.AuxFromIdx[tp.i] = auxFromIdx.BigInt()
 959		tp.zki.NewAccount[tp.i] = big.NewInt(1)
 960
 961		// intermediate states
 962		tp.zki.ISOnChain[tp.i] = big.NewInt(1)
 963	}
 964	var accReceiver *common.Account
 965	if tx.ToIdx == auxFromIdx {
 966		accReceiver = accSender
 967	} else {
 968		accReceiver, err = tp.s.GetAccount(tx.ToIdx)
 969		if err != nil {
 970			log.Error(err)
 971			return tracerr.Wrap(err)
 972		}
 973	}
 974
 975	if tp.zki != nil {
 976		// Set the State2 before updating the Receiver leaf
 977		tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
 978		tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
 979		receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
 980		if receiverBJJSign {
 981			tp.zki.Sign2[tp.i] = big.NewInt(1)
 982		}
 983		tp.zki.Ay2[tp.i] = receiverBJJY
 984		tp.zki.Balance2[tp.i] = accReceiver.Balance
 985		tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
 986	}
 987
 988	// add amount to the receiver
 989	accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
 990
 991	// update receiver account in localStateDB
 992	p, err = tp.s.UpdateAccount(tx.ToIdx, accReceiver)
 993	if err != nil {
 994		return tracerr.Wrap(err)
 995	}
 996	if tp.zki != nil {
 997		tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
 998	}
 999
1000	return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
1001}
1002
1003// It returns the ExitAccount and a boolean determining if the Exit created a
1004// new Leaf in the ExitTree.
1005func (tp *TxProcessor) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
1006	collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
1007	tx common.Tx) (*common.Account, bool, error) {
1008	// 0. subtract tx.Amount from current Account in StateMT
1009	// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
1010	acc, err := tp.s.GetAccount(tx.FromIdx)
1011	if err != nil {
1012		return nil, false, tracerr.Wrap(err)
1013	}
1014	if tp.zki != nil {
1015		tp.zki.TokenID1[tp.i] = acc.TokenID.BigInt()
1016		tp.zki.Nonce1[tp.i] = acc.Nonce.BigInt()
1017		accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1018		if accBJJSign {
1019			tp.zki.Sign1[tp.i] = big.NewInt(1)
1020		}
1021		tp.zki.Ay1[tp.i] = accBJJY
1022		tp.zki.Balance1[tp.i] = acc.Balance
1023		tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1024	}
1025
1026	if !tx.IsL1 {
1027		// increment nonce
1028		acc.Nonce++
1029
1030		// compute fee and subtract it from the accSender
1031		fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
1032		if err != nil {
1033			return nil, false, tracerr.Wrap(err)
1034		}
1035		feeAndAmount := new(big.Int).Add(tx.Amount, fee)
1036		acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
1037
1038		if _, ok := coordIdxsMap[acc.TokenID]; ok {
1039			accCoord, err := tp.s.GetAccount(coordIdxsMap[acc.TokenID])
1040			if err != nil {
1041				return nil, false, tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", acc.TokenID, coordIdxsMap[acc.TokenID]))
1042			}
1043
1044			// accumulate the fee for the Coord account
1045			accumulated := tp.AccumulatedFees[accCoord.Idx]
1046			accumulated.Add(accumulated, fee)
1047
1048			if tp.s.Typ == statedb.TypeSynchronizer ||
1049				tp.s.Typ == statedb.TypeBatchBuilder {
1050				collected := collectedFees[accCoord.TokenID]
1051				collected.Add(collected, fee)
1052			}
1053		} else {
1054			log.Debugw("No coord Idx to receive fee", "tx", tx)
1055		}
1056	} else {
1057		acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
1058	}
1059
1060	p, err := tp.s.UpdateAccount(tx.FromIdx, acc)
1061	if err != nil {
1062		return nil, false, tracerr.Wrap(err)
1063	}
1064	if tp.zki != nil {
1065		tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
1066	}
1067
1068	if exitTree == nil {
1069		return nil, false, nil
1070	}
1071	exitAccount, err := statedb.GetAccountInTreeDB(exitTree.DB(), tx.FromIdx)
1072	if tracerr.Unwrap(err) == db.ErrNotFound {
1073		// 1a. if idx does not exist in exitTree:
1074		// add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance =
1075		// exitAmount (exitAmount=tx.Amount)
1076		exitAccount := &common.Account{
1077			TokenID: acc.TokenID,
1078			Nonce:   common.Nonce(0),
1079			Balance: tx.Amount,
1080			BJJ:     acc.BJJ,
1081			EthAddr: acc.EthAddr,
1082		}
1083		if tp.zki != nil {
1084			// Set the State2 before creating the Exit leaf
1085			tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
1086			tp.zki.Nonce2[tp.i] = big.NewInt(0)
1087			accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1088			if accBJJSign {
1089				tp.zki.Sign2[tp.i] = big.NewInt(1)
1090			}
1091			tp.zki.Ay2[tp.i] = accBJJY
1092			tp.zki.Balance2[tp.i] = tx.Amount
1093			tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1094			// as Leaf didn't exist in the ExitTree, set NewExit[i]=1
1095			tp.zki.NewExit[tp.i] = big.NewInt(1)
1096		}
1097		p, err = statedb.CreateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
1098		if err != nil {
1099			return nil, false, tracerr.Wrap(err)
1100		}
1101		if tp.zki != nil {
1102			tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
1103			if p.IsOld0 {
1104				tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
1105			}
1106			tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
1107			tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
1108			tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
1109		}
1110		return exitAccount, true, nil
1111	} else if err != nil {
1112		return exitAccount, false, tracerr.Wrap(err)
1113	}
1114	exitAccount.Nonce = exitAccount.Nonce + 1
1115
1116	// 1b. if idx already exist in exitTree:
1117	if tp.zki != nil {
1118		// Set the State2 before updating the Exit leaf
1119		tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
1120		// increment nonce from existing ExitLeaf
1121		tp.zki.Nonce2[tp.i] = exitAccount.Nonce.BigInt()
1122		accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
1123		if accBJJSign {
1124			tp.zki.Sign2[tp.i] = big.NewInt(1)
1125		}
1126		tp.zki.Ay2[tp.i] = accBJJY
1127		tp.zki.Balance2[tp.i] = tx.Amount
1128		tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
1129	}
1130
1131	// update account, where account.Balance += exitAmount
1132	exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
1133	p, err = statedb.UpdateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
1134	if err != nil {
1135		return nil, false, tracerr.Wrap(err)
1136	}
1137
1138	if tp.zki != nil {
1139		tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
1140		if p.IsOld0 {
1141			tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
1142		}
1143		tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
1144		tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
1145	}
1146
1147	return exitAccount, false, nil
1148}
1149
1150// computeEffectiveAmounts checks that the L1Tx data is correct
1151func (tp *TxProcessor) computeEffectiveAmounts(tx *common.L1Tx) {
1152	tx.EffectiveAmount = tx.Amount
1153	tx.EffectiveDepositAmount = tx.DepositAmount
1154
1155	if !tx.UserOrigin {
1156		// case where the L1Tx is generated by the Coordinator
1157		tx.EffectiveAmount = big.NewInt(0)
1158		tx.EffectiveDepositAmount = big.NewInt(0)
1159		return
1160	}
1161
1162	if tx.Type == common.TxTypeCreateAccountDeposit {
1163		return
1164	}
1165
1166	if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
1167		// CreateAccountDepositTransfer case
1168		cmp := tx.DepositAmount.Cmp(tx.Amount)
1169		if cmp == -1 { // DepositAmount<Amount
1170			tx.EffectiveAmount = big.NewInt(0)
1171			return
1172		}
1173
1174		// check if tx.TokenID==receiver.TokenID
1175		accReceiver, err := tp.s.GetAccount(tx.ToIdx)
1176		if err != nil {
1177			log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
1178			tx.EffectiveDepositAmount = big.NewInt(0)
1179			tx.EffectiveAmount = big.NewInt(0)
1180			return
1181		}
1182		if tx.TokenID != accReceiver.TokenID {
1183			log.Debugf("EffectiveAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
1184			tx.EffectiveAmount = big.NewInt(0)
1185			return
1186		}
1187		return
1188	}
1189
1190	accSender, err := tp.s.GetAccount(tx.FromIdx)
1191	if err != nil {
1192		log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
1193		tx.EffectiveDepositAmount = big.NewInt(0)
1194		tx.EffectiveAmount = big.NewInt(0)
1195		return
1196	}
1197
1198	// check that tx.TokenID corresponds to the Sender account TokenID
1199	if tx.TokenID != accSender.TokenID {
1200		log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
1201		tx.EffectiveDepositAmount = big.NewInt(0)
1202		tx.EffectiveAmount = big.NewInt(0)
1203		return
1204	}
1205
1206	// check that Sender has enough balance
1207	bal := accSender.Balance
1208	if tx.DepositAmount != nil {
1209		bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
1210	}
1211	cmp := bal.Cmp(tx.Amount)
1212	if cmp == -1 {
1213		log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
1214		tx.EffectiveAmount = big.NewInt(0)
1215		return
1216	}
1217
1218	// check that the tx.FromEthAddr is the same than the EthAddress of the
1219	// Sender
1220	if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
1221		log.Debugf("EffectiveAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of the sender account by the Idx (%s)", tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
1222		tx.EffectiveAmount = big.NewInt(0)
1223	}
1224
1225	if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
1226		// if transfer is Exit type, there are no more checks
1227		return
1228	}
1229
1230	// check that TokenID is the same for Sender & Receiver account
1231	accReceiver, err := tp.s.GetAccount(tx.ToIdx)
1232	if err != nil {
1233		log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
1234		tx.EffectiveDepositAmount = big.NewInt(0)
1235		tx.EffectiveAmount = big.NewInt(0)
1236		return
1237	}
1238	if accSender.TokenID != accReceiver.TokenID {
1239		log.Debugf("EffectiveAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", accSender.TokenID, accReceiver.TokenID)
1240		tx.EffectiveAmount = big.NewInt(0)
1241		return
1242	}
1243	if tx.TokenID != accReceiver.TokenID {
1244		log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
1245		tx.EffectiveAmount = big.NewInt(0)
1246		return
1247	}
1248}