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