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