config.go 11.9 KB
Newer Older
H
holisticode 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Copyright 2017 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"reflect"
	"strconv"
26
	"strings"
E
ethersphere 已提交
27
	"time"
H
holisticode 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	"unicode"

	cli "gopkg.in/urfave/cli.v1"

	"github.com/ethereum/go-ethereum/cmd/utils"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/node"
	"github.com/naoina/toml"

	bzzapi "github.com/ethereum/go-ethereum/swarm/api"
)

var (
	//flag definition for the dumpconfig command
	DumpConfigCommand = cli.Command{
		Action:      utils.MigrateFlags(dumpConfig),
		Name:        "dumpconfig",
		Usage:       "Show configuration values",
		ArgsUsage:   "",
		Flags:       app.Flags,
		Category:    "MISCELLANEOUS COMMANDS",
		Description: `The dumpconfig command shows configuration values.`,
	}

	//flag definition for the config file command
	SwarmTomlConfigPathFlag = cli.StringFlag{
		Name:  "config",
		Usage: "TOML configuration file",
	}
)

//constants for environment variables
const (
E
ethersphere 已提交
62 63 64 65 66 67 68 69 70
	SWARM_ENV_CHEQUEBOOK_ADDR      = "SWARM_CHEQUEBOOK_ADDR"
	SWARM_ENV_ACCOUNT              = "SWARM_ACCOUNT"
	SWARM_ENV_LISTEN_ADDR          = "SWARM_LISTEN_ADDR"
	SWARM_ENV_PORT                 = "SWARM_PORT"
	SWARM_ENV_NETWORK_ID           = "SWARM_NETWORK_ID"
	SWARM_ENV_SWAP_ENABLE          = "SWARM_SWAP_ENABLE"
	SWARM_ENV_SWAP_API             = "SWARM_SWAP_API"
	SWARM_ENV_SYNC_DISABLE         = "SWARM_SYNC_DISABLE"
	SWARM_ENV_SYNC_UPDATE_DELAY    = "SWARM_ENV_SYNC_UPDATE_DELAY"
71
	SWARM_ENV_LIGHT_NODE_ENABLE    = "SWARM_LIGHT_NODE_ENABLE"
E
ethersphere 已提交
72 73 74 75 76 77 78 79 80
	SWARM_ENV_DELIVERY_SKIP_CHECK  = "SWARM_DELIVERY_SKIP_CHECK"
	SWARM_ENV_ENS_API              = "SWARM_ENS_API"
	SWARM_ENV_ENS_ADDR             = "SWARM_ENS_ADDR"
	SWARM_ENV_CORS                 = "SWARM_CORS"
	SWARM_ENV_BOOTNODES            = "SWARM_BOOTNODES"
	SWARM_ENV_PSS_ENABLE           = "SWARM_PSS_ENABLE"
	SWARM_ENV_STORE_PATH           = "SWARM_STORE_PATH"
	SWARM_ENV_STORE_CAPACITY       = "SWARM_STORE_CAPACITY"
	SWARM_ENV_STORE_CACHE_CAPACITY = "SWARM_STORE_CACHE_CAPACITY"
81
	SWARM_ACCESS_PASSWORD          = "SWARM_ACCESS_PASSWORD"
E
ethersphere 已提交
82
	GETH_ENV_DATADIR               = "GETH_DATADIR"
H
holisticode 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
)

// These settings ensure that TOML keys use the same names as Go struct fields.
var tomlSettings = toml.Config{
	NormFieldName: func(rt reflect.Type, key string) string {
		return key
	},
	FieldToKey: func(rt reflect.Type, field string) string {
		return field
	},
	MissingField: func(rt reflect.Type, field string) error {
		link := ""
		if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
			link = fmt.Sprintf(", check github.com/ethereum/go-ethereum/swarm/api/config.go for available fields")
		}
		return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
	},
}

//before booting the swarm node, build the configuration
func buildConfig(ctx *cli.Context) (config *bzzapi.Config, err error) {
	//start by creating a default config
E
ethersphere 已提交
105
	config = bzzapi.NewConfig()
H
holisticode 已提交
106 107
	//first load settings from config file (if provided)
	config, err = configFileOverride(config, ctx)
108 109 110
	if err != nil {
		return nil, err
	}
H
holisticode 已提交
111 112 113 114
	//override settings provided by environment variables
	config = envVarsOverride(config)
	//override settings provided by command line
	config = cmdLineOverride(config, ctx)
115 116
	//validate configuration parameters
	err = validateConfig(config)
H
holisticode 已提交
117 118 119 120 121 122 123 124 125 126

	return
}

//finally, after the configuration build phase is finished, initialize
func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context) {
	//at this point, all vars should be set in the Config
	//get the account for the provided swarm account
	prvkey := getAccount(config.BzzAccount, ctx, stack)
	//set the resolved config path (geth --datadir)
127
	config.Path = expandPath(stack.InstanceDir())
H
holisticode 已提交
128 129 130 131 132 133 134 135
	//finally, initialize the configuration
	config.Init(prvkey)
	//configuration phase completed here
	log.Debug("Starting Swarm with the following parameters:")
	//after having created the config, print it to screen
	log.Debug(printConfig(config))
}

