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, tracerr.Wrap(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,
279			cfg.Coordinator.TxSelector.Path, stateDB, l2DB)
280		if err != nil {
281			return nil, tracerr.Wrap(err)
282		}
283		batchBuilder, err := batchbuilder.NewBatchBuilder(cfg.Coordinator.BatchBuilder.Path,
284			stateDB, 0, uint64(cfg.Coordinator.Circuit.NLevels))
285		if err != nil {
286			return nil, tracerr.Wrap(err)
287		}
288		serverProofs := make([]prover.Client, len(cfg.Coordinator.ServerProofs))
289		for i, serverProofCfg := range cfg.Coordinator.ServerProofs {
290			serverProofs[i] = prover.NewProofServerClient(serverProofCfg.URL,
291				cfg.Coordinator.ProofServerPollInterval.Duration)
292		}
293
294		txProcessorCfg := txprocessor.Config{
295			NLevels:  uint32(cfg.Coordinator.Circuit.NLevels),
296			MaxTx:    uint32(cfg.Coordinator.Circuit.MaxTx),
297			ChainID:  chainIDU16,
298			MaxFeeTx: common.RollupConstMaxFeeIdxCoordinator,
299			MaxL1Tx:  common.RollupConstMaxL1Tx,
300		}
301		var verifierIdx int
302		if cfg.Coordinator.Debug.RollupVerifierIndex == nil {
303			verifierIdx, err = scConsts.Rollup.FindVerifierIdx(
304				cfg.Coordinator.Circuit.MaxTx,
305				cfg.Coordinator.Circuit.NLevels,
306			)
307			if err != nil {
308				return nil, tracerr.Wrap(err)
309			}
310			log.Infow("Found verifier that matches circuit config", "verifierIdx", verifierIdx)
311		} else {
312			verifierIdx = *cfg.Coordinator.Debug.RollupVerifierIndex
313			log.Infow("Using debug verifier index from config", "verifierIdx", verifierIdx)
314			if verifierIdx >= len(scConsts.Rollup.Verifiers) {
315				return nil, tracerr.Wrap(
316					fmt.Errorf("verifierIdx (%v) >= "+
317						"len(scConsts.Rollup.Verifiers) (%v)",
318						verifierIdx, len(scConsts.Rollup.Verifiers)))
319			}
320			verifier := scConsts.Rollup.Verifiers[verifierIdx]
321			if verifier.MaxTx != cfg.Coordinator.Circuit.MaxTx ||
322				verifier.NLevels != cfg.Coordinator.Circuit.NLevels {
323				return nil, tracerr.Wrap(
324					fmt.Errorf("Circuit config and verifier params don't match.  "+
325						"circuit.MaxTx = %v, circuit.NLevels = %v, "+
326						"verifier.MaxTx = %v, verifier.NLevels = %v",
327						cfg.Coordinator.Circuit.MaxTx, cfg.Coordinator.Circuit.NLevels,
328						verifier.MaxTx, verifier.NLevels,
329					))
330			}
331		}
332
333		coord, err = coordinator.NewCoordinator(
334			coordinator.Config{
335				ForgerAddress:          cfg.Coordinator.ForgerAddress,
336				ConfirmBlocks:          cfg.Coordinator.ConfirmBlocks,
337				L1BatchTimeoutPerc:     cfg.Coordinator.L1BatchTimeoutPerc,
338				ForgeRetryInterval:     cfg.Coordinator.ForgeRetryInterval.Duration,
339				ForgeDelay:             cfg.Coordinator.ForgeDelay.Duration,
340				ForgeNoTxsDelay:        cfg.Coordinator.ForgeNoTxsDelay.Duration,
341				SyncRetryInterval:      cfg.Coordinator.SyncRetryInterval.Duration,
342				PurgeByExtDelInterval:  cfg.Coordinator.PurgeByExtDelInterval.Duration,
343				EthClientAttempts:      cfg.Coordinator.EthClient.Attempts,
344				EthClientAttemptsDelay: cfg.Coordinator.EthClient.AttemptsDelay.Duration,
345				EthNoReuseNonce:        cfg.Coordinator.EthClient.NoReuseNonce,
346				EthTxResendTimeout:     cfg.Coordinator.EthClient.TxResendTimeout.Duration,
347				MaxGasPrice:            cfg.Coordinator.EthClient.MaxGasPrice,
348				GasPriceIncPerc:        cfg.Coordinator.EthClient.GasPriceIncPerc,
349				TxManagerCheckInterval: cfg.Coordinator.EthClient.CheckLoopInterval.Duration,
350				DebugBatchPath:         cfg.Coordinator.Debug.BatchPath,
351				Purger: coordinator.PurgerCfg{
352					PurgeBatchDelay:      cfg.Coordinator.L2DB.PurgeBatchDelay,
353					InvalidateBatchDelay: cfg.Coordinator.L2DB.InvalidateBatchDelay,
354					PurgeBlockDelay:      cfg.Coordinator.L2DB.PurgeBlockDelay,
355					InvalidateBlockDelay: cfg.Coordinator.L2DB.InvalidateBlockDelay,
356				},
357				ForgeBatchGasCost: cfg.Coordinator.EthClient.ForgeBatchGasCost,
358				VerifierIdx:       uint8(verifierIdx),
359				TxProcessorConfig: txProcessorCfg,
360			},
361			historyDB,
362			l2DB,
363			txSelector,
364			batchBuilder,
365			serverProofs,
366			client,
367			&scConsts,
368			&synchronizer.SCVariables{
369				Rollup:   *initSCVars.Rollup,
370				Auction:  *initSCVars.Auction,
371				WDelayer: *initSCVars.WDelayer,
372			},
373		)
374		if err != nil {
375			return nil, tracerr.Wrap(err)
376		}
377	}
378	var nodeAPI *NodeAPI
379	if cfg.API.Address != "" {
380		if cfg.Debug.GinDebugMode {
381			gin.SetMode(gin.DebugMode)
382		} else {
383			gin.SetMode(gin.ReleaseMode)
384		}
385		if cfg.API.UpdateMetricsInterval.Duration == 0 {
386			return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateMetricsInterval: %v",
387				cfg.API.UpdateMetricsInterval.Duration))
388		}
389		if cfg.API.UpdateRecommendedFeeInterval.Duration == 0 {
390			return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateRecommendedFeeInterval: %v",
391				cfg.API.UpdateRecommendedFeeInterval.Duration))
392		}
393		server := gin.Default()
394		coord := false
395		if mode == ModeCoordinator {
396			coord = cfg.Coordinator.API.Coordinator
397		}
398		var err error
399		nodeAPI, err = NewNodeAPI(
400			cfg.API.Address,
401			coord, cfg.API.Explorer,
402			server,
403			historyDB,
404			stateDB,
405			l2DB,
406			&api.Config{
407				RollupConstants:   scConsts.Rollup,
408				AuctionConstants:  scConsts.Auction,
409				WDelayerConstants: scConsts.WDelayer,
410				ChainID:           chainIDU16,
411				HermezAddress:     cfg.SmartContracts.Rollup,
412			},
413			cfg.Coordinator.ForgeDelay.Duration,
414		)
415		if err != nil {
416			return nil, tracerr.Wrap(err)
417		}
418		nodeAPI.api.SetRollupVariables(*initSCVars.Rollup)
419		nodeAPI.api.SetAuctionVariables(*initSCVars.Auction)
420		nodeAPI.api.SetWDelayerVariables(*initSCVars.WDelayer)
421	}
422	var debugAPI *debugapi.DebugAPI
423	if cfg.Debug.APIAddress != "" {
424		debugAPI = debugapi.NewDebugAPI(cfg.Debug.APIAddress, stateDB, sync)
425	}
426	priceUpdater, err := priceupdater.NewPriceUpdater(cfg.PriceUpdater.URL,
427		priceupdater.APIType(cfg.PriceUpdater.Type), historyDB)
428	if err != nil {
429		return nil, tracerr.Wrap(err)
430	}
431	ctx, cancel := context.WithCancel(context.Background())
432	return &Node{
433		nodeAPI:      nodeAPI,
434		debugAPI:     debugAPI,
435		priceUpdater: priceUpdater,
436		coord:        coord,
437		sync:         sync,
438		cfg:          cfg,
439		mode:         mode,
440		sqlConnRead:  dbRead,
441		sqlConnWrite: dbWrite,
442		ctx:          ctx,
443		cancel:       cancel,
444	}, nil
445}
446
447// NodeAPI holds the node http API
448type NodeAPI struct { //nolint:golint
449	api    *api.API
450	engine *gin.Engine
451	addr   string
452}
453
454func handleNoRoute(c *gin.Context) {
455	c.JSON(http.StatusNotFound, gin.H{
456		"error": "404 page not found",
457	})
458}
459
460// NewNodeAPI creates a new NodeAPI (which internally calls api.NewAPI)
461func NewNodeAPI(
462	addr string,
463	coordinatorEndpoints, explorerEndpoints bool,
464	server *gin.Engine,
465	hdb *historydb.HistoryDB,
466	sdb *statedb.StateDB,
467	l2db *l2db.L2DB,
468	config *api.Config,
469	forgeDelay time.Duration,
470) (*NodeAPI, error) {
471	engine := gin.Default()
472	engine.NoRoute(handleNoRoute)
473	engine.Use(cors.Default())
474	_api, err := api.NewAPI(
475		coordinatorEndpoints, explorerEndpoints,
476		engine,
477		hdb,
478		l2db,
479		config,
480		&api.NodeConfig{
481			ForgeDelay: forgeDelay.Seconds(),
482		},
483	)
484	if err != nil {
485		return nil, tracerr.Wrap(err)
486	}
487	return &NodeAPI{
488		addr:   addr,
489		api:    _api,
490		engine: engine,
491	}, nil
492}
493
494// Run starts the http server of the NodeAPI.  To stop it, pass a context with
495// cancelation.
496func (a *NodeAPI) Run(ctx context.Context) error {
497	server := &http.Server{
498		Handler: a.engine,
499		// TODO: Figure out best parameters for production
500		ReadTimeout:    30 * time.Second, //nolint:gomnd
501		WriteTimeout:   30 * time.Second, //nolint:gomnd
502		MaxHeaderBytes: 1 << 20,          //nolint:gomnd
503	}
504	listener, err := net.Listen("tcp", a.addr)
505	if err != nil {
506		return tracerr.Wrap(err)
507	}
508	log.Infof("NodeAPI is ready at %v", a.addr)
509	go func() {
510		if err := server.Serve(listener); err != nil &&
511			tracerr.Unwrap(err) != http.ErrServerClosed {
512			log.Fatalf("Listen: %s\n", err)
513		}
514	}()
515
516	<-ctx.Done()
517	log.Info("Stopping NodeAPI...")
518	ctxTimeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) //nolint:gomnd
519	defer cancel()
520	if err := server.Shutdown(ctxTimeout); err != nil {
521		return tracerr.Wrap(err)
522	}
523	log.Info("NodeAPI done")
524	return nil
525}
526
527func (n *Node) handleNewBlock(ctx context.Context, stats *synchronizer.Stats,
528	vars synchronizer.SCVariablesPtr, batches []common.BatchData) {
529	if n.mode == ModeCoordinator {
530		n.coord.SendMsg(ctx, coordinator.MsgSyncBlock{
531			Stats:   *stats,
532			Vars:    vars,
533			Batches: batches,
534		})
535	}
536	if n.nodeAPI != nil {
537		if vars.Rollup != nil {
538			n.nodeAPI.api.SetRollupVariables(*vars.Rollup)
539		}
540		if vars.Auction != nil {
541			n.nodeAPI.api.SetAuctionVariables(*vars.Auction)
542		}
543		if vars.WDelayer != nil {
544			n.nodeAPI.api.SetWDelayerVariables(*vars.WDelayer)
545		}
546
547		if stats.Synced() {
548			if err := n.nodeAPI.api.UpdateNetworkInfo(
549				stats.Eth.LastBlock, stats.Sync.LastBlock,
550				common.BatchNum(stats.Eth.LastBatchNum),
551				stats.Sync.Auction.CurrentSlot.SlotNum,
552			); err != nil {
553				log.Errorw("API.UpdateNetworkInfo", "err", err)
554			}
555		} else {
556			n.nodeAPI.api.UpdateNetworkInfoBlock(
557				stats.Eth.LastBlock, stats.Sync.LastBlock,
558			)
559		}
560	}
561}
562
563func (n *Node) handleReorg(ctx context.Context, stats *synchronizer.Stats,
564	vars synchronizer.SCVariablesPtr) {
565	if n.mode == ModeCoordinator {
566		n.coord.SendMsg(ctx, coordinator.MsgSyncReorg{
567			Stats: *stats,
568			Vars:  vars,
569		})
570	}
571	if n.nodeAPI != nil {
572		vars := n.sync.SCVars()
573		n.nodeAPI.api.SetRollupVariables(*vars.Rollup)
574		n.nodeAPI.api.SetAuctionVariables(*vars.Auction)
575		n.nodeAPI.api.SetWDelayerVariables(*vars.WDelayer)
576		n.nodeAPI.api.UpdateNetworkInfoBlock(
577			stats.Eth.LastBlock, stats.Sync.LastBlock,
578		)
579	}
580}
581
582// TODO(Edu): Consider keeping the `lastBlock` inside synchronizer so that we
583// don't have to pass it around.
584func (n *Node) syncLoopFn(ctx context.Context, lastBlock *common.Block) (*common.Block,
585	time.Duration, error) {
586	blockData, discarded, err := n.sync.Sync(ctx, lastBlock)
587	stats := n.sync.Stats()
588	if err != nil {
589		// case: error
590		return nil, n.cfg.Synchronizer.SyncLoopInterval.Duration, tracerr.Wrap(err)
591	} else if discarded != nil {
592		// case: reorg
593		log.Infow("Synchronizer.Sync reorg", "discarded", *discarded)
594		vars := n.sync.SCVars()
595		n.handleReorg(ctx, stats, vars)
596		return nil, time.Duration(0), nil
597	} else if blockData != nil {
598		// case: new block
599		vars := synchronizer.SCVariablesPtr{
600			Rollup:   blockData.Rollup.Vars,
601			Auction:  blockData.Auction.Vars,
602			WDelayer: blockData.WDelayer.Vars,
603		}
604		n.handleNewBlock(ctx, stats, vars, blockData.Rollup.Batches)
605		return &blockData.Block, time.Duration(0), nil
606	} else {
607		// case: no block
608		return lastBlock, n.cfg.Synchronizer.SyncLoopInterval.Duration, nil
609	}
610}
611
612// StartSynchronizer starts the synchronizer
613func (n *Node) StartSynchronizer() {
614	log.Info("Starting Synchronizer...")
615
616	// Trigger a manual call to handleNewBlock with the loaded state of the
617	// synchronizer in order to quickly activate the API and Coordinator
618	// and avoid waiting for the next block.  Without this, the API and
619	// Coordinator will not react until the following block (starting from
620	// the last synced one) is synchronized
621	stats := n.sync.Stats()
622	vars := n.sync.SCVars()
623	n.handleNewBlock(n.ctx, stats, vars, []common.BatchData{})
624
625	n.wg.Add(1)
626	go func() {
627		var err error
628		var lastBlock *common.Block
629		waitDuration := time.Duration(0)
630		for {
631			select {
632			case <-n.ctx.Done():
633				log.Info("Synchronizer done")
634				n.wg.Done()
635				return
636			case <-time.After(waitDuration):
637				if lastBlock, waitDuration, err = n.syncLoopFn(n.ctx,
638					lastBlock); err != nil {
639					if n.ctx.Err() != nil {
640						continue
641					}
642					if errors.Is(err, eth.ErrBlockHashMismatchEvent) {
643						log.Warnw("Synchronizer.Sync", "err", err)
644					} else if errors.Is(err, synchronizer.ErrUnknownBlock) {
645						log.Warnw("Synchronizer.Sync", "err", err)
646					} else {
647						log.Errorw("Synchronizer.Sync", "err", err)
648					}
649				}
650			}
651		}
652	}()
653
654	n.wg.Add(1)
655	go func() {
656		for {
657			select {
658			case <-n.ctx.Done():
659				log.Info("PriceUpdater done")
660				n.wg.Done()
661				return
662			case <-time.After(n.cfg.PriceUpdater.Interval.Duration):
663				if err := n.priceUpdater.UpdateTokenList(); err != nil {
664					log.Errorw("PriceUpdater.UpdateTokenList()", "err", err)
665				}
666				n.priceUpdater.UpdatePrices(n.ctx)
667			}
668		}
669	}()
670}
671
672// StartDebugAPI starts the DebugAPI
673func (n *Node) StartDebugAPI() {
674	log.Info("Starting DebugAPI...")
675	n.wg.Add(1)
676	go func() {
677		defer func() {
678			log.Info("DebugAPI routine stopped")
679			n.wg.Done()
680		}()
681		if err := n.debugAPI.Run(n.ctx); err != nil {
682			if n.ctx.Err() != nil {
683				return
684			}
685			log.Fatalw("DebugAPI.Run", "err", err)
686		}
687	}()
688}
689
690// StartNodeAPI starts the NodeAPI
691func (n *Node) StartNodeAPI() {
692	log.Info("Starting NodeAPI...")
693	n.wg.Add(1)
694	go func() {
695		defer func() {
696			log.Info("NodeAPI routine stopped")
697			n.wg.Done()
698		}()
699		if err := n.nodeAPI.Run(n.ctx); err != nil {
700			if n.ctx.Err() != nil {
701				return
702			}
703			log.Fatalw("NodeAPI.Run", "err", err)
704		}
705	}()
706
707	n.wg.Add(1)
708	go func() {
709		// Do an initial update on startup
710		if err := n.nodeAPI.api.UpdateMetrics(); err != nil {
711			log.Errorw("API.UpdateMetrics", "err", err)
712		}
713		for {
714			select {
715			case <-n.ctx.Done():
716				log.Info("API.UpdateMetrics loop done")
717				n.wg.Done()
718				return
719			case <-time.After(n.cfg.API.UpdateMetricsInterval.Duration):
720				if err := n.nodeAPI.api.UpdateMetrics(); err != nil {
721					log.Errorw("API.UpdateMetrics", "err", err)
722				}
723			}
724		}
725	}()
726
727	n.wg.Add(1)
728	go func() {
729		// Do an initial update on startup
730		if err := n.nodeAPI.api.UpdateRecommendedFee(); err != nil {
731			log.Errorw("API.UpdateRecommendedFee", "err", err)
732		}
733		for {
734			select {
735			case <-n.ctx.Done():
736				log.Info("API.UpdateRecommendedFee loop done")
737				n.wg.Done()
738				return
739			case <-time.After(n.cfg.API.UpdateRecommendedFeeInterval.Duration):
740				if err := n.nodeAPI.api.UpdateRecommendedFee(); err != nil {
741					log.Errorw("API.UpdateRecommendedFee", "err", err)
742				}
743			}
744		}
745	}()
746}
747
748// Start the node
749func (n *Node) Start() {
750	log.Infow("Starting node...", "mode", n.mode)
751	if n.debugAPI != nil {
752		n.StartDebugAPI()
753	}
754	if n.nodeAPI != nil {
755		n.StartNodeAPI()
756	}
757	if n.mode == ModeCoordinator {
758		log.Info("Starting Coordinator...")
759		n.coord.Start()
760	}
761	n.StartSynchronizer()
762}
763
764// Stop the node
765func (n *Node) Stop() {
766	log.Infow("Stopping node...")
767	n.cancel()
768	n.wg.Wait()
769	if n.mode == ModeCoordinator {
770		log.Info("Stopping Coordinator...")
771		n.coord.Stop()
772	}
773	// Close kv DBs
774	n.sync.StateDB().Close()
775	if n.mode == ModeCoordinator {
776		n.coord.TxSelector().LocalAccountsDB().Close()
777		n.coord.BatchBuilder().LocalStateDB().Close()
778	}
779}