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