136
//configFileOverride overrides the current config with the config file, if a config file has been provided
H
holisticode 已提交
137 138 139 140 141 142 143 144 145
func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) {
	var err error

	//only do something if the -config flag has been set
	if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) {
		var filepath string
		if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" {
			utils.Fatalf("Config file flag provided with invalid file path")
		}
146 147
		var f *os.File
		f, err = os.Open(filepath)
H
holisticode 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
		if err != nil {
			return nil, err
		}
		defer f.Close()

		//decode the TOML file into a Config struct
		//note that we are decoding into the existing defaultConfig;
		//if an entry is not present in the file, the default entry is kept
		err = tomlSettings.NewDecoder(f).Decode(&config)
		// Add file name to errors that have a line number.
		if _, ok := err.(*toml.LineError); ok {
			err = errors.New(filepath + ", " + err.Error())
		}
	}
	return config, err
}

//override the current config with whatever is provided through the command line
//most values are not allowed a zero value (empty string), if not otherwise noted
func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Config {

	if keyid := ctx.GlobalString(SwarmAccountFlag.Name); keyid != "" {
		currentConfig.BzzAccount = keyid
	}

	if chbookaddr := ctx.GlobalString(ChequebookAddrFlag.Name); chbookaddr != "" {
		currentConfig.Contract = common.HexToAddress(chbookaddr)
	}

	if networkid := ctx.GlobalString(SwarmNetworkIdFlag.Name); networkid != "" {
		if id, _ := strconv.Atoi(networkid); id != 0 {
E
ethersphere 已提交
179
			currentConfig.NetworkID = uint64(id)
H
holisticode 已提交
180 181 182 183 184
		}
	}

	if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
		if datadir := ctx.GlobalString(utils.DataDirFlag.Name); datadir != "" {
185
			currentConfig.Path = expandPath(datadir)
H
holisticode 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		}
	}

	bzzport := ctx.GlobalString(SwarmPortFlag.Name)
	if len(bzzport) > 0 {
		currentConfig.Port = bzzport
	}

	if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
		currentConfig.ListenAddr = bzzaddr
	}

	if ctx.GlobalIsSet(SwarmSwapEnabledFlag.Name) {
		currentConfig.SwapEnabled = true
	}

E
ethersphere 已提交
202 203 204 205 206 207
	if ctx.GlobalIsSet(SwarmSyncDisabledFlag.Name) {
		currentConfig.SyncEnabled = false
	}

	if d := ctx.GlobalDuration(SwarmSyncUpdateDelay.Name); d > 0 {
		currentConfig.SyncUpdateDelay = d
H
holisticode 已提交
208 209
	}

210 211 212 213
	if ctx.GlobalIsSet(SwarmLightNodeEnabled.Name) {
		currentConfig.LightNodeEnabled = true
	}

E
ethersphere 已提交
214 215 216 217 218 219
	if ctx.GlobalIsSet(SwarmDeliverySkipCheckFlag.Name) {
		currentConfig.DeliverySkipCheck = true
	}

	currentConfig.SwapAPI = ctx.GlobalString(SwarmSwapAPIFlag.Name)
	if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
H
holisticode 已提交
220 221 222 223
		utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
	}

	if ctx.GlobalIsSet(EnsAPIFlag.Name) {
224
		ensAPIs := ctx.GlobalStringSlice(EnsAPIFlag.Name)
225
		// preserve backward compatibility to disable ENS with --ens-api=""
226
		if len(ensAPIs) == 1 && ensAPIs[0] == "" {
227
			ensAPIs = nil
228
		}
229 230 231 232
		for i := range ensAPIs {
			ensAPIs[i] = expandPath(ensAPIs[i])
		}

233
		currentConfig.EnsAPIs = ensAPIs
H
holisticode 已提交
234 235 236 237 238 239
	}

	if cors := ctx.GlobalString(CorsStringFlag.Name); cors != "" {
		currentConfig.Cors = cors
	}

E
ethersphere 已提交
240 241 242 243 244 245 246 247 248 249 250 251
	if storePath := ctx.GlobalString(SwarmStorePath.Name); storePath != "" {
		currentConfig.LocalStoreParams.ChunkDbPath = storePath
	}

	if storeCapacity := ctx.GlobalUint64(SwarmStoreCapacity.Name); storeCapacity != 0 {
		currentConfig.LocalStoreParams.DbCapacity = storeCapacity
	}

	if storeCacheCapacity := ctx.GlobalUint(SwarmStoreCacheCapacity.Name); storeCacheCapacity != 0 {
		currentConfig.LocalStoreParams.CacheCapacity = storeCacheCapacity
	}

H
holisticode 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
	return currentConfig

}

