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