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