github.com/codingfuture/orig-energi3@v0.8.4/cmd/swarm/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  	"errors"
    21  	"fmt"
    22  	"io"
    23  	"os"
    24  	"reflect"
    25  	"strconv"
    26  	"strings"
    27  	"time"
    28  	"unicode"
    29  
    30  	cli "gopkg.in/urfave/cli.v1"
    31  
    32  	"github.com/ethereum/go-ethereum/cmd/utils"
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/node"
    36  	"github.com/naoina/toml"
    37  
    38  	bzzapi "github.com/ethereum/go-ethereum/swarm/api"
    39  )
    40  
    41  var (
    42  	//flag definition for the dumpconfig command
    43  	DumpConfigCommand = cli.Command{
    44  		Action:      utils.MigrateFlags(dumpConfig),
    45  		Name:        "dumpconfig",
    46  		Usage:       "Show configuration values",
    47  		ArgsUsage:   "",
    48  		Flags:       app.Flags,
    49  		Category:    "MISCELLANEOUS COMMANDS",
    50  		Description: `The dumpconfig command shows configuration values.`,
    51  	}
    52  
    53  	//flag definition for the config file command
    54  	SwarmTomlConfigPathFlag = cli.StringFlag{
    55  		Name:  "config",
    56  		Usage: "TOML configuration file",
    57  	}
    58  )
    59  
    60  //constants for environment variables
    61  const (
    62  	SWARM_ENV_CHEQUEBOOK_ADDR         = "SWARM_CHEQUEBOOK_ADDR"
    63  	SWARM_ENV_ACCOUNT                 = "SWARM_ACCOUNT"
    64  	SWARM_ENV_LISTEN_ADDR             = "SWARM_LISTEN_ADDR"
    65  	SWARM_ENV_PORT                    = "SWARM_PORT"
    66  	SWARM_ENV_NETWORK_ID              = "SWARM_NETWORK_ID"
    67  	SWARM_ENV_SWAP_ENABLE             = "SWARM_SWAP_ENABLE"
    68  	SWARM_ENV_SWAP_API                = "SWARM_SWAP_API"
    69  	SWARM_ENV_SYNC_DISABLE            = "SWARM_SYNC_DISABLE"
    70  	SWARM_ENV_SYNC_UPDATE_DELAY       = "SWARM_ENV_SYNC_UPDATE_DELAY"
    71  	SWARM_ENV_MAX_STREAM_PEER_SERVERS = "SWARM_ENV_MAX_STREAM_PEER_SERVERS"
    72  	SWARM_ENV_LIGHT_NODE_ENABLE       = "SWARM_LIGHT_NODE_ENABLE"
    73  	SWARM_ENV_DELIVERY_SKIP_CHECK     = "SWARM_DELIVERY_SKIP_CHECK"
    74  	SWARM_ENV_ENS_API                 = "SWARM_ENS_API"
    75  	SWARM_ENV_ENS_ADDR                = "SWARM_ENS_ADDR"
    76  	SWARM_ENV_CORS                    = "SWARM_CORS"
    77  	SWARM_ENV_BOOTNODES               = "SWARM_BOOTNODES"
    78  	SWARM_ENV_PSS_ENABLE              = "SWARM_PSS_ENABLE"
    79  	SWARM_ENV_STORE_PATH              = "SWARM_STORE_PATH"
    80  	SWARM_ENV_STORE_CAPACITY          = "SWARM_STORE_CAPACITY"
    81  	SWARM_ENV_STORE_CACHE_CAPACITY    = "SWARM_STORE_CACHE_CAPACITY"
    82  	SWARM_ENV_BOOTNODE_MODE           = "SWARM_BOOTNODE_MODE"
    83  	SWARM_ACCESS_PASSWORD             = "SWARM_ACCESS_PASSWORD"
    84  	SWARM_AUTO_DEFAULTPATH            = "SWARM_AUTO_DEFAULTPATH"
    85  	SWARM_GLOBALSTORE_API             = "SWARM_GLOBALSTORE_API"
    86  	GETH_ENV_DATADIR                  = "GETH_DATADIR"
    87  )
    88  
    89  // These settings ensure that TOML keys use the same names as Go struct fields.
    90  var tomlSettings = toml.Config{
    91  	NormFieldName: func(rt reflect.Type, key string) string {
    92  		return key
    93  	},
    94  	FieldToKey: func(rt reflect.Type, field string) string {
    95  		return field
    96  	},
    97  	MissingField: func(rt reflect.Type, field string) error {
    98  		link := ""
    99  		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
   100  			link = fmt.Sprintf(", check github.com/ethereum/go-ethereum/swarm/api/config.go for available fields")
   101  		}
   102  		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
   103  	},
   104  }
   105  
   106  //before booting the swarm node, build the configuration
   107  func buildConfig(ctx *cli.Context) (config *bzzapi.Config, err error) {
   108  	//start by creating a default config
   109  	config = bzzapi.NewConfig()
   110  	//first load settings from config file (if provided)
   111  	config, err = configFileOverride(config, ctx)
   112  	if err != nil {
   113  		return nil, err
   114  	}
   115  	//override settings provided by environment variables
   116  	config = envVarsOverride(config)
   117  	//override settings provided by command line
   118  	config = cmdLineOverride(config, ctx)
   119  	//validate configuration parameters
   120  	err = validateConfig(config)
   121  
   122  	return
   123  }
   124  
   125  //finally, after the configuration build phase is finished, initialize
   126  func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context) {
   127  	//at this point, all vars should be set in the Config
   128  	//get the account for the provided swarm account
   129  	prvkey := getAccount(config.BzzAccount, ctx, stack)
   130  	//set the resolved config path (geth --datadir)
   131  	config.Path = expandPath(stack.InstanceDir())
   132  	//finally, initialize the configuration
   133  	config.Init(prvkey)
   134  	//configuration phase completed here
   135  	log.Debug("Starting Swarm with the following parameters:")
   136  	//after having created the config, print it to screen
   137  	log.Debug(printConfig(config))
   138  }
   139  
   140  //configFileOverride overrides the current config with the config file, if a config file has been provided
   141  func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) {
   142  	var err error
   143  
   144  	//only do something if the -config flag has been set
   145  	if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) {
   146  		var filepath string
   147  		if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" {
   148  			utils.Fatalf("Config file flag provided with invalid file path")
   149  		}
   150  		var f *os.File
   151  		f, err = os.Open(filepath)
   152  		if err != nil {
   153  			return nil, err
   154  		}
   155  		defer f.Close()
   156  
   157  		//decode the TOML file into a Config struct
   158  		//note that we are decoding into the existing defaultConfig;
   159  		//if an entry is not present in the file, the default entry is kept
   160  		err = tomlSettings.NewDecoder(f).Decode(&config)
   161  		// Add file name to errors that have a line number.
   162  		if _, ok := err.(*toml.LineError); ok {
   163  			err = errors.New(filepath + ", " + err.Error())
   164  		}
   165  	}
   166  	return config, err
   167  }
   168  
   169  // cmdLineOverride overrides the current config with whatever is provided through the command line
   170  // most values are not allowed a zero value (empty string), if not otherwise noted
   171  func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Config {
   172  	if keyid := ctx.GlobalString(SwarmAccountFlag.Name); keyid != "" {
   173  		currentConfig.BzzAccount = keyid
   174  	}
   175  
   176  	if chbookaddr := ctx.GlobalString(ChequebookAddrFlag.Name); chbookaddr != "" {
   177  		currentConfig.Contract = common.HexToAddress(chbookaddr)
   178  	}
   179  
   180  	if networkid := ctx.GlobalString(SwarmNetworkIdFlag.Name); networkid != "" {
   181  		id, err := strconv.ParseUint(networkid, 10, 64)
   182  		if err != nil {
   183  			utils.Fatalf("invalid cli flag %s: %v", SwarmNetworkIdFlag.Name, err)
   184  		}
   185  		if id != 0 {
   186  			currentConfig.NetworkID = id
   187  		}
   188  	}
   189  
   190  	if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
   191  		if datadir := ctx.GlobalString(utils.DataDirFlag.Name); datadir != "" {
   192  			currentConfig.Path = expandPath(datadir)
   193  		}
   194  	}
   195  
   196  	bzzport := ctx.GlobalString(SwarmPortFlag.Name)
   197  	if len(bzzport) > 0 {
   198  		currentConfig.Port = bzzport
   199  	}
   200  
   201  	if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
   202  		currentConfig.ListenAddr = bzzaddr
   203  	}
   204  
   205  	if ctx.GlobalIsSet(SwarmSwapEnabledFlag.Name) {
   206  		currentConfig.SwapEnabled = true
   207  	}
   208  
   209  	if ctx.GlobalIsSet(SwarmSyncDisabledFlag.Name) {
   210  		currentConfig.SyncEnabled = false
   211  	}
   212  
   213  	if d := ctx.GlobalDuration(SwarmSyncUpdateDelay.Name); d > 0 {
   214  		currentConfig.SyncUpdateDelay = d
   215  	}
   216  
   217  	// any value including 0 is acceptable
   218  	currentConfig.MaxStreamPeerServers = ctx.GlobalInt(SwarmMaxStreamPeerServersFlag.Name)
   219  
   220  	if ctx.GlobalIsSet(SwarmLightNodeEnabled.Name) {
   221  		currentConfig.LightNodeEnabled = true
   222  	}
   223  
   224  	if ctx.GlobalIsSet(SwarmDeliverySkipCheckFlag.Name) {
   225  		currentConfig.DeliverySkipCheck = true
   226  	}
   227  
   228  	currentConfig.SwapAPI = ctx.GlobalString(SwarmSwapAPIFlag.Name)
   229  	if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
   230  		utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
   231  	}
   232  
   233  	if ctx.GlobalIsSet(EnsAPIFlag.Name) {
   234  		ensAPIs := ctx.GlobalStringSlice(EnsAPIFlag.Name)
   235  		// preserve backward compatibility to disable ENS with --ens-api=""
   236  		if len(ensAPIs) == 1 && ensAPIs[0] == "" {
   237  			ensAPIs = nil
   238  		}
   239  		for i := range ensAPIs {
   240  			ensAPIs[i] = expandPath(ensAPIs[i])
   241  		}
   242  
   243  		currentConfig.EnsAPIs = ensAPIs
   244  	}
   245  
   246  	if cors := ctx.GlobalString(CorsStringFlag.Name); cors != "" {
   247  		currentConfig.Cors = cors
   248  	}
   249  
   250  	if storePath := ctx.GlobalString(SwarmStorePath.Name); storePath != "" {
   251  		currentConfig.LocalStoreParams.ChunkDbPath = storePath
   252  	}
   253  
   254  	if storeCapacity := ctx.GlobalUint64(SwarmStoreCapacity.Name); storeCapacity != 0 {
   255  		currentConfig.LocalStoreParams.DbCapacity = storeCapacity
   256  	}
   257  
   258  	if storeCacheCapacity := ctx.GlobalUint(SwarmStoreCacheCapacity.Name); storeCacheCapacity != 0 {
   259  		currentConfig.LocalStoreParams.CacheCapacity = storeCacheCapacity
   260  	}
   261  
   262  	if ctx.GlobalIsSet(SwarmBootnodeModeFlag.Name) {
   263  		currentConfig.BootnodeMode = ctx.GlobalBool(SwarmBootnodeModeFlag.Name)
   264  	}
   265  
   266  	if ctx.GlobalIsSet(SwarmGlobalStoreAPIFlag.Name) {
   267  		currentConfig.GlobalStoreAPI = ctx.GlobalString(SwarmGlobalStoreAPIFlag.Name)
   268  	}
   269  
   270  	return currentConfig
   271  
   272  }
   273  
   274  // envVarsOverride overrides the current config with whatver is provided in environment variables
   275  // most values are not allowed a zero value (empty string), if not otherwise noted
   276  func envVarsOverride(currentConfig *bzzapi.Config) (config *bzzapi.Config) {
   277  	if keyid := os.Getenv(SWARM_ENV_ACCOUNT); keyid != "" {
   278  		currentConfig.BzzAccount = keyid
   279  	}
   280  
   281  	if chbookaddr := os.Getenv(SWARM_ENV_CHEQUEBOOK_ADDR); chbookaddr != "" {
   282  		currentConfig.Contract = common.HexToAddress(chbookaddr)
   283  	}
   284  
   285  	if networkid := os.Getenv(SWARM_ENV_NETWORK_ID); networkid != "" {
   286  		id, err := strconv.ParseUint(networkid, 10, 64)
   287  		if err != nil {
   288  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_NETWORK_ID, err)
   289  		}
   290  		if id != 0 {
   291  			currentConfig.NetworkID = id
   292  		}
   293  	}
   294  
   295  	if datadir := os.Getenv(GETH_ENV_DATADIR); datadir != "" {
   296  		currentConfig.Path = expandPath(datadir)
   297  	}
   298  
   299  	bzzport := os.Getenv(SWARM_ENV_PORT)
   300  	if len(bzzport) > 0 {
   301  		currentConfig.Port = bzzport
   302  	}
   303  
   304  	if bzzaddr := os.Getenv(SWARM_ENV_LISTEN_ADDR); bzzaddr != "" {
   305  		currentConfig.ListenAddr = bzzaddr
   306  	}
   307  
   308  	if swapenable := os.Getenv(SWARM_ENV_SWAP_ENABLE); swapenable != "" {
   309  		swap, err := strconv.ParseBool(swapenable)
   310  		if err != nil {
   311  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_SWAP_ENABLE, err)
   312  		}
   313  		currentConfig.SwapEnabled = swap
   314  	}
   315  
   316  	if syncdisable := os.Getenv(SWARM_ENV_SYNC_DISABLE); syncdisable != "" {
   317  		sync, err := strconv.ParseBool(syncdisable)
   318  		if err != nil {
   319  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_SYNC_DISABLE, err)
   320  		}
   321  		currentConfig.SyncEnabled = !sync
   322  	}
   323  
   324  	if v := os.Getenv(SWARM_ENV_DELIVERY_SKIP_CHECK); v != "" {
   325  		skipCheck, err := strconv.ParseBool(v)
   326  		if err != nil {
   327  			currentConfig.DeliverySkipCheck = skipCheck
   328  		}
   329  	}
   330  
   331  	if v := os.Getenv(SWARM_ENV_SYNC_UPDATE_DELAY); v != "" {
   332  		d, err := time.ParseDuration(v)
   333  		if err != nil {
   334  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_SYNC_UPDATE_DELAY, err)
   335  		}
   336  		currentConfig.SyncUpdateDelay = d
   337  	}
   338  
   339  	if max := os.Getenv(SWARM_ENV_MAX_STREAM_PEER_SERVERS); max != "" {
   340  		m, err := strconv.Atoi(max)
   341  		if err != nil {
   342  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_MAX_STREAM_PEER_SERVERS, err)
   343  		}
   344  		currentConfig.MaxStreamPeerServers = m
   345  	}
   346  
   347  	if lne := os.Getenv(SWARM_ENV_LIGHT_NODE_ENABLE); lne != "" {
   348  		lightnode, err := strconv.ParseBool(lne)
   349  		if err != nil {
   350  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_LIGHT_NODE_ENABLE, err)
   351  		}
   352  		currentConfig.LightNodeEnabled = lightnode
   353  	}
   354  
   355  	if swapapi := os.Getenv(SWARM_ENV_SWAP_API); swapapi != "" {
   356  		currentConfig.SwapAPI = swapapi
   357  	}
   358  
   359  	if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
   360  		utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
   361  	}
   362  
   363  	if ensapi := os.Getenv(SWARM_ENV_ENS_API); ensapi != "" {
   364  		currentConfig.EnsAPIs = strings.Split(ensapi, ",")
   365  	}
   366  
   367  	if ensaddr := os.Getenv(SWARM_ENV_ENS_ADDR); ensaddr != "" {
   368  		currentConfig.EnsRoot = common.HexToAddress(ensaddr)
   369  	}
   370  
   371  	if cors := os.Getenv(SWARM_ENV_CORS); cors != "" {
   372  		currentConfig.Cors = cors
   373  	}
   374  
   375  	if bm := os.Getenv(SWARM_ENV_BOOTNODE_MODE); bm != "" {
   376  		bootnodeMode, err := strconv.ParseBool(bm)
   377  		if err != nil {
   378  			utils.Fatalf("invalid environment variable %s: %v", SWARM_ENV_BOOTNODE_MODE, err)
   379  		}
   380  		currentConfig.BootnodeMode = bootnodeMode
   381  	}
   382  
   383  	if api := os.Getenv(SWARM_GLOBALSTORE_API); api != "" {
   384  		currentConfig.GlobalStoreAPI = api
   385  	}
   386  
   387  	return currentConfig
   388  }
   389  
   390  // dumpConfig is the dumpconfig command.
   391  // writes a default config to STDOUT
   392  func dumpConfig(ctx *cli.Context) error {
   393  	cfg, err := buildConfig(ctx)
   394  	if err != nil {
   395  		utils.Fatalf(fmt.Sprintf("Uh oh - dumpconfig triggered an error %v", err))
   396  	}
   397  	comment := ""
   398  	out, err := tomlSettings.Marshal(&cfg)
   399  	if err != nil {
   400  		return err
   401  	}
   402  	io.WriteString(os.Stdout, comment)
   403  	os.Stdout.Write(out)
   404  	return nil
   405  }
   406  
   407  //validate configuration parameters
   408  func validateConfig(cfg *bzzapi.Config) (err error) {
   409  	for _, ensAPI := range cfg.EnsAPIs {
   410  		if ensAPI != "" {
   411  			if err := validateEnsAPIs(ensAPI); err != nil {
   412  				return fmt.Errorf("invalid format [tld:][contract-addr@]url for ENS API endpoint configuration %q: %v", ensAPI, err)
   413  			}
   414  		}
   415  	}
   416  	return nil
   417  }
   418  
   419  //validate EnsAPIs configuration parameter
   420  func validateEnsAPIs(s string) (err error) {
   421  	// missing contract address
   422  	if strings.HasPrefix(s, "@") {
   423  		return errors.New("missing contract address")
   424  	}
   425  	// missing url
   426  	if strings.HasSuffix(s, "@") {
   427  		return errors.New("missing url")
   428  	}
   429  	// missing tld
   430  	if strings.HasPrefix(s, ":") {
   431  		return errors.New("missing tld")
   432  	}
   433  	// missing url
   434  	if strings.HasSuffix(s, ":") {
   435  		return errors.New("missing url")
   436  	}
   437  	return nil
   438  }
   439  
   440  //print a Config as string
   441  func printConfig(config *bzzapi.Config) string {
   442  	out, err := tomlSettings.Marshal(&config)
   443  	if err != nil {
   444  		return fmt.Sprintf("Something is not right with the configuration: %v", err)
   445  	}
   446  	return string(out)
   447  }