forked from 0xPolygon/polygon-edge
-
Notifications
You must be signed in to change notification settings - Fork 23
/
server.go
541 lines (460 loc) · 13.5 KB
/
server.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
package server
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"github.com/dogechain-lab/dogechain/command"
"github.com/dogechain-lab/dogechain/command/helper"
"github.com/dogechain-lab/dogechain/crypto"
"github.com/dogechain-lab/dogechain/helper/daemon"
"github.com/dogechain-lab/dogechain/helper/gasprice"
"github.com/dogechain-lab/dogechain/helper/kvdb"
"github.com/dogechain-lab/dogechain/network"
"github.com/dogechain-lab/dogechain/server"
"github.com/dogechain-lab/dogechain/txpool"
"github.com/howeyc/gopass"
"github.com/spf13/cobra"
)
func GetCommand() *cobra.Command {
serverCmd := &cobra.Command{
Use: "server",
Short: "The default command that starts the Dogechain-Lab Dogechain client, by bootstrapping all modules together",
PreRunE: runPreRun,
Run: runCommand,
}
helper.RegisterGRPCAddressFlag(serverCmd)
helper.RegisterLegacyGRPCAddressFlag(serverCmd)
helper.RegisterJSONRPCFlag(serverCmd)
helper.RegisterGraphQLFlag(serverCmd)
setFlags(serverCmd)
return serverCmd
}
func setFlags(cmd *cobra.Command) {
defaultConfig := DefaultConfig()
// basic flags
{
cmd.Flags().StringVar(
¶ms.configPath,
configFlag,
"",
"the path to the CLI config. Supports .json and .hcl",
)
cmd.Flags().StringVar(
¶ms.rawConfig.DataDir,
dataDirFlag,
defaultConfig.DataDir,
"the data directory used for storing Dogechain-Lab Dogechain client data",
)
cmd.Flags().StringVar(
¶ms.rawConfig.GenesisPath,
genesisPathFlag,
defaultConfig.GenesisPath,
"the genesis file used for starting the chain",
)
cmd.Flags().StringVar(
¶ms.rawConfig.RestoreFile,
restoreFlag,
"",
"the path to the archive blockchain data to restore on initialization",
)
}
// block flags
{
cmd.Flags().Uint64Var(
¶ms.rawConfig.BlockTime,
blockTimeFlag,
defaultConfig.BlockTime,
"minimum block time in seconds (at least 1s)",
)
cmd.Flags().BoolVar(
¶ms.rawConfig.BlockBroadcast,
blockBroadcastFlag,
false,
"(deprecated) enable block broadcast when syncing",
)
}
// endpoint flags
{
cmd.Flags().Uint64Var(
¶ms.rawConfig.JSONRPCBatchRequestLimit,
jsonRPCBatchRequestLimitFlag,
defaultConfig.JSONRPCBatchRequestLimit,
"the max length to be considered when handling json-rpc batch requests",
)
cmd.Flags().Uint64Var(
¶ms.rawConfig.JSONRPCBlockRangeLimit,
jsonRPCBlockRangeLimitFlag,
defaultConfig.JSONRPCBlockRangeLimit,
"the max block range to be considered when executing json-rpc requests "+
"that consider fromBlock/toBlock values (e.g. eth_getLogs)",
)
cmd.Flags().BoolVar(
¶ms.rawConfig.EnableWS,
enableWSFlag,
false,
"the flag indicating that node enable websocket service",
)
cmd.Flags().BoolVar(
¶ms.rawConfig.EnableGraphQL,
enableGraphQLFlag,
false,
"the flag indicating that node enable graphql service",
)
cmd.Flags().StringVar(
¶ms.rawConfig.JSONNamespace,
jsonrpcNamespaceFlag,
defaultConfig.JSONNamespace,
"the jsonrpc endpoint namespaces should be enabled "+
"(eth, net, web3, txpool, debug. concatenate with commas or * for all)",
)
}
// leveldb flags
{
cmd.Flags().IntVar(
¶ms.leveldbCacheSize,
leveldbCacheFlag,
kvdb.DefaultLevelDBCache,
"the size of the leveldb cache in MB",
)
cmd.Flags().IntVar(
¶ms.leveldbHandles,
leveldbHandlesFlag,
kvdb.DefaultLevelDBHandles,
"the number of handles to leveldb open files",
)
cmd.Flags().IntVar(
¶ms.leveldbBloomKeyBits,
leveldbBloomKeyBitsFlag,
kvdb.DefaultLevelDBBloomKeyBits,
"the bits of leveldb bloom filters",
)
cmd.Flags().IntVar(
¶ms.leveldbTableSize,
leveldbTableSizeFlag,
kvdb.DefaultLevelDBCompactionTableSize,
"the leveldb 'sorted table' size in MB",
)
cmd.Flags().IntVar(
¶ms.leveldbTotalTableSize,
leveldbTotalTableSizeFlag,
kvdb.DefaultLevelDBCompactionTotalSize,
"limits leveldb total size of 'sorted table' for each level in MB",
)
cmd.Flags().BoolVar(
¶ms.leveldbNoSync,
leveldbNoSyncFlag,
kvdb.DefaultLevelDBNoSync,
"leveldb nosync allows completely disable fsync",
)
}
// log flags
{
cmd.Flags().StringVar(
¶ms.rawConfig.LogLevel,
command.LogLevelFlag,
defaultConfig.LogLevel,
"the log level for console output",
)
cmd.Flags().StringVar(
¶ms.rawConfig.LogFilePath,
logFileLocationFlag,
defaultConfig.LogFilePath,
"write all logs to the file at specified location instead of writing them to console",
)
}
// miner flags
{
cmd.Flags().BoolVar(
¶ms.rawConfig.ShouldSeal,
sealFlag,
false,
"the flag indicating that the client should seal blocks",
)
cmd.Flags().StringVar(
¶ms.rawConfig.BlockGasTarget,
blockGasTargetFlag,
strconv.FormatUint(0, 10),
"the target block gas limit for the chain. If omitted, the value of the parent block is used",
)
cmd.Flags().BoolVar(
¶ms.isDaemon,
daemonFlag,
false,
"the flag indicating that the server ran as daemon",
)
cmd.Flags().StringVar(
¶ms.rawConfig.SecretsConfigPath,
secretsConfigFlag,
"",
"the path to the SecretsManager config file. Used for Hashicorp Vault. "+
"If omitted, the local FS secrets manager is used",
)
}
// network flags
{
cmd.Flags().StringVar(
¶ms.rawConfig.Network.IgnoreDiscoverCIDR,
command.IgnoreDiscoverCIDRFlag,
defaultConfig.Network.IgnoreDiscoverCIDR,
"The comma separated list of CIDR ranges to ignore when discovering peers",
)
cmd.Flags().BoolVar(
¶ms.rawConfig.Network.NoDiscover,
command.NoDiscoverFlag,
defaultConfig.Network.NoDiscover,
"prevent the client from discovering other peers (default: false)",
)
cmd.Flags().Int64Var(
¶ms.rawConfig.Network.MaxPeers,
maxPeersFlag,
-1,
"the client's max number of peers allowed",
)
// override default usage value
cmd.Flag(maxPeersFlag).DefValue = fmt.Sprintf("%d", defaultConfig.Network.MaxPeers)
cmd.Flags().Int64Var(
¶ms.rawConfig.Network.MaxInboundPeers,
maxInboundPeersFlag,
-1,
"the client's max number of inbound peers allowed",
)
// override default usage value
cmd.Flag(maxInboundPeersFlag).DefValue = fmt.Sprintf("%d", defaultConfig.Network.MaxInboundPeers)
cmd.Flags().Int64Var(
¶ms.rawConfig.Network.MaxOutboundPeers,
maxOutboundPeersFlag,
-1,
"the client's max number of outbound peers allowed",
)
// override default usage value
cmd.Flag(maxOutboundPeersFlag).DefValue = fmt.Sprintf("%d", defaultConfig.Network.MaxOutboundPeers)
cmd.Flags().StringVar(
¶ms.rawConfig.Network.Libp2pAddr,
libp2pAddressFlag,
fmt.Sprintf("127.0.0.1:%d", network.DefaultLibp2pPort),
"the address and port for the libp2p service",
)
cmd.Flags().StringVar(
¶ms.rawConfig.Network.NatAddr,
natFlag,
"",
"the external address (address:port), as can be seen by peers",
)
cmd.Flags().StringVar(
¶ms.rawConfig.Network.DNSAddr,
dnsFlag,
"",
"the host DNS address which can be used by a remote peer for connection",
)
cmd.Flags().StringArrayVar(
¶ms.corsAllowedOrigins,
corsOriginFlag,
defaultConfig.Headers.AccessControlAllowOrigins,
"the CORS header indicating whether any JSON-RPC response can be shared with the specified origin",
)
}
// telemetry flags
{
cmd.Flags().StringVar(
¶ms.rawConfig.Telemetry.PrometheusAddr,
prometheusAddressFlag,
"",
"the address and port for the prometheus instrumentation service (address:port). "+
"If only port is defined (:port) it will bind to 0.0.0.0:port",
)
cmd.Flags().BoolVar(
¶ms.rawConfig.Telemetry.EnableIOTimer,
enableIOTimerFlag,
false,
"enable IO timer metrics",
)
}
// txpool flags
{
cmd.Flags().Uint64Var(
¶ms.rawConfig.TxPool.PriceLimit,
priceLimitFlag,
0,
fmt.Sprintf(
"the minimum gas price limit to enforce for acceptance into the pool (default %d)",
defaultConfig.TxPool.PriceLimit,
),
)
cmd.Flags().Uint64Var(
¶ms.rawConfig.TxPool.MaxSlots,
maxSlotsFlag,
txpool.DefaultMaxSlots,
"maximum slots in the pool",
)
// pruning outdated account flags
{
cmd.Flags().Uint64Var(
¶ms.rawConfig.TxPool.PruneTickSeconds,
pruneTickSecondsFlag,
txpool.DefaultPruneTickSeconds,
"tick seconds for pruning account future transactions in the pool",
)
cmd.Flags().Uint64Var(
¶ms.rawConfig.TxPool.PromoteOutdateSeconds,
promoteOutdateSecondsFlag,
txpool.DefaultPromoteOutdateSeconds,
"account in the pool not promoted for a long time would be pruned",
)
}
}
{ // gas price oracle flags
cmd.Flags().IntVar(
¶ms.rawConfig.GPO.Blocks,
gpoBlocksFlag,
gasprice.Defaults.Blocks,
"number of recent blocks to blocks check for gas prices",
)
cmd.Flags().IntVar(
¶ms.rawConfig.GPO.Percentile,
gpoPercentileFlag,
gasprice.Defaults.Percentile,
"the given percentile of a set of recent transaction gas prices",
)
cmd.Flags().Int64Var(
¶ms.gpoMaxGasPrice,
gpoMaxGasPriceFlag,
gasprice.Defaults.MaxPrice.Int64(),
"maximum gasprice recommended by gas price oracle",
)
cmd.Flags().Int64Var(
¶ms.gpoIgnoreGasPrice,
gpoIgnoreGasPriceFlag,
gasprice.Defaults.IgnorePrice.Int64(),
"gas price below which gpo will ignore transactions",
)
}
setDevFlags(cmd)
}
func setDevFlags(cmd *cobra.Command) {
cmd.Flags().BoolVar(
¶ms.isDevMode,
devFlag,
false,
"should the client start in dev mode (default false)",
)
_ = cmd.Flags().MarkHidden(devFlag)
cmd.Flags().Uint64Var(
¶ms.devInterval,
devIntervalFlag,
0,
"the client's dev notification interval in seconds (default 1)",
)
helper.RegisterPprofFlag(cmd)
helper.RegisterJaegerFlag(cmd)
_ = cmd.Flags().MarkHidden(devIntervalFlag)
}
func runPreRun(cmd *cobra.Command, _ []string) error {
// Set the grpc, json and graphql ip:port bindings
// The config file will have precedence over --flag
params.setRawGRPCAddress(helper.GetGRPCAddress(cmd))
params.setRawJSONRPCAddress(helper.GetJSONRPCAddress(cmd))
params.setRawGraphQLAddress(helper.GetGraphQLAddress(cmd))
// Check if the config file has been specified
// Config file settings will override JSON-RPC and GRPC address values
if isConfigFileSpecified(cmd) {
if err := params.initConfigFromFile(); err != nil {
return err
}
}
if err := params.validateFlags(); err != nil {
return err
}
if err := params.initRawParams(); err != nil {
return err
}
return nil
}
func isConfigFileSpecified(cmd *cobra.Command) bool {
return cmd.Flags().Changed(configFlag)
}
func askForConfirmation() string {
reader := bufio.NewReader(os.Stdin)
for {
privateKeyRaw, err := gopass.GetPasswdPrompt("Enter ValidatorKey:", true, os.Stdin, os.Stdout)
if err != nil {
log.Println("Parent process ", os.Getpid(), " passwd prompt err:", err)
}
privateKey, err := crypto.BytesToPrivateKey(privateKeyRaw)
if err != nil {
log.Println("Parent process ", os.Getpid(), " input to private key, err:", err)
}
validatorKeyAddr := crypto.PubKeyToAddress(&privateKey.PublicKey)
log.Println("Parent process ", os.Getpid(), " passwd prompt, ValidatorKey len:", len(params.validatorKey),
", ValidatorKeyAddr: ", validatorKeyAddr.String())
fmt.Printf("ValidatorKey Address: %s [y/n]: ", validatorKeyAddr.String())
response, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return string(privateKeyRaw)
} else if response == "n" || response == "no" {
continue
}
}
}
func runCommand(cmd *cobra.Command, _ []string) {
command.InitializePprofServer(cmd)
outputter := command.InitializeOutputter(cmd)
log.Println("Main process run isDaemon:", params.isDaemon)
// Launch daemons
if params.isDaemon {
// First time, daemonIdx is empty
daemonIdx := os.Getenv(daemon.EnvDaemonIdx)
if len(daemonIdx) == 0 {
params.validatorKey = askForConfirmation()
} else {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Println("Child process ", os.Getpid(), " read pipe data err: ", err)
} else {
log.Println("Child process ", os.Getpid(), " read pipe data: ", len(string(data)))
params.validatorKey = string(data)
}
}
// Create a daemon object
newDaemon := daemon.NewDaemon(daemon.DaemonLog)
newDaemon.MaxCount = daemon.MaxCount
newDaemon.ValidatorKey = params.validatorKey
// Execute daemon mode
newDaemon.Run()
// When params.isDaemon = true,
// the following code will only be executed by the final child process,
// and neither the main process nor the daemon will execute
log.Println("Child process ", os.Getpid(), "start...")
log.Println("Child process ", os.Getpid(), "isDaemon: ", params.isDaemon)
log.Println("Child process ", os.Getpid(), "ValidatorKey len: ", len(params.validatorKey))
}
// pprof flag
params.rawConfig.EnablePprof = helper.GetPprofFlag(cmd)
// jaeger flag
if enableJaeger, jaegerURL := helper.GetJaegerFlag(cmd); enableJaeger {
params.rawConfig.Telemetry.EnableJaeger = enableJaeger
params.rawConfig.Telemetry.JaegerURL = jaegerURL
}
if err := runServerLoop(params.generateConfig(), outputter); err != nil {
outputter.SetError(err)
outputter.WriteOutput()
return
}
}
func runServerLoop(
config *server.Config,
outputter command.OutputFormatter,
) error {
serverInstance, err := server.NewServer(config)
if err != nil {
return err
}
return helper.HandleSignals(serverInstance.Close, outputter)
}