arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/node/node.go
node/node.goRaw
  1package node
  2
  3import (
  4	"context"
  5	"errors"
  6	"fmt"
  7	"net"
  8	"net/http"
  9	"sync"
 10	"time"
 11
 12	"github.com/ethereum/go-ethereum/accounts"
 13	ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
 14	"github.com/ethereum/go-ethereum/ethclient"
 15	"github.com/gin-contrib/cors"
 16	"github.com/gin-gonic/gin"
 17	"github.com/hermeznetwork/hermez-node/api"
 18	"github.com/hermeznetwork/hermez-node/batchbuilder"
 19	"github.com/hermeznetwork/hermez-node/common"
 20	"github.com/hermeznetwork/hermez-node/config"
 21	"github.com/hermeznetwork/hermez-node/coordinator"
 22	dbUtils "github.com/hermeznetwork/hermez-node/db"
 23	"github.com/hermeznetwork/hermez-node/db/historydb"
 24	"github.com/hermeznetwork/hermez-node/db/l2db"
 25	"github.com/hermeznetwork/hermez-node/db/statedb"
 26	"github.com/hermeznetwork/hermez-node/eth"
 27	"github.com/hermeznetwork/hermez-node/log"
 28	"github.com/hermeznetwork/hermez-node/priceupdater"
 29	"github.com/hermeznetwork/hermez-node/prover"
 30	"github.com/hermeznetwork/hermez-node/synchronizer"
 31	"github.com/hermeznetwork/hermez-node/test/debugapi"
 32	"github.com/hermeznetwork/hermez-node/txprocessor"
 33	"github.com/hermeznetwork/hermez-node/txselector"
 34	"github.com/hermeznetwork/tracerr"
 35	"github.com/jmoiron/sqlx"
 36	"github.com/russross/meddler"
 37)
 38
 39// Mode sets the working mode of the node (synchronizer or coordinator)
 40type Mode string
 41
 42const (
 43	// ModeCoordinator defines the mode of the HermezNode as Coordinator, which
 44	// means that the node is set to forge (which also will be synchronizing with
 45	// the L1 blockchain state)
 46	ModeCoordinator Mode = "coordinator"
 47
 48	// ModeSynchronizer defines the mode of the HermezNode as Synchronizer, which
 49	// means that the node is set to only synchronize with the L1 blockchain state
 50	// and will not forge
 51	ModeSynchronizer Mode = "synchronizer"
 52)
 53
 54// Node is the Hermez Node
 55type Node struct {
 56	nodeAPI      *NodeAPI
 57	debugAPI     *debugapi.DebugAPI
 58	priceUpdater *priceupdater.PriceUpdater
 59	// Coordinator
 60	coord *coordinator.Coordinator
 61
 62	// Synchronizer
 63	sync *synchronizer.Synchronizer
 64
 65	// General
 66	cfg          *config.Node
 67	mode         Mode
 68	sqlConnRead  *sqlx.DB
 69	sqlConnWrite *sqlx.DB
 70	ctx          context.Context
 71	wg           sync.WaitGroup
 72	cancel       context.CancelFunc
 73}
 74
 75// NewNode creates a Node
 76func NewNode(mode Mode, cfg *config.Node) (*Node, error) {
 77	meddler.Debug = cfg.Debug.MeddlerLogs
 78	// Stablish DB connection
 79	dbWrite, err := dbUtils.InitSQLDB(
 80		cfg.PostgreSQL.PortWrite,
 81		cfg.PostgreSQL.HostWrite,
 82		cfg.PostgreSQL.UserWrite,
 83		cfg.PostgreSQL.PasswordWrite,
 84		cfg.PostgreSQL.NameWrite,
 85	)
 86	if err != nil {
 87		return nil, tracerr.Wrap(fmt.Errorf("dbUtils.InitSQLDB: %w", err))
 88	}
 89	var dbRead *sqlx.DB
 90	if cfg.PostgreSQL.HostRead == "" {
 91		dbRead = dbWrite
 92	} else if cfg.PostgreSQL.HostRead == cfg.PostgreSQL.HostWrite {
 93		return nil, tracerr.Wrap(fmt.Errorf(
 94			"PostgreSQL.HostRead and PostgreSQL.HostWrite must be different",
 95		))
 96	} else {
 97		dbRead, err = dbUtils.InitSQLDB(
 98			cfg.PostgreSQL.PortRead,
 99			cfg.PostgreSQL.HostRead,
100			cfg.PostgreSQL.UserRead,
101			cfg.PostgreSQL.PasswordRead,
102			cfg.PostgreSQL.NameRead,
103		)
104		if err != nil {
105			return nil, tracerr.Wrap(fmt.Errorf("dbUtils.InitSQLDB: %w", err))
106		}
107	}
108	var apiConnCon *dbUtils.APIConnectionController
109	if cfg.API.Explorer || mode == ModeCoordinator {
110		apiConnCon = dbUtils.NewAPICnnectionController(
111			cfg.API.MaxSQLConnections,
112			cfg.API.SQLConnectionTimeout.Duration,
113		)
114	}
115
116	historyDB := historydb.NewHistoryDB(dbRead, dbWrite, apiConnCon)
117
118	ethClient, err := ethclient.Dial(cfg.Web3.URL)
119	if err != nil {
120		return nil, tracerr.Wrap(err)
121	}
122	var ethCfg eth.EthereumConfig
123	var account *accounts.Account
124	var keyStore *ethKeystore.KeyStore
125	if mode == ModeCoordinator {
126		ethCfg = eth.EthereumConfig{
127			CallGasLimit: 0, // cfg.Coordinator.EthClient.CallGasLimit,
128			GasPriceDiv:  0, // cfg.Coordinator.EthClient.GasPriceDiv,
129		}
130
131		scryptN := ethKeystore.StandardScryptN
132		scryptP := ethKeystore.StandardScryptP
133		if cfg.Coordinator.Debug.LightScrypt {
134			scryptN = ethKeystore.LightScryptN
135			scryptP = ethKeystore.LightScryptP
136		}
137		keyStore = ethKeystore.NewKeyStore(cfg.Coordinator.EthClient.Keystore.Path,
138			scryptN, scryptP)
139
140		balance, err := ethClient.BalanceAt(context.TODO(), cfg.Coordinator.ForgerAddress, nil)
141		if err != nil {
142			return nil, tracerr.Wrap(err)
143		}
144
145		minForgeBalance := cfg.Coordinator.MinimumForgeAddressBalance
146		if minForgeBalance != nil && balance.Cmp(minForgeBalance) == -1 {
147			return nil, tracerr.Wrap(fmt.Errorf(
148				"forger account balance is less than cfg.Coordinator.MinimumForgeAddressBalance: %v < %v",
149				balance, minForgeBalance))
150		}
151		log.Infow("forger ethereum account balance",
152			"addr", cfg.Coordinator.ForgerAddress,
153			"balance", balance,
154			"minForgeBalance", minForgeBalance,
155		)
156
157		// Unlock Coordinator ForgerAddr in the keystore to make calls
158		// to ForgeBatch in the smart contract
159		if !keyStore.HasAddress(cfg.Coordinator.ForgerAddress) {
160			return nil, tracerr.Wrap(fmt.Errorf(
161				"ethereum keystore doesn't have the key for address %v",
162				cfg.Coordinator.ForgerAddress))
163		}
164		account = &accounts.Account{
165			Address: cfg.Coordinator.ForgerAddress,
166		}
167		if err := keyStore.Unlock(*account,
168			cfg.Coordinator.EthClient.Keystore.Password); err != nil {
169			return nil, tracerr.Wrap(err)
170		}
171		log.Infow("Forger ethereum account unlocked in the keystore",
172			"addr", cfg.Coordinator.ForgerAddress)
173	}
174	client, err := eth.NewClient(ethClient, account, keyStore, &eth.ClientConfig{
175		Ethereum: ethCfg,
176		Rollup: eth.RollupConfig{
177			Address: cfg.SmartContracts.Rollup,
178		},
179		Auction: eth.AuctionConfig{
180			Address: cfg.SmartContracts.Auction,
181			TokenHEZ: eth.TokenConfig{
182				Address: cfg.SmartContracts.TokenHEZ,
183				Name:    cfg.SmartContracts.TokenHEZName,
184			},
185		},
186		WDelayer: eth.WDelayerConfig{
187			Address: cfg.SmartContracts.WDelayer,
188		},
189	})
190	if err != nil {
191		return nil, tracerr.Wrap(err)
192	}
193
194	chainID, err := client.EthChainID()
195	if err != nil {
196		return nil, tracerr.Wrap(err)
197	}
198	if !chainID.IsUint64() {
199		return nil, tracerr.Wrap(fmt.Errorf("chainID cannot be represented as uint64"))
200	}
201	chainIDU64 := chainID.Uint64()
202	const maxUint16 uint64 = 0xffff
203	if chainIDU64 > maxUint16 {
204		return nil, tracerr.Wrap(fmt.Errorf("chainID overflows uint16"))
205	}
206	chainIDU16 := uint16(chainIDU64)
207
208	const safeStateDBKeep = 128
209	if cfg.StateDB.Keep < safeStateDBKeep {
210		return nil, tracerr.Wrap(fmt.Errorf("cfg.StateDB.Keep = %v < %v, which is unsafe",
211			cfg.StateDB.Keep, safeStateDBKeep))
212	}
213	stateDB, err := statedb.NewStateDB(statedb.Config{
214		Path:    cfg.StateDB.Path,
215		Keep:    cfg.StateDB.Keep,
216		Type:    statedb.TypeSynchronizer,
217		NLevels: statedb.MaxNLevels,
218	})
219	if err != nil {
220		return nil, tracerr.Wrap(err)
221	}
222
223	sync, err := synchronizer.NewSynchronizer(client, historyDB, stateDB, synchronizer.Config{
224		StatsRefreshPeriod: cfg.Synchronizer.StatsRefreshPeriod.Duration,
225		ChainID:            chainIDU16,
226	})
227	if err != nil {
228		return nil, tracerr.Wrap(err)
229	}
230	initSCVars := sync.SCVars()
231
232	scConsts := synchronizer.SCConsts{
233		Rollup:   *sync.RollupConstants(),
234		Auction:  *sync.AuctionConstants(),
235		WDelayer: *sync.WDelayerConstants(),
236	}
237
238	var coord *coordinator.Coordinator
239	var l2DB *l2db.L2DB
240	if mode == ModeCoordinator {
241		l2DB = l2db.NewL2DB(
242			dbRead, dbWrite,
243			cfg.Coordinator.L2DB.SafetyPeriod,
244			cfg.Coordinator.L2DB.MaxTxs,
245			cfg.Coordinator.L2DB.MinFeeUSD,
246			cfg.Coordinator.L2DB.TTL.Duration,
247			apiConnCon,
248		)
249
250		// Unlock FeeAccount EthAddr in the keystore to generate the
251		// account creation authorization
252		if !keyStore.HasAddress(cfg.Coordinator.FeeAccount.Address) {
253			return nil, tracerr.Wrap(fmt.Errorf(
254				"ethereum keystore doesn't have the key for address %v",
255				cfg.Coordinator.FeeAccount.Address))
256		}
257		feeAccount := accounts.Account{
258			Address: cfg.Coordinator.FeeAccount.Address,
259		}
260		if err := keyStore.Unlock(feeAccount,
261			cfg.Coordinator.EthClient.Keystore.Password); err != nil {
262			return nil, tracerr.Wrap(err)
263		}
264		auth := &common.AccountCreationAuth{
265			EthAddr: cfg.Coordinator.FeeAccount.Address,
266			BJJ:     cfg.Coordinator.FeeAccount.BJJ,
267		}
268		if err := auth.Sign(func(msg []byte) ([]byte, error) {
269			return keyStore.SignHash(feeAccount, msg)
270		}, chainIDU16, cfg.SmartContracts.Rollup); err != nil {
271			return nil, err
272		}
273		coordAccount := &txselector.CoordAccount{
274			Addr:                cfg.Coordinator.FeeAccount.Address,
275			BJJ:                 cfg.Coordinator.FeeAccount.BJJ,
276			AccountCreationAuth: auth.Signature,
277		}
278		txSelector, err := txselector.NewTxSelector(coordAccount, cfg.Coordinator.TxSelector.Path, stateDB, l2DB)
279		if err != nil {
280			return nil, tracerr.Wrap(err)
281		}
282		batchBuilder, err := batchbuilder.NewBatchBuilder(cfg.Coordinator.BatchBuilder.Path,
283			stateDB, 0, uint64(cfg.Coordinator.Circuit.NLevels))
284		if err != nil {
285			return nil, tracerr.Wrap(err)
286		}
287		serverProofs := make([]prover.Client, len(cfg.Coordinator.ServerProofs))
288		for i, serverProofCfg := range cfg.Coordinator.ServerProofs {
289			serverProofs[i] = prover.NewProofServerClient(serverProofCfg.URL,
290				cfg.Coordinator.ProofServerPollInterval.Duration)
291		}
292
293		txProcessorCfg := txprocessor.Config{
294			NLevels:  uint32(cfg.Coordinator.Circuit.NLevels),
295			MaxTx:    uint32(cfg.Coordinator.Circuit.MaxTx),
296			ChainID:  chainIDU16,
297			MaxFeeTx: common.RollupConstMaxFeeIdxCoordinator,
298			MaxL1Tx:  common.RollupConstMaxL1Tx,
299		}
300		var verifierIdx int
301		if cfg.Coordinator.Debug.RollupVerifierIndex == nil {
302			verifierIdx, err = scConsts.Rollup.FindVerifierIdx(
303				cfg.Coordinator.Circuit.MaxTx,
304				cfg.Coordinator.Circuit.NLevels,
305			)
306			if err != nil {
307				return nil, tracerr.Wrap(err)
308			}
309			log.Infow("Found verifier that matches circuit config", "verifierIdx", verifierIdx)
310		} else {
311			verifierIdx = *cfg.Coordinator.Debug.RollupVerifierIndex
312			log.Infow("Using debug verifier index from config", "verifierIdx", verifierIdx)
313			if verifierIdx >= len(scConsts.Rollup.Verifiers) {
314				return nil, tracerr.Wrap(
315					fmt.Errorf("verifierIdx (%v) >= "+
316						"len(scConsts.Rollup.Verifiers) (%v)",
317						verifierIdx, len(scConsts.Rollup.Verifiers)))
318			}
319			verifier := scConsts.Rollup.Verifiers[verifierIdx]
320			if verifier.MaxTx != cfg.Coordinator.Circuit.MaxTx ||
321				verifier.NLevels != cfg.Coordinator.Circuit.NLevels {
322				return nil, tracerr.Wrap(
323					fmt.Errorf("Circuit config and verifier params don't match.  "+
324						"circuit.MaxTx = %v, circuit.NLevels = %v, "+
325						"verifier.MaxTx = %v, verifier.NLevels = %v",
326						cfg.Coordinator.Circuit.MaxTx, cfg.Coordinator.Circuit.NLevels,
327						verifier.MaxTx, verifier.NLevels,
328					))
329			}
330		}
331
332		coord, err = coordinator.NewCoordinator(
333			coordinator.Config{
334				ForgerAddress:          cfg.Coordinator.ForgerAddress,
335				ConfirmBlocks:          cfg.Coordinator.ConfirmBlocks,
336				L1BatchTimeoutPerc:     cfg.Coordinator.L1BatchTimeoutPerc,
337				ForgeRetryInterval:     cfg.Coordinator.ForgeRetryInterval.Duration,
338				ForgeDelay:             cfg.Coordinator.ForgeDelay.Duration,
339				ForgeNoTxsDelay:        cfg.Coordinator.ForgeNoTxsDelay.Duration,
340				SyncRetryInterval:      cfg.Coordinator.SyncRetryInterval.Duration,
341				PurgeByExtDelInterval:  cfg.Coordinator.PurgeByExtDelInterval.Duration,
342				EthClientAttempts:      cfg.Coordinator.EthClient.Attempts,
343				EthClientAttemptsDelay: cfg.Coordinator.EthClient.AttemptsDelay.Duration,
344				EthNoReuseNonce:        cfg.Coordinator.EthClient.NoReuseNonce,
345				EthTxResendTimeout:     cfg.Coordinator.EthClient.TxResendTimeout.Duration,
346				MaxGasPrice:            cfg.Coordinator.EthClient.MaxGasPrice,
347				GasPriceIncPerc:        cfg.Coordinator.EthClient.GasPriceIncPerc,
348				TxManagerCheckInterval: cfg.Coordinator.EthClient.CheckLoopInterval.Duration,
349				DebugBatchPath:         cfg.Coordinator.Debug.BatchPath,
350				Purger: coordinator.PurgerCfg{
351					PurgeBatchDelay:      cfg.Coordinator.L2DB.PurgeBatchDelay,
352					InvalidateBatchDelay: cfg.Coordinator.L2DB.InvalidateBatchDelay,
353					PurgeBlockDelay:      cfg.Coordinator.L2DB.PurgeBlockDelay,
354					InvalidateBlockDelay: cfg.Coordinator.L2DB.InvalidateBlockDelay,
355				},
356				ForgeBatchGasCost: cfg.Coordinator.EthClient.ForgeBatchGasCost,
357				VerifierIdx:       uint8(verifierIdx),
358				TxProcessorConfig: txProcessorCfg,
359			},
360			historyDB,
361			l2DB,
362			txSelector,
363			batchBuilder,
364			serverProofs,
365			client,
366			&scConsts,
367			&synchronizer.SCVariables{
368				Rollup:   *initSCVars.Rollup,
369				Auction:  *initSCVars.Auction,
370				WDelayer: *initSCVars.WDelayer,
371			},
372		)
373		if err != nil {
374			return nil, tracerr.Wrap(err)
375		}
376	}
377	var nodeAPI *NodeAPI
378	if cfg.API.Address != "" {
379		if cfg.Debug.GinDebugMode {
380			gin.SetMode(gin.DebugMode)
381		} else {
382			gin.SetMode(gin.ReleaseMode)
383		}
384		if cfg.API.UpdateMetricsInterval.Duration == 0 {
385			return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateMetricsInterval: %v",
386				cfg.API.UpdateMetricsInterval.Duration))
387		}
388		if cfg.API.UpdateRecommendedFeeInterval.Duration == 0 {
389			return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateRecommendedFeeInterval: %v",
390				cfg.API.UpdateRecommendedFeeInterval.Duration))
391		}
392		server := gin.Default()
393		coord := false
394		if mode == ModeCoordinator {
395			coord = cfg.Coordinator.API.Coordinator
396		}
397		var err error
398		nodeAPI, err = NewNodeAPI(
399			cfg.API.Address,
400			coord, cfg.API.Explorer,
401			server,
402			historyDB,
403			stateDB,
404			l2DB,
405			&api.Config{
406				RollupConstants:   scConsts.Rollup,
407				AuctionConstants:  scConsts.Auction,
408				WDelayerConstants: scConsts.WDelayer,
409				ChainID:           chainIDU16,
410				HermezAddress:     cfg.SmartContracts.Rollup,
411			},
412			cfg.Coordinator.ForgeDelay.Duration,
413		)
414		if err != nil {
415			return nil, tracerr.Wrap(err)
416		}
417		nodeAPI.api.SetRollupVariables(*initSCVars.Rollup)
418		nodeAPI.api.SetAuctionVariables(*initSCVars.Auction)
419		nodeAPI.api.SetWDelayerVariables(*initSCVars.WDelayer)
420	}
421	var debugAPI *debugapi.DebugAPI
422	if cfg.Debug.APIAddress != "" {
423		debugAPI = debugapi.NewDebugAPI(cfg.Debug.APIAddress, stateDB, sync)
424	}
425	priceUpdater, err := priceupdater.NewPriceUpdater(cfg.PriceUpdater.URL,
426		priceupdater.APIType(cfg.PriceUpdater.Type), historyDB)
427	if err != nil {
428		return nil, tracerr.Wrap(err)
429	}
430	ctx, cancel := context.WithCancel(context.Background())
431	return &Node{
432		nodeAPI:      nodeAPI,
433		debugAPI:     debugAPI,
434		priceUpdater: priceUpdater,
435		coord:        coord,
436		sync:         sync,
437		cfg:          cfg,
438		mode:         mode,
439		sqlConnRead:  dbRead,
440		sqlConnWrite: dbWrite,
441		ctx:          ctx,
442		cancel:       cancel,
443	}, nil
444}
445
446// NodeAPI holds the node http API
447type NodeAPI struct { //nolint:golint
448	api    *api.API
449	engine *gin.Engine
450	addr   string
451}
452
453func handleNoRoute(c *gin.Context) {
454	c.JSON(http.StatusNotFound, gin.H{
455		"error": "404 page not found",
456	})
457}
458
459// NewNodeAPI creates a new NodeAPI (which internally calls api.NewAPI)
460func NewNodeAPI(
461	addr string,
462	coordinatorEndpoints, explorerEndpoints bool,
463	server *gin.Engine,
464	hdb *historydb.HistoryDB,
465	sdb *statedb.StateDB,
466	l2db *l2db.L2DB,
467	config *api.Config,
468	forgeDelay time.Duration,
469) (*NodeAPI, error) {
470	engine := gin.Default()
471	engine.NoRoute(handleNoRoute)
472	engine.Use(cors.Default())
473	_api, err := api.NewAPI(
474		coordinatorEndpoints, explorerEndpoints,
475		engine,
476		hdb,
477		l2db,
478		config,
479		&api.NodeConfig{
480			ForgeDelay: forgeDelay.Seconds(),
481		},
482	)
483	if err != nil {
484		return nil, tracerr.Wrap(err)
485	}
486	return &NodeAPI{
487		addr:   addr,
488		api:    _api,
489		engine: engine,
490	}, nil
491}
492
493// Run starts the http server of the NodeAPI.  To stop it, pass a context with
494// cancelation.
495func (a *NodeAPI) Run(ctx context.Context) error {
496	server := &http.Server{
497		Handler: a.engine,
498		// TODO: Figure out best parameters for production
499		ReadTimeout:    30 * time.Second, //nolint:gomnd
500		WriteTimeout:   30 * time.Second, //nolint:gomnd
501		MaxHeaderBytes: 1 << 20,          //nolint:gomnd
502	}
503	listener, err := net.Listen("tcp", a.addr)
504	if err != nil {
505		return tracerr.Wrap(err)
506	}
507	log.Infof("NodeAPI is ready at %v", a.addr)
508	go func() {
509		if err := server.Serve(listener); err != nil &&
510			tracerr.Unwrap(err) != http.ErrServerClosed {
511			log.Fatalf("Listen: %s\n", err)
512		}
513	}()
514
515	<-ctx.Done()
516	log.Info("Stopping NodeAPI...")
517	ctxTimeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) //nolint:gomnd
518	defer cancel()
519	if err := server.Shutdown(ctxTimeout); err != nil {
520		return tracerr.Wrap(err)
521	}
522	log.Info("NodeAPI done")
523	return nil
524}
525
526func (n *Node) handleNewBlock(ctx context.Context, stats *synchronizer.Stats, vars synchronizer.SCVariablesPtr,
527	batches []common.BatchData) {
528	if n.mode == ModeCoordinator {
529		n.coord.SendMsg(ctx, coordinator.MsgSyncBlock{
530			Stats:   *stats,
531			Vars:    vars,
532			Batches: batches,
533		})
534	}
535	if n.nodeAPI != nil {
536		if vars.Rollup != nil {
537			n.nodeAPI.api.SetRollupVariables(*vars.Rollup)
538		}
539		if vars.Auction != nil {
540			n.nodeAPI.api.SetAuctionVariables(*vars.Auction)
541		}
542		if vars.WDelayer != nil {
543			n.nodeAPI.api.SetWDelayerVariables(*vars.WDelayer)
544		}
545
546		if stats.Synced() {
547			if err := n.nodeAPI.api.UpdateNetworkInfo(
548				stats.Eth.LastBlock, stats.Sync.LastBlock,
549				common.BatchNum(stats.Eth.LastBatchNum),
550				stats.Sync.Auction.CurrentSlot.SlotNum,
551			); err != nil {
552				log.Errorw("API.UpdateNetworkInfo", "err", err)
553			}
554		} else {
555			n.nodeAPI.api.UpdateNetworkInfoBlock(
556				stats.Eth.LastBlock, stats.Sync.LastBlock,
557			)
558		}
559	}
560}
561
562func (n *Node) handleReorg(ctx context.Context, stats *synchronizer.Stats, vars synchronizer.SCVariablesPtr) {
563	if n.mode == ModeCoordinator {
564		n.coord.SendMsg(ctx, coordinator.MsgSyncReorg{
565			Stats: *stats,
566			Vars:  vars,
567		})
568	}
569	if n.nodeAPI != nil {
570		vars := n.sync.SCVars()
571		n.nodeAPI.api.SetRollupVariables(*vars.Rollup)
572		n.nodeAPI.api.SetAuctionVariables(*vars.Auction)
573		n.nodeAPI.api.SetWDelayerVariables(*vars.WDelayer)
574		n.nodeAPI.api.UpdateNetworkInfoBlock(
575			stats.Eth.LastBlock, stats.Sync.LastBlock,
576		)
577	}
578}
579
580// TODO(Edu): Consider keeping the `lastBlock` inside synchronizer so that we
581// don't have to pass it around.
582func (n *Node) syncLoopFn(ctx context.Context, lastBlock *common.Block) (*common.Block, time.Duration, error) {
583	blockData, discarded, err := n.sync.Sync(ctx, lastBlock)
584	stats := n.sync.Stats()
585	if err != nil {
586		// case: error
587		return nil, n.cfg.Synchronizer.SyncLoopInterval.Duration, tracerr.Wrap(err)
588	} else if discarded != nil {
589		// case: reorg
590		log.Infow("Synchronizer.Sync reorg", "discarded", *discarded)
591		vars := n.sync.SCVars()
592		n.handleReorg(ctx, stats, vars)
593		return nil, time.Duration(0), nil
594	} else if blockData != nil {
595		// case: new block
596		vars := synchronizer.SCVariablesPtr{
597			Rollup:   blockData.Rollup.Vars,
598			Auction:  blockData.Auction.Vars,
599			WDelayer: blockData.WDelayer.Vars,
600		}
601		n.handleNewBlock(ctx, stats, vars, blockData.Rollup.Batches)
602		return &blockData.Block, time.Duration(0), nil
603	} else {
604		// case: no block
605		return lastBlock, n.cfg.Synchronizer.SyncLoopInterval.Duration, nil
606	}
607}
608
609// StartSynchronizer starts the synchronizer
610func (n *Node) StartSynchronizer() {
611	log.Info("Starting Synchronizer...")
612
613	// Trigger a manual call to handleNewBlock with the loaded state of the
614	// synchronizer in order to quickly activate the API and Coordinator
615	// and avoid waiting for the next block.  Without this, the API and
616	// Coordinator will not react until the following block (starting from
617	// the last synced one) is synchronized
618	stats := n.sync.Stats()
619	vars := n.sync.SCVars()
620	n.handleNewBlock(n.ctx, stats, vars, []common.BatchData{})
621
622	n.wg.Add(1)
623	go func() {
624		var err error
625		var lastBlock *common.Block
626		waitDuration := time.Duration(0)
627		for {
628			select {
629			case <-n.ctx.Done():
630				log.Info("Synchronizer done")
631				n.wg.Done()
632				return
633			case <-time.After(waitDuration):
634				if lastBlock, waitDuration, err = n.syncLoopFn(n.ctx,
635					lastBlock); err != nil {
636					if n.ctx.Err() != nil {
637						continue
638					}
639					if errors.Is(err, eth.ErrBlockHashMismatchEvent) {
640						log.Warnw("Synchronizer.Sync", "err", err)
641					} else if errors.Is(err, synchronizer.ErrUnknownBlock) {
642						log.Warnw("Synchronizer.Sync", "err", err)
643					} else {
644						log.Errorw("Synchronizer.Sync", "err", err)
645					}
646				}
647			}
648		}
649	}()
650
651	n.wg.Add(1)
652	go func() {
653		for {
654			select {
655			case <-n.ctx.Done():
656				log.Info("PriceUpdater done")
657				n.wg.Done()
658				return
659			case <-time.After(n.cfg.PriceUpdater.Interval.Duration):
660				if err := n.priceUpdater.UpdateTokenList(); err != nil {
661					log.Errorw("PriceUpdater.UpdateTokenList()", "err", err)
662				}
663				n.priceUpdater.UpdatePrices(n.ctx)
664			}
665		}
666	}()
667}
668
669// StartDebugAPI starts the DebugAPI
670func (n *Node) StartDebugAPI() {
671	log.Info("Starting DebugAPI...")
672	n.wg.Add(1)
673	go func() {
674		defer func() {
675			log.Info("DebugAPI routine stopped")
676			n.wg.Done()
677		}()
678		if err := n.debugAPI.Run(n.ctx); err != nil {
679			if n.ctx.Err() != nil {
680				return
681			}
682			log.Fatalw("DebugAPI.Run", "err", err)
683		}
684	}()
685}
686
687// StartNodeAPI starts the NodeAPI
688func (n *Node) StartNodeAPI() {
689	log.Info("Starting NodeAPI...")
690	n.wg.Add(1)
691	go func() {
692		defer func() {
693			log.Info("NodeAPI routine stopped")
694			n.wg.Done()
695		}()
696		if err := n.nodeAPI.Run(n.ctx); err != nil {
697			if n.ctx.Err() != nil {
698				return
699			}
700			log.Fatalw("NodeAPI.Run", "err", err)
701		}
702	}()
703
704	n.wg.Add(1)
705	go func() {
706		// Do an initial update on startup
707		if err := n.nodeAPI.api.UpdateMetrics(); err != nil {
708			log.Errorw("API.UpdateMetrics", "err", err)
709		}
710		for {
711			select {
712			case <-n.ctx.Done():
713				log.Info("API.UpdateMetrics loop done")
714				n.wg.Done()
715				return
716			case <-time.After(n.cfg.API.UpdateMetricsInterval.Duration):
717				if err := n.nodeAPI.api.UpdateMetrics(); err != nil {
718					log.Errorw("API.UpdateMetrics", "err", err)
719				}
720			}
721		}
722	}()
723
724	n.wg.Add(1)
725	go func() {
726		// Do an initial update on startup
727		if err := n.nodeAPI.api.UpdateRecommendedFee(); err != nil {
728			log.Errorw("API.UpdateRecommendedFee", "err", err)
729		}
730		for {
731			select {
732			case <-n.ctx.Done():
733				log.Info("API.UpdateRecommendedFee loop done")
734				n.wg.Done()
735				return
736			case <-time.After(n.cfg.API.UpdateRecommendedFeeInterval.Duration):
737				if err := n.nodeAPI.api.UpdateRecommendedFee(); err != nil {
738					log.Errorw("API.UpdateRecommendedFee", "err", err)
739				}
740			}
741		}
742	}()
743}
744
745// Start the node
746func (n *Node) Start() {
747	log.Infow("Starting node...", "mode", n.mode)
748	if n.debugAPI != nil {
749		n.StartDebugAPI()
750	}
751	if n.nodeAPI != nil {
752		n.StartNodeAPI()
753	}
754	if n.mode == ModeCoordinator {
755		log.Info("Starting Coordinator...")
756		n.coord.Start()
757	}
758	n.StartSynchronizer()
759}
760
761// Stop the node
762func (n *Node) Stop() {
763	log.Infow("Stopping node...")
764	n.cancel()
765	n.wg.Wait()
766	if n.mode == ModeCoordinator {
767		log.Info("Stopping Coordinator...")
768		n.coord.Stop()
769	}
770	// Close kv DBs
771	n.sync.StateDB().Close()
772	if n.mode == ModeCoordinator {
773		n.coord.TxSelector().LocalAccountsDB().Close()
774		n.coord.BatchBuilder().LocalStateDB().Close()
775	}
776}