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