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