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