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