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