forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
575 lines (509 loc) · 16.5 KB
/
run.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package main
import (
"context"
"fmt"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"runtime"
"time"
"github.com/0xPolygonHermez/zkevm-node"
"github.com/0xPolygonHermez/zkevm-node/aggregator"
"github.com/0xPolygonHermez/zkevm-node/config"
"github.com/0xPolygonHermez/zkevm-node/db"
"github.com/0xPolygonHermez/zkevm-node/etherman"
"github.com/0xPolygonHermez/zkevm-node/ethtxmanager"
"github.com/0xPolygonHermez/zkevm-node/event"
"github.com/0xPolygonHermez/zkevm-node/event/nileventstorage"
"github.com/0xPolygonHermez/zkevm-node/event/pgeventstorage"
"github.com/0xPolygonHermez/zkevm-node/gasprice"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/client"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/merkletree"
"github.com/0xPolygonHermez/zkevm-node/metrics"
"github.com/0xPolygonHermez/zkevm-node/pool"
"github.com/0xPolygonHermez/zkevm-node/pool/pgpoolstorage"
"github.com/0xPolygonHermez/zkevm-node/sequencer"
"github.com/0xPolygonHermez/zkevm-node/sequencesender"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/0xPolygonHermez/zkevm-node/state/runtime/executor"
"github.com/0xPolygonHermez/zkevm-node/synchronizer"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli/v2"
)
func start(cliCtx *cli.Context) error {
c, err := config.Load(cliCtx, true)
if err != nil {
return err
}
setupLog(c.Log)
if c.Log.Environment == log.EnvironmentDevelopment {
zkevm.PrintVersion(os.Stdout)
log.Info("Starting application")
} else if c.Log.Environment == log.EnvironmentProduction {
logVersion()
}
if c.Metrics.Enabled {
metrics.Init()
}
components := cliCtx.StringSlice(config.FlagComponents)
// Only runs migration if the component is the synchronizer and if the flag is deactivated
if !cliCtx.Bool(config.FlagMigrations) {
for _, comp := range components {
if comp == SYNCHRONIZER {
runStateMigrations(c.StateDB)
}
}
}
checkStateMigrations(c.StateDB)
// Decide if this node instance needs an executor and/or a state tree
var needsExecutor, needsStateTree bool
for _, component := range components {
switch component {
case SEQUENCER, RPC, SYNCHRONIZER:
needsExecutor = true
needsStateTree = true
}
}
// Event log
var eventLog *event.EventLog
var eventStorage event.Storage
if c.EventLog.DB.Name != "" {
eventStorage, err = pgeventstorage.NewPostgresEventStorage(c.EventLog.DB)
if err != nil {
log.Fatal(err)
}
} else {
eventStorage, err = nileventstorage.NewNilEventStorage()
if err != nil {
log.Fatal(err)
}
}
eventLog = event.NewEventLog(c.EventLog, eventStorage)
// Core State DB
stateSqlDB, err := db.NewSQLDB(c.StateDB)
if err != nil {
log.Fatal(err)
}
var (
cancelFuncs []context.CancelFunc
etherman *etherman.Client
)
etherman, err = newEtherman(*c)
if err != nil {
log.Fatal(err)
}
// READ CHAIN ID FROM POE SC
l2ChainID, err := etherman.GetL2ChainID()
if err != nil {
log.Fatal(err)
}
// Read Fork ID FROM POE SC
forkIDIntervals, err := etherman.GetForks(cliCtx.Context, c.NetworkConfig.Genesis.GenesisBlockNum)
if err != nil {
log.Fatal("error getting forks. Please check the configuration. Error: ", err)
} else if len(forkIDIntervals) == 0 {
log.Fatal("error: no forkID received. It should receive at least one, please check the configuration...")
}
currentForkID := forkIDIntervals[len(forkIDIntervals)-1].ForkId
log.Infof("Fork ID read from POE SC = %v", forkIDIntervals[len(forkIDIntervals)-1].ForkId)
c.Aggregator.ChainID = l2ChainID
c.Aggregator.ForkId = currentForkID
log.Infof("Chain ID read from POE SC = %v", l2ChainID)
ctx := context.Background()
st := newState(ctx, c, l2ChainID, forkIDIntervals, stateSqlDB, eventLog, needsExecutor, needsStateTree)
ethTxManagerStorage, err := ethtxmanager.NewPostgresStorage(c.StateDB)
if err != nil {
log.Fatal(err)
}
etm := ethtxmanager.New(c.EthTxManager, etherman, ethTxManagerStorage, st)
ev := &event.Event{
ReceivedAt: time.Now(),
Source: event.Source_Node,
Level: event.Level_Info,
EventID: event.EventID_NodeComponentStarted,
}
var poolInstance *pool.Pool
if c.Metrics.ProfilingEnabled {
go startProfilingHttpServer(c.Metrics)
}
for _, component := range components {
switch component {
case AGGREGATOR:
ev.Component = event.Component_Aggregator
ev.Description = "Running aggregator"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
go runAggregator(ctx, c.Aggregator, etherman, etm, st)
case SEQUENCER:
ev.Component = event.Component_Sequencer
ev.Description = "Running sequencer"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
if poolInstance == nil {
poolInstance = createPool(c.Pool, l2ChainID, st, eventLog)
}
seq := createSequencer(*c, poolInstance, ethTxManagerStorage, st, eventLog)
go seq.Start(ctx)
case SEQUENCE_SENDER:
ev.Component = event.Component_Sequence_Sender
ev.Description = "Running sequence sender"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
if poolInstance == nil {
poolInstance = createPool(c.Pool, l2ChainID, st, eventLog)
}
seqSender := createSequenceSender(*c, poolInstance, ethTxManagerStorage, st, eventLog)
go seqSender.Start(ctx)
case RPC:
ev.Component = event.Component_RPC
ev.Description = "Running JSON-RPC server"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
if poolInstance == nil {
poolInstance = createPool(c.Pool, l2ChainID, st, eventLog)
}
if c.RPC.EnableL2SuggestedGasPricePolling {
// Needed for rejecting transactions with too low gas price
poolInstance.StartPollingMinSuggestedGasPrice(ctx)
}
apis := map[string]bool{}
for _, a := range cliCtx.StringSlice(config.FlagHTTPAPI) {
apis[a] = true
}
go runJSONRPCServer(*c, etherman, l2ChainID, poolInstance, st, apis)
case SYNCHRONIZER:
ev.Component = event.Component_Synchronizer
ev.Description = "Running synchronizer"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
if poolInstance == nil {
poolInstance = createPool(c.Pool, l2ChainID, st, eventLog)
}
go runSynchronizer(*c, etherman, etm, st, poolInstance, eventLog)
case ETHTXMANAGER:
ev.Component = event.Component_EthTxManager
ev.Description = "Running eth tx manager service"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
etm := createEthTxManager(*c, ethTxManagerStorage, st)
go etm.Start()
case L2GASPRICER:
ev.Component = event.Component_GasPricer
ev.Description = "Running L2 gasPricer"
err := eventLog.LogEvent(ctx, ev)
if err != nil {
log.Fatal(err)
}
if poolInstance == nil {
poolInstance = createPool(c.Pool, l2ChainID, st, eventLog)
}
go runL2GasPriceSuggester(c.L2GasPriceSuggester, st, poolInstance, etherman)
}
}
if c.Metrics.Enabled {
go startMetricsHttpServer(c.Metrics)
}
waitSignal(cancelFuncs)
return nil
}
func setupLog(c log.Config) {
log.Init(c)
}
func runStateMigrations(c db.Config) {
runMigrations(c, db.StateMigrationName)
}
func checkStateMigrations(c db.Config) {
err := db.CheckMigrations(c, db.StateMigrationName)
if err != nil {
log.Fatal(err)
}
}
func runPoolMigrations(c db.Config) {
runMigrations(c, db.PoolMigrationName)
}
func runMigrations(c db.Config, name string) {
log.Infof("running migrations for %v", name)
err := db.RunMigrationsUp(c, name)
if err != nil {
log.Fatal(err)
}
}
func newEtherman(c config.Config) (*etherman.Client, error) {
etherman, err := etherman.NewClient(c.Etherman, c.NetworkConfig.L1Config)
if err != nil {
return nil, err
}
return etherman, nil
}
func runSynchronizer(cfg config.Config, etherman *etherman.Client, ethTxManager *ethtxmanager.Client, st *state.State, pool *pool.Pool, eventLog *event.EventLog) {
var trustedSequencerURL string
var err error
if !cfg.IsTrustedSequencer {
if cfg.Synchronizer.TrustedSequencerURL != "" {
trustedSequencerURL = cfg.Synchronizer.TrustedSequencerURL
} else {
log.Debug("getting trusted sequencer URL from smc")
trustedSequencerURL, err = etherman.GetTrustedSequencerURL()
if err != nil {
log.Fatal("error getting trusted sequencer URI. Error: %v", err)
}
}
log.Debug("trustedSequencerURL ", trustedSequencerURL)
}
zkEVMClient := client.NewClient(trustedSequencerURL)
sy, err := synchronizer.NewSynchronizer(
cfg.IsTrustedSequencer, etherman, st, pool, ethTxManager,
zkEVMClient, eventLog, cfg.NetworkConfig.Genesis, cfg.Synchronizer,
)
if err != nil {
log.Fatal(err)
}
if err := sy.Sync(); err != nil {
log.Fatal(err)
}
}
func runJSONRPCServer(c config.Config, etherman *etherman.Client, chainID uint64, pool *pool.Pool, st *state.State, apis map[string]bool) {
var err error
storage := jsonrpc.NewStorage()
c.RPC.MaxCumulativeGasUsed = c.Sequencer.MaxCumulativeGasUsed
if !c.IsTrustedSequencer {
if c.RPC.SequencerNodeURI == "" {
log.Debug("getting trusted sequencer URL from smc")
c.RPC.SequencerNodeURI, err = etherman.GetTrustedSequencerURL()
if err != nil {
log.Fatal("error getting trusted sequencer URI. Error: %v", err)
}
}
log.Debug("SequencerNodeURI ", c.RPC.SequencerNodeURI)
}
services := []jsonrpc.Service{}
if _, ok := apis[jsonrpc.APIEth]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APIEth,
Service: jsonrpc.NewEthEndpoints(c.RPC, chainID, pool, st, storage),
})
}
if _, ok := apis[jsonrpc.APINet]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APINet,
Service: jsonrpc.NewNetEndpoints(c.RPC, chainID),
})
}
if _, ok := apis[jsonrpc.APIZKEVM]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APIZKEVM,
Service: jsonrpc.NewZKEVMEndpoints(c.RPC, st),
})
}
if _, ok := apis[jsonrpc.APITxPool]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APITxPool,
Service: &jsonrpc.TxPoolEndpoints{},
})
}
if _, ok := apis[jsonrpc.APIDebug]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APIDebug,
Service: jsonrpc.NewDebugEndpoints(c.RPC, st),
})
}
if _, ok := apis[jsonrpc.APIWeb3]; ok {
services = append(services, jsonrpc.Service{
Name: jsonrpc.APIWeb3,
Service: &jsonrpc.Web3Endpoints{},
})
}
if err := jsonrpc.NewServer(c.RPC, chainID, pool, st, storage, services).Start(); err != nil {
log.Fatal(err)
}
}
func createSequencer(cfg config.Config, pool *pool.Pool, etmStorage *ethtxmanager.PostgresStorage, st *state.State, eventLog *event.EventLog) *sequencer.Sequencer {
etherman, err := newEtherman(cfg)
if err != nil {
log.Fatal(err)
}
ethTxManager := ethtxmanager.New(cfg.EthTxManager, etherman, etmStorage, st)
seq, err := sequencer.New(cfg.Sequencer, pool, st, etherman, ethTxManager, eventLog)
if err != nil {
log.Fatal(err)
}
return seq
}
func createSequenceSender(cfg config.Config, pool *pool.Pool, etmStorage *ethtxmanager.PostgresStorage, st *state.State, eventLog *event.EventLog) *sequencesender.SequenceSender {
etherman, err := newEtherman(cfg)
if err != nil {
log.Fatal(err)
}
for _, privateKey := range cfg.SequenceSender.PrivateKeys {
_, err := etherman.LoadAuthFromKeyStore(privateKey.Path, privateKey.Password)
if err != nil {
log.Fatal(err)
}
}
cfg.SequenceSender.ForkUpgradeBatchNumber = cfg.ForkUpgradeBatchNumber
ethTxManager := ethtxmanager.New(cfg.EthTxManager, etherman, etmStorage, st)
seqSender, err := sequencesender.New(cfg.SequenceSender, st, etherman, ethTxManager, eventLog)
if err != nil {
log.Fatal(err)
}
return seqSender
}
func runAggregator(ctx context.Context, c aggregator.Config, etherman *etherman.Client, ethTxManager *ethtxmanager.Client, st *state.State) {
agg, err := aggregator.New(c, st, ethTxManager, etherman)
if err != nil {
log.Fatal(err)
}
err = agg.Start(ctx)
if err != nil {
log.Fatal(err)
}
}
// runL2GasPriceSuggester init gas price gasPriceEstimator based on type in config.
func runL2GasPriceSuggester(cfg gasprice.Config, state *state.State, pool *pool.Pool, etherman *etherman.Client) {
ctx := context.Background()
gasprice.NewL2GasPriceSuggester(ctx, cfg, pool, etherman, state)
}
func waitSignal(cancelFuncs []context.CancelFunc) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
for sig := range signals {
switch sig {
case os.Interrupt, os.Kill:
log.Info("terminating application gracefully...")
exitStatus := 0
for _, cancel := range cancelFuncs {
cancel()
}
os.Exit(exitStatus)
}
}
}
func newState(ctx context.Context, c *config.Config, l2ChainID uint64, forkIDIntervals []state.ForkIDInterval, sqlDB *pgxpool.Pool, eventLog *event.EventLog, needsExecutor, needsStateTree bool) *state.State {
stateDb := state.NewPostgresStorage(sqlDB)
// Executor
var executorClient executor.ExecutorServiceClient
if needsExecutor {
executorClient, _, _ = executor.NewExecutorClient(ctx, c.Executor)
}
// State Tree
var stateTree *merkletree.StateTree
if needsStateTree {
stateDBClient, _, _ := merkletree.NewMTDBServiceClient(ctx, c.MTClient)
stateTree = merkletree.NewStateTree(stateDBClient)
}
stateCfg := state.Config{
MaxCumulativeGasUsed: c.Sequencer.MaxCumulativeGasUsed,
ChainID: l2ChainID,
ForkIDIntervals: forkIDIntervals,
MaxResourceExhaustedAttempts: c.Executor.MaxResourceExhaustedAttempts,
WaitOnResourceExhaustion: c.Executor.WaitOnResourceExhaustion,
ForkUpgradeBatchNumber: c.ForkUpgradeBatchNumber,
ForkUpgradeNewForkId: c.ForkUpgradeNewForkId,
}
st := state.NewState(stateCfg, stateDb, executorClient, stateTree, eventLog)
return st
}
func createPool(cfgPool pool.Config, l2ChainID uint64, st *state.State, eventLog *event.EventLog) *pool.Pool {
runPoolMigrations(cfgPool.DB)
poolStorage, err := pgpoolstorage.NewPostgresPoolStorage(cfgPool.DB)
if err != nil {
log.Fatal(err)
}
poolInstance := pool.NewPool(cfgPool, poolStorage, st, l2ChainID, eventLog)
return poolInstance
}
func createEthTxManager(cfg config.Config, etmStorage *ethtxmanager.PostgresStorage, st *state.State) *ethtxmanager.Client {
etherman, err := newEtherman(cfg)
if err != nil {
log.Fatal(err)
}
for _, privateKey := range cfg.EthTxManager.PrivateKeys {
_, err := etherman.LoadAuthFromKeyStore(privateKey.Path, privateKey.Password)
if err != nil {
log.Fatal(err)
}
}
etm := ethtxmanager.New(cfg.EthTxManager, etherman, etmStorage, st)
return etm
}
func startProfilingHttpServer(c metrics.Config) {
const two = 2
mux := http.NewServeMux()
address := fmt.Sprintf("%s:%d", c.ProfilingHost, c.ProfilingPort)
lis, err := net.Listen("tcp", address)
if err != nil {
log.Errorf("failed to create tcp listener for profiling: %v", err)
return
}
mux.HandleFunc(metrics.ProfilingIndexEndpoint, pprof.Index)
mux.HandleFunc(metrics.ProfileEndpoint, pprof.Profile)
mux.HandleFunc(metrics.ProfilingCmdEndpoint, pprof.Cmdline)
mux.HandleFunc(metrics.ProfilingSymbolEndpoint, pprof.Symbol)
mux.HandleFunc(metrics.ProfilingTraceEndpoint, pprof.Trace)
profilingServer := &http.Server{
Handler: mux,
ReadHeaderTimeout: two * time.Minute,
ReadTimeout: two * time.Minute,
}
log.Infof("profiling server listening on port %d", c.ProfilingPort)
if err := profilingServer.Serve(lis); err != nil {
if err == http.ErrServerClosed {
log.Warnf("http server for profiling stopped")
return
}
log.Errorf("closed http connection for profiling server: %v", err)
return
}
}
func startMetricsHttpServer(c metrics.Config) {
const ten = 10
mux := http.NewServeMux()
address := fmt.Sprintf("%s:%d", c.Host, c.Port)
lis, err := net.Listen("tcp", address)
if err != nil {
log.Errorf("failed to create tcp listener for metrics: %v", err)
return
}
mux.Handle(metrics.Endpoint, promhttp.Handler())
metricsServer := &http.Server{
Handler: mux,
ReadHeaderTimeout: ten * time.Second,
ReadTimeout: ten * time.Second,
}
log.Infof("metrics server listening on port %d", c.Port)
if err := metricsServer.Serve(lis); err != nil {
if err == http.ErrServerClosed {
log.Warnf("http server for metrics stopped")
return
}
log.Errorf("closed http connection for metrics server: %v", err)
return
}
}
func logVersion() {
log.Infow("Starting application",
// node version is already logged by default
"gitRevision", zkevm.GitRev,
"gitBranch", zkevm.GitBranch,
"goVersion", runtime.Version(),
"built", zkevm.BuildDate,
"os/arch", fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
)
}