//override the current config with whatver is provided in environment variables
//most values are not allowed a zero value (empty string), if not otherwise noted
func envVarsOverride(currentConfig *bzzapi.Config) (config *bzzapi.Config) {

	if keyid := os.Getenv(SWARM_ENV_ACCOUNT); keyid != "" {
		currentConfig.BzzAccount = keyid
	}

	if chbookaddr := os.Getenv(SWARM_ENV_CHEQUEBOOK_ADDR); chbookaddr != "" {
		currentConfig.Contract = common.HexToAddress(chbookaddr)
	}

	if networkid := os.Getenv(SWARM_ENV_NETWORK_ID); networkid != "" {
		if id, _ := strconv.Atoi(networkid); id != 0 {
E
ethersphere 已提交
270
			currentConfig.NetworkID = uint64(id)
H
holisticode 已提交
271 272 273 274
		}
	}

	if datadir := os.Getenv(GETH_ENV_DATADIR); datadir != "" {
275
		currentConfig.Path = expandPath(datadir)
H
holisticode 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	}

	bzzport := os.Getenv(SWARM_ENV_PORT)
	if len(bzzport) > 0 {
		currentConfig.Port = bzzport
	}

	if bzzaddr := os.Getenv(SWARM_ENV_LISTEN_ADDR); bzzaddr != "" {
		currentConfig.ListenAddr = bzzaddr
	}

	if swapenable := os.Getenv(SWARM_ENV_SWAP_ENABLE); swapenable != "" {
		if swap, err := strconv.ParseBool(swapenable); err != nil {
			currentConfig.SwapEnabled = swap
		}
	}

E
ethersphere 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
	if syncdisable := os.Getenv(SWARM_ENV_SYNC_DISABLE); syncdisable != "" {
		if sync, err := strconv.ParseBool(syncdisable); err != nil {
			currentConfig.SyncEnabled = !sync
		}
	}

	if v := os.Getenv(SWARM_ENV_DELIVERY_SKIP_CHECK); v != "" {
		if skipCheck, err := strconv.ParseBool(v); err != nil {
			currentConfig.DeliverySkipCheck = skipCheck
		}
	}

	if v := os.Getenv(SWARM_ENV_SYNC_UPDATE_DELAY); v != "" {
		if d, err := time.ParseDuration(v); err != nil {
			currentConfig.SyncUpdateDelay = d
H
holisticode 已提交
308 309 310
		}
	}

311 312 313 314 315 316
	if lne := os.Getenv(SWARM_ENV_LIGHT_NODE_ENABLE); lne != "" {
		if lightnode, err := strconv.ParseBool(lne); err != nil {
			currentConfig.LightNodeEnabled = lightnode
		}
	}

H
holisticode 已提交
317
	if swapapi := os.Getenv(SWARM_ENV_SWAP_API); swapapi != "" {
E
ethersphere 已提交
318
		currentConfig.SwapAPI = swapapi
H
holisticode 已提交
319 320
	}

E
ethersphere 已提交
321
	if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
H
holisticode 已提交
322 323 324
		utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
	}

325 326
	if ensapi := os.Getenv(SWARM_ENV_ENS_API); ensapi != "" {
		currentConfig.EnsAPIs = strings.Split(ensapi, ",")
H
holisticode 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	}

	if ensaddr := os.Getenv(SWARM_ENV_ENS_ADDR); ensaddr != "" {
		currentConfig.EnsRoot = common.HexToAddress(ensaddr)
	}

	if cors := os.Getenv(SWARM_ENV_CORS); cors != "" {
		currentConfig.Cors = cors
	}

	return currentConfig
}

// dumpConfig is the dumpconfig command.
// writes a default config to STDOUT
func dumpConfig(ctx *cli.Context) error {
	cfg, err := buildConfig(ctx)
	if err != nil {
		utils.Fatalf(fmt.Sprintf("Uh oh - dumpconfig triggered an error %v", err))
	}
	comment := ""
	out, err := tomlSettings.Marshal(&cfg)
	if err != nil {
		return err
	}
	io.WriteString(os.Stdout, comment)
	os.Stdout.Write(out)
	return nil
}

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
//validate configuration parameters
func validateConfig(cfg *bzzapi.Config) (err error) {
	for _, ensAPI := range cfg.EnsAPIs {
		if ensAPI != "" {
			if err := validateEnsAPIs(ensAPI); err != nil {
				return fmt.Errorf("invalid format [tld:][contract-addr@]url for ENS API endpoint configuration %q: %v", ensAPI, err)
			}
		}
	}
	return nil
}

//validate EnsAPIs configuration parameter
func validateEnsAPIs(s string) (err error) {
	// missing contract address
	if strings.HasPrefix(s, "@") {
		return errors.New("missing contract address")
	}
	// missing url
	if strings.HasSuffix(s, "@") {
		return errors.New("missing url")
	}
	// missing tld
	if strings.HasPrefix(s, ":") {
		return errors.New("missing tld")
	}
	// missing url
	if strings.HasSuffix(s, ":") {
		return errors.New("missing url")
	}
	return nil
}

H
holisticode 已提交
390 391 392 393
//print a Config as string
func printConfig(config *bzzapi.Config) string {
	out, err := tomlSettings.Marshal(&config)
	if err != nil {
394
		return fmt.Sprintf("Something is not right with the configuration: %v", err)
H
holisticode 已提交
395 396 397
	}
	return string(out)
}