github.com/ethereum/go-ethereum@v1.14.4-0.20240516095835-473ee8fc07a3/cmd/geth/config.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // go-ethereum is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 16 17 package main 18 19 import ( 20 "bufio" 21 "errors" 22 "fmt" 23 "os" 24 "reflect" 25 "runtime" 26 "strings" 27 "unicode" 28 29 "github.com/ethereum/go-ethereum/accounts" 30 "github.com/ethereum/go-ethereum/accounts/external" 31 "github.com/ethereum/go-ethereum/accounts/keystore" 32 "github.com/ethereum/go-ethereum/accounts/scwallet" 33 "github.com/ethereum/go-ethereum/accounts/usbwallet" 34 "github.com/ethereum/go-ethereum/beacon/blsync" 35 "github.com/ethereum/go-ethereum/cmd/utils" 36 "github.com/ethereum/go-ethereum/common" 37 "github.com/ethereum/go-ethereum/common/hexutil" 38 "github.com/ethereum/go-ethereum/eth/catalyst" 39 "github.com/ethereum/go-ethereum/eth/ethconfig" 40 "github.com/ethereum/go-ethereum/internal/flags" 41 "github.com/ethereum/go-ethereum/internal/version" 42 "github.com/ethereum/go-ethereum/log" 43 "github.com/ethereum/go-ethereum/metrics" 44 "github.com/ethereum/go-ethereum/node" 45 "github.com/ethereum/go-ethereum/params" 46 "github.com/ethereum/go-ethereum/rpc" 47 "github.com/naoina/toml" 48 "github.com/urfave/cli/v2" 49 ) 50 51 var ( 52 dumpConfigCommand = &cli.Command{ 53 Action: dumpConfig, 54 Name: "dumpconfig", 55 Usage: "Export configuration values in a TOML format", 56 ArgsUsage: "<dumpfile (optional)>", 57 Flags: flags.Merge(nodeFlags, rpcFlags), 58 Description: `Export configuration values in TOML format (to stdout by default).`, 59 } 60 61 configFileFlag = &cli.StringFlag{ 62 Name: "config", 63 Usage: "TOML configuration file", 64 Category: flags.EthCategory, 65 } 66 ) 67 68 // These settings ensure that TOML keys use the same names as Go struct fields. 69 var tomlSettings = toml.Config{ 70 NormFieldName: func(rt reflect.Type, key string) string { 71 return key 72 }, 73 FieldToKey: func(rt reflect.Type, field string) string { 74 return field 75 }, 76 MissingField: func(rt reflect.Type, field string) error { 77 id := fmt.Sprintf("%s.%s", rt.String(), field) 78 if deprecated(id) { 79 log.Warn("Config field is deprecated and won't have an effect", "name", id) 80 return nil 81 } 82 var link string 83 if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" { 84 link = fmt.Sprintf(", see https://godoc.org/%s#%s for available fields", rt.PkgPath(), rt.Name()) 85 } 86 return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link) 87 }, 88 } 89 90 type ethstatsConfig struct { 91 URL string `toml:",omitempty"` 92 } 93 94 type gethConfig struct { 95 Eth ethconfig.Config 96 Node node.Config 97 Ethstats ethstatsConfig 98 Metrics metrics.Config 99 } 100 101 func loadConfig(file string, cfg *gethConfig) error { 102 f, err := os.Open(file) 103 if err != nil { 104 return err 105 } 106 defer f.Close() 107 108 err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg) 109 // Add file name to errors that have a line number. 110 if _, ok := err.(*toml.LineError); ok { 111 err = errors.New(file + ", " + err.Error()) 112 } 113 return err 114 } 115 116 func defaultNodeConfig() node.Config { 117 git, _ := version.VCS() 118 cfg := node.DefaultConfig 119 cfg.Name = clientIdentifier 120 cfg.Version = params.VersionWithCommit(git.Commit, git.Date) 121 cfg.HTTPModules = append(cfg.HTTPModules, "eth") 122 cfg.WSModules = append(cfg.WSModules, "eth") 123 cfg.IPCPath = "geth.ipc" 124 return cfg 125 } 126 127 // loadBaseConfig loads the gethConfig based on the given command line 128 // parameters and config file. 129 func loadBaseConfig(ctx *cli.Context) gethConfig { 130 // Load defaults. 131 cfg := gethConfig{ 132 Eth: ethconfig.Defaults, 133 Node: defaultNodeConfig(), 134 Metrics: metrics.DefaultConfig, 135 } 136 137 // Load config file. 138 if file := ctx.String(configFileFlag.Name); file != "" { 139 if err := loadConfig(file, &cfg); err != nil { 140 utils.Fatalf("%v", err) 141 } 142 } 143 144 // Apply flags. 145 utils.SetNodeConfig(ctx, &cfg.Node) 146 return cfg 147 } 148 149 // makeConfigNode loads geth configuration and creates a blank node instance. 150 func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) { 151 cfg := loadBaseConfig(ctx) 152 stack, err := node.New(&cfg.Node) 153 if err != nil { 154 utils.Fatalf("Failed to create the protocol stack: %v", err) 155 } 156 // Node doesn't by default populate account manager backends 157 if err := setAccountManagerBackends(stack.Config(), stack.AccountManager(), stack.KeyStoreDir()); err != nil { 158 utils.Fatalf("Failed to set account manager backends: %v", err) 159 } 160 161 utils.SetEthConfig(ctx, stack, &cfg.Eth) 162 if ctx.IsSet(utils.EthStatsURLFlag.Name) { 163 cfg.Ethstats.URL = ctx.String(utils.EthStatsURLFlag.Name) 164 } 165 applyMetricConfig(ctx, &cfg) 166 167 return stack, cfg 168 } 169 170 // makeFullNode loads geth configuration and creates the Ethereum backend. 171 func makeFullNode(ctx *cli.Context) *node.Node { 172 stack, cfg := makeConfigNode(ctx) 173 if ctx.IsSet(utils.OverrideCancun.Name) { 174 v := ctx.Uint64(utils.OverrideCancun.Name) 175 cfg.Eth.OverrideCancun = &v 176 } 177 if ctx.IsSet(utils.OverrideVerkle.Name) { 178 v := ctx.Uint64(utils.OverrideVerkle.Name) 179 cfg.Eth.OverrideVerkle = &v 180 } 181 182 backend, eth := utils.RegisterEthService(stack, &cfg.Eth) 183 184 // Create gauge with geth system and build information 185 if eth != nil { // The 'eth' backend may be nil in light mode 186 var protos []string 187 for _, p := range eth.Protocols() { 188 protos = append(protos, fmt.Sprintf("%v/%d", p.Name, p.Version)) 189 } 190 metrics.NewRegisteredGaugeInfo("geth/info", nil).Update(metrics.GaugeInfoValue{ 191 "arch": runtime.GOARCH, 192 "os": runtime.GOOS, 193 "version": cfg.Node.Version, 194 "protocols": strings.Join(protos, ","), 195 }) 196 } 197 198 // Configure log filter RPC API. 199 filterSystem := utils.RegisterFilterAPI(stack, backend, &cfg.Eth) 200 201 // Configure GraphQL if requested. 202 if ctx.IsSet(utils.GraphQLEnabledFlag.Name) { 203 utils.RegisterGraphQLService(stack, backend, filterSystem, &cfg.Node) 204 } 205 // Add the Ethereum Stats daemon if requested. 206 if cfg.Ethstats.URL != "" { 207 utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL) 208 } 209 // Configure full-sync tester service if requested 210 if ctx.IsSet(utils.SyncTargetFlag.Name) { 211 hex := hexutil.MustDecode(ctx.String(utils.SyncTargetFlag.Name)) 212 if len(hex) != common.HashLength { 213 utils.Fatalf("invalid sync target length: have %d, want %d", len(hex), common.HashLength) 214 } 215 utils.RegisterFullSyncTester(stack, eth, common.BytesToHash(hex)) 216 } 217 218 if ctx.IsSet(utils.DeveloperFlag.Name) { 219 // Start dev mode. 220 simBeacon, err := catalyst.NewSimulatedBeacon(ctx.Uint64(utils.DeveloperPeriodFlag.Name), eth) 221 if err != nil { 222 utils.Fatalf("failed to register dev mode catalyst service: %v", err) 223 } 224 catalyst.RegisterSimulatedBeaconAPIs(stack, simBeacon) 225 stack.RegisterLifecycle(simBeacon) 226 } else if ctx.IsSet(utils.BeaconApiFlag.Name) { 227 // Start blsync mode. 228 srv := rpc.NewServer() 229 srv.RegisterName("engine", catalyst.NewConsensusAPI(eth)) 230 blsyncer := blsync.NewClient(ctx) 231 blsyncer.SetEngineRPC(rpc.DialInProc(srv)) 232 stack.RegisterLifecycle(blsyncer) 233 } else { 234 // Launch the engine API for interacting with external consensus client. 235 err := catalyst.Register(stack, eth) 236 if err != nil { 237 utils.Fatalf("failed to register catalyst service: %v", err) 238 } 239 } 240 return stack 241 } 242 243 // dumpConfig is the dumpconfig command. 244 func dumpConfig(ctx *cli.Context) error { 245 _, cfg := makeConfigNode(ctx) 246 comment := "" 247 248 if cfg.Eth.Genesis != nil { 249 cfg.Eth.Genesis = nil 250 comment += "# Note: this config doesn't contain the genesis block.\n\n" 251 } 252 253 out, err := tomlSettings.Marshal(&cfg) 254 if err != nil { 255 return err 256 } 257 258 dump := os.Stdout 259 if ctx.NArg() > 0 { 260 dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) 261 if err != nil { 262 return err 263 } 264 defer dump.Close() 265 } 266 dump.WriteString(comment) 267 dump.Write(out) 268 269 return nil 270 } 271 272 func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) { 273 if ctx.IsSet(utils.MetricsEnabledFlag.Name) { 274 cfg.Metrics.Enabled = ctx.Bool(utils.MetricsEnabledFlag.Name) 275 } 276 if ctx.IsSet(utils.MetricsEnabledExpensiveFlag.Name) { 277 log.Warn("Expensive metrics are collected by default, please remove this flag", "flag", utils.MetricsEnabledExpensiveFlag.Name) 278 } 279 if ctx.IsSet(utils.MetricsHTTPFlag.Name) { 280 cfg.Metrics.HTTP = ctx.String(utils.MetricsHTTPFlag.Name) 281 } 282 if ctx.IsSet(utils.MetricsPortFlag.Name) { 283 cfg.Metrics.Port = ctx.Int(utils.MetricsPortFlag.Name) 284 } 285 if ctx.IsSet(utils.MetricsEnableInfluxDBFlag.Name) { 286 cfg.Metrics.EnableInfluxDB = ctx.Bool(utils.MetricsEnableInfluxDBFlag.Name) 287 } 288 if ctx.IsSet(utils.MetricsInfluxDBEndpointFlag.Name) { 289 cfg.Metrics.InfluxDBEndpoint = ctx.String(utils.MetricsInfluxDBEndpointFlag.Name) 290 } 291 if ctx.IsSet(utils.MetricsInfluxDBDatabaseFlag.Name) { 292 cfg.Metrics.InfluxDBDatabase = ctx.String(utils.MetricsInfluxDBDatabaseFlag.Name) 293 } 294 if ctx.IsSet(utils.MetricsInfluxDBUsernameFlag.Name) { 295 cfg.Metrics.InfluxDBUsername = ctx.String(utils.MetricsInfluxDBUsernameFlag.Name) 296 } 297 if ctx.IsSet(utils.MetricsInfluxDBPasswordFlag.Name) { 298 cfg.Metrics.InfluxDBPassword = ctx.String(utils.MetricsInfluxDBPasswordFlag.Name) 299 } 300 if ctx.IsSet(utils.MetricsInfluxDBTagsFlag.Name) { 301 cfg.Metrics.InfluxDBTags = ctx.String(utils.MetricsInfluxDBTagsFlag.Name) 302 } 303 if ctx.IsSet(utils.MetricsEnableInfluxDBV2Flag.Name) { 304 cfg.Metrics.EnableInfluxDBV2 = ctx.Bool(utils.MetricsEnableInfluxDBV2Flag.Name) 305 } 306 if ctx.IsSet(utils.MetricsInfluxDBTokenFlag.Name) { 307 cfg.Metrics.InfluxDBToken = ctx.String(utils.MetricsInfluxDBTokenFlag.Name) 308 } 309 if ctx.IsSet(utils.MetricsInfluxDBBucketFlag.Name) { 310 cfg.Metrics.InfluxDBBucket = ctx.String(utils.MetricsInfluxDBBucketFlag.Name) 311 } 312 if ctx.IsSet(utils.MetricsInfluxDBOrganizationFlag.Name) { 313 cfg.Metrics.InfluxDBOrganization = ctx.String(utils.MetricsInfluxDBOrganizationFlag.Name) 314 } 315 } 316 317 func deprecated(field string) bool { 318 switch field { 319 case "ethconfig.Config.EVMInterpreter": 320 return true 321 case "ethconfig.Config.EWASMInterpreter": 322 return true 323 case "ethconfig.Config.TrieCleanCacheJournal": 324 return true 325 case "ethconfig.Config.TrieCleanCacheRejournal": 326 return true 327 default: 328 return false 329 } 330 } 331 332 func setAccountManagerBackends(conf *node.Config, am *accounts.Manager, keydir string) error { 333 scryptN := keystore.StandardScryptN 334 scryptP := keystore.StandardScryptP 335 if conf.UseLightweightKDF { 336 scryptN = keystore.LightScryptN 337 scryptP = keystore.LightScryptP 338 } 339 340 // Assemble the supported backends 341 if len(conf.ExternalSigner) > 0 { 342 log.Info("Using external signer", "url", conf.ExternalSigner) 343 if extBackend, err := external.NewExternalBackend(conf.ExternalSigner); err == nil { 344 am.AddBackend(extBackend) 345 return nil 346 } else { 347 return fmt.Errorf("error connecting to external signer: %v", err) 348 } 349 } 350 351 // For now, we're using EITHER external signer OR local signers. 352 // If/when we implement some form of lockfile for USB and keystore wallets, 353 // we can have both, but it's very confusing for the user to see the same 354 // accounts in both externally and locally, plus very racey. 355 am.AddBackend(keystore.NewKeyStore(keydir, scryptN, scryptP)) 356 if conf.USB { 357 // Start a USB hub for Ledger hardware wallets 358 if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil { 359 log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err)) 360 } else { 361 am.AddBackend(ledgerhub) 362 } 363 // Start a USB hub for Trezor hardware wallets (HID version) 364 if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil { 365 log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err)) 366 } else { 367 am.AddBackend(trezorhub) 368 } 369 // Start a USB hub for Trezor hardware wallets (WebUSB version) 370 if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil { 371 log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err)) 372 } else { 373 am.AddBackend(trezorhub) 374 } 375 } 376 if len(conf.SmartCardDaemonPath) > 0 { 377 // Start a smart card hub 378 if schub, err := scwallet.NewHub(conf.SmartCardDaemonPath, scwallet.Scheme, keydir); err != nil { 379 log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err)) 380 } else { 381 am.AddBackend(schub) 382 } 383 } 384 385 return nil 386 }