github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/cmd/sipe/config.go (about)

     1  // Copyright 2017 The go-simplechain Authors
     2  // This file is part of go-simplechain.
     3  //
     4  // go-simplechain 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-simplechain 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-simplechain. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"bufio"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"os"
    25  	"reflect"
    26  	"unicode"
    27  
    28  	"github.com/bigzoro/my_simplechain/cmd/utils"
    29  	"github.com/bigzoro/my_simplechain/consensus/raft"
    30  	raftBackend "github.com/bigzoro/my_simplechain/consensus/raft/backend"
    31  	"github.com/bigzoro/my_simplechain/eth"
    32  	"github.com/bigzoro/my_simplechain/log"
    33  	"github.com/bigzoro/my_simplechain/monitor"
    34  	"github.com/bigzoro/my_simplechain/node"
    35  	"github.com/bigzoro/my_simplechain/p2p/enode"
    36  	"github.com/bigzoro/my_simplechain/params"
    37  	whisper "github.com/bigzoro/my_simplechain/whisper/whisperv6"
    38  
    39  	"github.com/naoina/toml"
    40  	"gopkg.in/urfave/cli.v1"
    41  )
    42  
    43  var (
    44  	dumpConfigCommand = cli.Command{
    45  		Action:      utils.MigrateFlags(dumpConfig),
    46  		Name:        "dumpconfig",
    47  		Usage:       "Show configuration values",
    48  		ArgsUsage:   "",
    49  		Flags:       append(append(nodeFlags, rpcFlags...), whisperFlags...),
    50  		Category:    "MISCELLANEOUS COMMANDS",
    51  		Description: `The dumpconfig command shows configuration values.`,
    52  	}
    53  
    54  	configFileFlag = cli.StringFlag{
    55  		Name:  "config",
    56  		Usage: "TOML configuration file",
    57  	}
    58  )
    59  
    60  // These settings ensure that TOML keys use the same names as Go struct fields.
    61  var tomlSettings = toml.Config{
    62  	NormFieldName: func(rt reflect.Type, key string) string {
    63  		return key
    64  	},
    65  	FieldToKey: func(rt reflect.Type, field string) string {
    66  		return field
    67  	},
    68  	MissingField: func(rt reflect.Type, field string) error {
    69  		link := ""
    70  		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
    71  			link = fmt.Sprintf(", see https://godoc.org/%s#%s for available fields", rt.PkgPath(), rt.Name())
    72  		}
    73  		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
    74  	},
    75  }
    76  
    77  type ethstatsConfig struct {
    78  	URL string `toml:",omitempty"`
    79  }
    80  
    81  type gethConfig struct {
    82  	Eth      eth.Config
    83  	Shh      whisper.Config
    84  	Node     node.Config
    85  	Ethstats ethstatsConfig
    86  }
    87  
    88  func loadConfig(file string, cfg *gethConfig) error {
    89  	f, err := os.Open(file)
    90  	if err != nil {
    91  		return err
    92  	}
    93  	defer f.Close()
    94  
    95  	err = tomlSettings.NewDecoder(bufio.NewReader(f)).Decode(cfg)
    96  	// Add file name to errors that have a line number.
    97  	if _, ok := err.(*toml.LineError); ok {
    98  		err = errors.New(file + ", " + err.Error())
    99  	}
   100  	return err
   101  }
   102  
   103  func defaultNodeConfig() node.Config {
   104  	cfg := node.DefaultConfig
   105  	cfg.Name = clientIdentifier
   106  	cfg.Version = params.VersionWithCommit(gitCommit, gitDate)
   107  	cfg.HTTPModules = append(cfg.HTTPModules, "eth", "shh")
   108  	cfg.WSModules = append(cfg.WSModules, "eth", "shh")
   109  	cfg.IPCPath = "sipe.ipc"
   110  	return cfg
   111  }
   112  
   113  func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
   114  	// Load defaults.
   115  	cfg := gethConfig{
   116  		Eth:  eth.DefaultConfig,
   117  		Shh:  whisper.DefaultConfig,
   118  		Node: defaultNodeConfig(),
   119  	}
   120  
   121  	// Load config file.
   122  	if file := ctx.GlobalString(configFileFlag.Name); file != "" {
   123  		if err := loadConfig(file, &cfg); err != nil {
   124  			utils.Fatalf("%v", err)
   125  		}
   126  	}
   127  
   128  	// Apply flags.
   129  	utils.SetNodeConfig(ctx, &cfg.Node)
   130  	stack, err := node.New(&cfg.Node)
   131  	if err != nil {
   132  		utils.Fatalf("Failed to create the protocol stack: %v", err)
   133  	}
   134  	utils.SetEthConfig(ctx, stack, &cfg.Eth)
   135  	if ctx.GlobalIsSet(utils.EthStatsURLFlag.Name) {
   136  		cfg.Ethstats.URL = ctx.GlobalString(utils.EthStatsURLFlag.Name)
   137  	}
   138  	utils.SetShhConfig(ctx, stack, &cfg.Shh)
   139  	return stack, cfg
   140  }
   141  
   142  // enableWhisper returns true in case one of the whisper flags is set.
   143  func enableWhisper(ctx *cli.Context) bool {
   144  	for _, flag := range whisperFlags {
   145  		if ctx.GlobalIsSet(flag.GetName()) {
   146  			return true
   147  		}
   148  	}
   149  	return false
   150  }
   151  
   152  func makeFullNode(ctx *cli.Context) *node.Node {
   153  	stack, cfg := makeConfigNode(ctx)
   154  	if ctx.GlobalIsSet(utils.OverrideSingularityFlag.Name) {
   155  		cfg.Eth.OverrideSingularity = new(big.Int).SetUint64(ctx.GlobalUint64(utils.OverrideSingularityFlag.Name))
   156  	}
   157  	cfg.Eth.NeedCheckPermission = ctx.GlobalBool(utils.EnableNodePermissionFlag.Name)
   158  	mainCh, raftCh := utils.RegisterEthService(stack, &cfg.Eth)
   159  
   160  	// Whisper must be explicitly enabled by specifying at least 1 whisper flag or in dev mode
   161  	shhEnabled := enableWhisper(ctx)
   162  	shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DeveloperFlag.Name)
   163  	if shhEnabled || shhAutoEnabled {
   164  		if ctx.GlobalIsSet(utils.WhisperMaxMessageSizeFlag.Name) {
   165  			cfg.Shh.MaxMessageSize = uint32(ctx.Int(utils.WhisperMaxMessageSizeFlag.Name))
   166  		}
   167  		if ctx.GlobalIsSet(utils.WhisperMinPOWFlag.Name) {
   168  			cfg.Shh.MinimumAcceptedPOW = ctx.Float64(utils.WhisperMinPOWFlag.Name)
   169  		}
   170  		if ctx.GlobalIsSet(utils.WhisperRestrictConnectionBetweenLightClientsFlag.Name) {
   171  			cfg.Shh.RestrictConnectionBetweenLightClients = true
   172  		}
   173  		utils.RegisterShhService(stack, &cfg.Shh)
   174  	}
   175  	// Configure GraphQL if requested
   176  	if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
   177  		utils.RegisterGraphQLService(stack, cfg.Node.GraphQLEndpoint(), cfg.Node.GraphQLCors, cfg.Node.GraphQLVirtualHosts, cfg.Node.HTTPTimeouts)
   178  	}
   179  	// Add the SimpleService Stats daemon if requested.
   180  	if cfg.Ethstats.URL != "" {
   181  		utils.RegisterEthStatsService(stack, cfg.Ethstats.URL)
   182  	}
   183  	utils.RegisterPermissionService(ctx, stack, mainCh)
   184  	if ctx.GlobalBool(utils.RaftModeFlag.Name) {
   185  		RegisterRaftService(stack, ctx, cfg, raftCh)
   186  	}
   187  
   188  	if ctx.GlobalBool(utils.MonitorModeFlag.Name) {
   189  		RegisterMonitorService(stack, ctx, cfg)
   190  	}
   191  
   192  	// init hotstuff config and register service
   193  	if ctx.GlobalBool(utils.HotstuffModeFlag.Name) && cfg.Eth.Hotstuff.Mine {
   194  		RegisterHotstuffService(stack, ctx, &cfg.Eth)
   195  	}
   196  	return stack
   197  }
   198  
   199  func RegisterHotstuffService(stack *node.Node, ctx *cli.Context, cfg *eth.Config) {
   200  
   201  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   202  		if cfg.Hotstuff.ServiceMaker == nil {
   203  			return nil, errors.New("unknow Hotstuff service register")
   204  		}
   205  		return cfg.Hotstuff.ServiceMaker(cfg.Hotstuff.ChainReader), nil
   206  	}); err != nil {
   207  		utils.Fatalf("Failed to register the Hotstuff service: %v", err)
   208  	}
   209  }
   210  
   211  func RegisterRaftService(stack *node.Node, ctx *cli.Context, cfg gethConfig, eth <-chan *eth.SimpleService) {
   212  	var isFirstRaftNode bool
   213  	if ctx.GlobalIsSet(utils.FirstRaftNodeFlag.Name) {
   214  		isFirstRaftNode = ctx.GlobalBool(utils.FirstRaftNodeFlag.Name)
   215  	}
   216  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   217  		privkey := cfg.Node.NodeKey()
   218  		strId := enode.PubkeyToIDV4(&privkey.PublicKey).String()
   219  		peers := cfg.Node.StaticNodes()
   220  		var myId uint16
   221  		var joinExisting bool
   222  		if !isFirstRaftNode {
   223  			id := enode.PubkeyToIDV4(&privkey.PublicKey)
   224  			raftId, err := raft.ReadGenRaftConfigJson(id[:], stack.InstanceDir())
   225  			if err != nil {
   226  				utils.Fatalf("ReadGenRaftConfigJson failed err:%v", err)
   227  			} else {
   228  				myId = raftId
   229  			}
   230  			if myId == 0 {
   231  				utils.Fatalf("failed to find local enode ID (%v)", strId)
   232  			}
   233  			joinExisting = true
   234  		} else if len(peers) == 0 {
   235  			utils.Fatalf("Raft-based consensus requires either (1) an initial peers list (in static-nodes.json) including this enode hash (%v), or (2) the flag --raftjoinexisting RAFT_ID, where RAFT_ID has been issued by an existing cluster member calling `raft.addPeer(ENODE_ID)` with an enode ID containing this node's enode hash.", strId)
   236  		} else {
   237  			peerIds := make([]string, len(peers))
   238  
   239  			for peerIdx, peer := range peers {
   240  				if !peer.HasRaftPort() {
   241  					utils.Fatalf("raftport querystring parameter not specified in static-node enode ID: %v. please check your static-nodes.json file.", peer.String())
   242  				}
   243  				peerId := peer.ID().String()
   244  				peerIds[peerIdx] = peerId
   245  				if peerId == strId {
   246  					id := peer.ID()
   247  					raftId, err := raft.ReadGenRaftConfigJson(id[:], stack.InstanceDir())
   248  					if err != nil {
   249  						utils.Fatalf("ReadGenRaftConfigJson failed err:%v", err)
   250  					} else {
   251  						myId = raftId
   252  					}
   253  				}
   254  			}
   255  
   256  			if myId == 0 {
   257  				utils.Fatalf("failed to find local enode ID (%v) amongst peer IDs: %v", strId, peerIds)
   258  			}
   259  		}
   260  		log.Info("raft id:", "myId", myId)
   261  		log.Info("is join:", "joinExisting", joinExisting)
   262  		return raftBackend.New(ctx, myId, uint16(cfg.Node.RaftPort), joinExisting, <-eth, peers, cfg.Node.DataDir)
   263  	}); err != nil {
   264  		utils.Fatalf("Failed to register the Raft service: %v", err)
   265  	}
   266  
   267  }
   268  func RegisterMonitorService(stack *node.Node, ctx *cli.Context, cfg gethConfig) {
   269  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   270  		fmt.Println("start monitor service")
   271  		return monitor.New(fmt.Sprintf("%v", cfg.Node.MonitorPort)), nil
   272  	}); err != nil {
   273  		utils.Fatalf("Failed to register the Monitor service: %v", err)
   274  	}
   275  }
   276  
   277  // dumpConfig is the dumpconfig command.
   278  func dumpConfig(ctx *cli.Context) error {
   279  	_, cfg := makeConfigNode(ctx)
   280  	comment := ""
   281  
   282  	if cfg.Eth.Genesis != nil {
   283  		cfg.Eth.Genesis = nil
   284  		comment += "# Note: this config doesn't contain the genesis block.\n\n"
   285  	}
   286  
   287  	out, err := tomlSettings.Marshal(&cfg)
   288  	if err != nil {
   289  		return err
   290  	}
   291  
   292  	dump := os.Stdout
   293  	if ctx.NArg() > 0 {
   294  		dump, err = os.OpenFile(ctx.Args().Get(0), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
   295  		if err != nil {
   296  			return err
   297  		}
   298  		defer dump.Close()
   299  	}
   300  	dump.WriteString(comment)
   301  	dump.Write(out)
   302  
   303  	return nil
   304  }