github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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  	"unicode"
    26  
    27  	cli "gopkg.in/urfave/cli.v1"
    28  
    29  	"github.com/naoina/toml"
    30  	"github.com/zhiqiangxu/go-ethereum/cmd/utils"
    31  	"github.com/zhiqiangxu/go-ethereum/eth"
    32  	"github.com/zhiqiangxu/go-ethereum/node"
    33  	"github.com/zhiqiangxu/go-ethereum/params"
    34  	whisper "github.com/zhiqiangxu/go-ethereum/whisper/whisperv6"
    35  )
    36  
    37  var (
    38  	dumpConfigCommand = cli.Command{
    39  		Action:      utils.MigrateFlags(dumpConfig),
    40  		Name:        "dumpconfig",
    41  		Usage:       "Show configuration values",
    42  		ArgsUsage:   "",
    43  		Flags:       append(append(nodeFlags, rpcFlags...), whisperFlags...),
    44  		Category:    "MISCELLANEOUS COMMANDS",
    45  		Description: `The dumpconfig command shows configuration values.`,
    46  	}
    47  
    48  	configFileFlag = cli.StringFlag{
    49  		Name:  "config",
    50  		Usage: "TOML configuration file",
    51  	}
    52  )
    53  
    54  // These settings ensure that TOML keys use the same names as Go struct fields.
    55  var tomlSettings = toml.Config{
    56  	NormFieldName: func(rt reflect.Type, key string) string {
    57  		return key
    58  	},
    59  	FieldToKey: func(rt reflect.Type, field string) string {
    60  		return field
    61  	},
    62  	MissingField: func(rt reflect.Type, field string) error {
    63  		link := ""
    64  		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
    65  			link = fmt.Sprintf(", see https://godoc.org/%s#%s for available fields", rt.PkgPath(), rt.Name())
    66  		}
    67  		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
    68  	},
    69  }
    70  
    71  type ethstatsConfig struct {
    72  	URL string `toml:",omitempty"`
    73  }
    74  
    75  type gethConfig struct {
    76  	Eth      eth.Config
    77  	Shh      whisper.Config
    78  	Node     node.Config
    79  	Ethstats ethstatsConfig
    80  }
    81  
    82  func loadConfig(file string, cfg *gethConfig) error {
    83  	f, err := os.Open(file)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	defer f.Close()
    88  
    89  	err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
    90  	// Add file name to errors that have a line number.
    91  	if _, ok := err.(*toml.LineError); ok {
    92  		err = errors.New(file + ", " + err.Error())
    93  	}
    94  	return err
    95  }
    96  
    97  func defaultNodeConfig() node.Config {
    98  	cfg := node.DefaultConfig
    99  	cfg.Name = clientIdentifier
   100  	cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
   101  	cfg.HTTPModules = append(cfg.HTTPModules, "eth")
   102  	cfg.WSModules = append(cfg.WSModules, "eth")
   103  	cfg.IPCPath = "geth.ipc"
   104  	return cfg
   105  }
   106  
   107  func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
   108  	// Load defaults.
   109  	cfg := gethConfig{
   110  		Eth:  eth.DefaultConfig,
   111  		Shh:  whisper.DefaultConfig,
   112  		Node: defaultNodeConfig(),
   113  	}
   114  
   115  	// Load config file.
   116  	if file := ctx.GlobalString(configFileFlag.Name); file != "" {
   117  		if err := loadConfig(file, &cfg); err != nil {
   118  			utils.Fatalf("%v", err)
   119  		}
   120  	}
   121  
   122  	// Apply flags.
   123  	utils.SetNodeConfig(ctx, &cfg.Node)
   124  	stack, err := node.New(&cfg.Node)
   125  	if err != nil {
   126  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   127  	}
   128  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   129  	if ctx.GlobalIsSet(utils.EthStatsURLFlag.Name) {
   130  		cfg.Ethstats.URL = ctx.GlobalString(utils.EthStatsURLFlag.Name)
   131  	}
   132  	utils.SetShhConfig(ctx, stack, &cfg.Shh)
   133  
   134  	return stack, cfg
   135  }
   136  
   137  // enableWhisper returns true in case one of the whisper flags is set.
   138  func enableWhisper(ctx *cli.Context) bool {
   139  	for _, flag := range whisperFlags {
   140  		if ctx.GlobalIsSet(flag.GetName()) {
   141  			return true
   142  		}
   143  	}
   144  	return false
   145  }
   146  
   147  func makeFullNode(ctx *cli.Context) *node.Node {
   148  	stack, cfg := makeConfigNode(ctx)
   149  	utils.RegisterEthService(stack, &cfg.Eth)
   150  
   151  	// Whisper must be explicitly enabled by specifying at least 1 whisper flag or in dev mode
   152  	shhEnabled := enableWhisper(ctx)
   153  	shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DeveloperFlag.Name)
   154  	if shhEnabled || shhAutoEnabled {
   155  		if ctx.GlobalIsSet(utils.WhisperMaxMessageSizeFlag.Name) {
   156  			cfg.Shh.MaxMessageSize = uint32(ctx.Int(utils.WhisperMaxMessageSizeFlag.Name))
   157  		}
   158  		if ctx.GlobalIsSet(utils.WhisperMinPOWFlag.Name) {
   159  			cfg.Shh.MinimumAcceptedPOW = ctx.Float64(utils.WhisperMinPOWFlag.Name)
   160  		}
   161  		if ctx.GlobalIsSet(utils.WhisperRestrictConnectionBetweenLightClientsFlag.Name) {
   162  			cfg.Shh.RestrictConnectionBetweenLightClients = true
   163  		}
   164  		utils.RegisterShhService(stack, &cfg.Shh)
   165  	}
   166  	// Configure GraphQL if requested
   167  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   168  		utils.RegisterGraphQLService(stack, cfg.Node.GraphQLEndpoint(), cfg.Node.GraphQLCors, cfg.Node.GraphQLVirtualHosts, cfg.Node.HTTPTimeouts)
   169  	}
   170  	// Add the Ethereum Stats daemon if requested.
   171  	if cfg.Ethstats.URL != "" {
   172  		utils.RegisterEthStatsService(stack, cfg.Ethstats.URL)
   173  	}
   174  	return stack
   175  }
   176  
   177  // dumpConfig is the dumpconfig command.
   178  func dumpConfig(ctx *cli.Context) error {
   179  	_, cfg := makeConfigNode(ctx)
   180  	comment := ""
   181  
   182  	if cfg.Eth.Genesis != nil {
   183  		cfg.Eth.Genesis = nil
   184  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   185  	}
   186  
   187  	out, err := tomlSettings.Marshal(&cfg)
   188  	if err != nil {
   189  		return err
   190  	}
   191  
   192  	dump := os.Stdout
   193  	if ctx.NArg() > 0 {
   194  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   195  		if err != nil {
   196  			return err
   197  		}
   198  		defer dump.Close()
   199  	}
   200  	dump.WriteString(comment)
   201  	dump.Write(out)
   202  
   203  	return nil
   204  }