config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. package main
  17. import (
  18. "errors"
  19. "fmt"
  20. "io"
  21. "os"
  22. "reflect"
  23. "strconv"
  24. "strings"
  25. "unicode"
  26. cli "gopkg.in/urfave/cli.v1"
  27. "github.com/ethereum/go-ethereum/cmd/utils"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/node"
  31. "github.com/naoina/toml"
  32. bzzapi "github.com/ethereum/go-ethereum/swarm/api"
  33. )
  34. var (
  35. //flag definition for the dumpconfig command
  36. DumpConfigCommand = cli.Command{
  37. Action: utils.MigrateFlags(dumpConfig),
  38. Name: "dumpconfig",
  39. Usage: "Show configuration values",
  40. ArgsUsage: "",
  41. Flags: app.Flags,
  42. Category: "MISCELLANEOUS COMMANDS",
  43. Description: `The dumpconfig command shows configuration values.`,
  44. }
  45. //flag definition for the config file command
  46. SwarmTomlConfigPathFlag = cli.StringFlag{
  47. Name: "config",
  48. Usage: "TOML configuration file",
  49. }
  50. )
  51. //constants for environment variables
  52. const (
  53. SWARM_ENV_CHEQUEBOOK_ADDR = "SWARM_CHEQUEBOOK_ADDR"
  54. SWARM_ENV_ACCOUNT = "SWARM_ACCOUNT"
  55. SWARM_ENV_LISTEN_ADDR = "SWARM_LISTEN_ADDR"
  56. SWARM_ENV_PORT = "SWARM_PORT"
  57. SWARM_ENV_NETWORK_ID = "SWARM_NETWORK_ID"
  58. SWARM_ENV_SWAP_ENABLE = "SWARM_SWAP_ENABLE"
  59. SWARM_ENV_SWAP_API = "SWARM_SWAP_API"
  60. SWARM_ENV_SYNC_ENABLE = "SWARM_SYNC_ENABLE"
  61. SWARM_ENV_ENS_API = "SWARM_ENS_API"
  62. SWARM_ENV_ENS_ADDR = "SWARM_ENS_ADDR"
  63. SWARM_ENV_CORS = "SWARM_CORS"
  64. SWARM_ENV_BOOTNODES = "SWARM_BOOTNODES"
  65. GETH_ENV_DATADIR = "GETH_DATADIR"
  66. )
  67. // These settings ensure that TOML keys use the same names as Go struct fields.
  68. var tomlSettings = toml.Config{
  69. NormFieldName: func(rt reflect.Type, key string) string {
  70. return key
  71. },
  72. FieldToKey: func(rt reflect.Type, field string) string {
  73. return field
  74. },
  75. MissingField: func(rt reflect.Type, field string) error {
  76. link := ""
  77. if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
  78. link = fmt.Sprintf(", check github.com/ethereum/go-ethereum/swarm/api/config.go for available fields")
  79. }
  80. return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
  81. },
  82. }
  83. //before booting the swarm node, build the configuration
  84. func buildConfig(ctx *cli.Context) (config *bzzapi.Config, err error) {
  85. //check for deprecated flags
  86. checkDeprecated(ctx)
  87. //start by creating a default config
  88. config = bzzapi.NewDefaultConfig()
  89. //first load settings from config file (if provided)
  90. config, err = configFileOverride(config, ctx)
  91. if err != nil {
  92. return nil, err
  93. }
  94. //override settings provided by environment variables
  95. config = envVarsOverride(config)
  96. //override settings provided by command line
  97. config = cmdLineOverride(config, ctx)
  98. //validate configuration parameters
  99. err = validateConfig(config)
  100. return
  101. }
  102. //finally, after the configuration build phase is finished, initialize
  103. func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context) {
  104. //at this point, all vars should be set in the Config
  105. //get the account for the provided swarm account
  106. prvkey := getAccount(config.BzzAccount, ctx, stack)
  107. //set the resolved config path (geth --datadir)
  108. config.Path = stack.InstanceDir()
  109. //finally, initialize the configuration
  110. config.Init(prvkey)
  111. //configuration phase completed here
  112. log.Debug("Starting Swarm with the following parameters:")
  113. //after having created the config, print it to screen
  114. log.Debug(printConfig(config))
  115. }
  116. //override the current config with whatever is in the config file, if a config file has been provided
  117. func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) {
  118. var err error
  119. //only do something if the -config flag has been set
  120. if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) {
  121. var filepath string
  122. if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" {
  123. utils.Fatalf("Config file flag provided with invalid file path")
  124. }
  125. f, err := os.Open(filepath)
  126. if err != nil {
  127. return nil, err
  128. }
  129. defer f.Close()
  130. //decode the TOML file into a Config struct
  131. //note that we are decoding into the existing defaultConfig;
  132. //if an entry is not present in the file, the default entry is kept
  133. err = tomlSettings.NewDecoder(f).Decode(&config)
  134. // Add file name to errors that have a line number.
  135. if _, ok := err.(*toml.LineError); ok {
  136. err = errors.New(filepath + ", " + err.Error())
  137. }
  138. }
  139. return config, err
  140. }
  141. //override the current config with whatever is provided through the command line
  142. //most values are not allowed a zero value (empty string), if not otherwise noted
  143. func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Config {
  144. if keyid := ctx.GlobalString(SwarmAccountFlag.Name); keyid != "" {
  145. currentConfig.BzzAccount = keyid
  146. }
  147. if chbookaddr := ctx.GlobalString(ChequebookAddrFlag.Name); chbookaddr != "" {
  148. currentConfig.Contract = common.HexToAddress(chbookaddr)
  149. }
  150. if networkid := ctx.GlobalString(SwarmNetworkIdFlag.Name); networkid != "" {
  151. if id, _ := strconv.Atoi(networkid); id != 0 {
  152. currentConfig.NetworkId = uint64(id)
  153. }
  154. }
  155. if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
  156. if datadir := ctx.GlobalString(utils.DataDirFlag.Name); datadir != "" {
  157. currentConfig.Path = datadir
  158. }
  159. }
  160. bzzport := ctx.GlobalString(SwarmPortFlag.Name)
  161. if len(bzzport) > 0 {
  162. currentConfig.Port = bzzport
  163. }
  164. if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
  165. currentConfig.ListenAddr = bzzaddr
  166. }
  167. if ctx.GlobalIsSet(SwarmSwapEnabledFlag.Name) {
  168. currentConfig.SwapEnabled = true
  169. }
  170. if ctx.GlobalIsSet(SwarmSyncEnabledFlag.Name) {
  171. currentConfig.SyncEnabled = true
  172. }
  173. currentConfig.SwapApi = ctx.GlobalString(SwarmSwapAPIFlag.Name)
  174. if currentConfig.SwapEnabled && currentConfig.SwapApi == "" {
  175. utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
  176. }
  177. if ctx.GlobalIsSet(EnsAPIFlag.Name) {
  178. ensAPIs := ctx.GlobalStringSlice(EnsAPIFlag.Name)
  179. // preserve backward compatibility to disable ENS with --ens-api=""
  180. if len(ensAPIs) == 1 && ensAPIs[0] == "" {
  181. ensAPIs = nil
  182. }
  183. currentConfig.EnsAPIs = ensAPIs
  184. }
  185. if ensaddr := ctx.GlobalString(DeprecatedEnsAddrFlag.Name); ensaddr != "" {
  186. currentConfig.EnsRoot = common.HexToAddress(ensaddr)
  187. }
  188. if cors := ctx.GlobalString(CorsStringFlag.Name); cors != "" {
  189. currentConfig.Cors = cors
  190. }
  191. if ctx.GlobalIsSet(utils.BootnodesFlag.Name) {
  192. currentConfig.BootNodes = ctx.GlobalString(utils.BootnodesFlag.Name)
  193. }
  194. return currentConfig
  195. }
  196. //override the current config with whatver is provided in environment variables
  197. //most values are not allowed a zero value (empty string), if not otherwise noted
  198. func envVarsOverride(currentConfig *bzzapi.Config) (config *bzzapi.Config) {
  199. if keyid := os.Getenv(SWARM_ENV_ACCOUNT); keyid != "" {
  200. currentConfig.BzzAccount = keyid
  201. }
  202. if chbookaddr := os.Getenv(SWARM_ENV_CHEQUEBOOK_ADDR); chbookaddr != "" {
  203. currentConfig.Contract = common.HexToAddress(chbookaddr)
  204. }
  205. if networkid := os.Getenv(SWARM_ENV_NETWORK_ID); networkid != "" {
  206. if id, _ := strconv.Atoi(networkid); id != 0 {
  207. currentConfig.NetworkId = uint64(id)
  208. }
  209. }
  210. if datadir := os.Getenv(GETH_ENV_DATADIR); datadir != "" {
  211. currentConfig.Path = datadir
  212. }
  213. bzzport := os.Getenv(SWARM_ENV_PORT)
  214. if len(bzzport) > 0 {
  215. currentConfig.Port = bzzport
  216. }
  217. if bzzaddr := os.Getenv(SWARM_ENV_LISTEN_ADDR); bzzaddr != "" {
  218. currentConfig.ListenAddr = bzzaddr
  219. }
  220. if swapenable := os.Getenv(SWARM_ENV_SWAP_ENABLE); swapenable != "" {
  221. if swap, err := strconv.ParseBool(swapenable); err != nil {
  222. currentConfig.SwapEnabled = swap
  223. }
  224. }
  225. if syncenable := os.Getenv(SWARM_ENV_SYNC_ENABLE); syncenable != "" {
  226. if sync, err := strconv.ParseBool(syncenable); err != nil {
  227. currentConfig.SyncEnabled = sync
  228. }
  229. }
  230. if swapapi := os.Getenv(SWARM_ENV_SWAP_API); swapapi != "" {
  231. currentConfig.SwapApi = swapapi
  232. }
  233. if currentConfig.SwapEnabled && currentConfig.SwapApi == "" {
  234. utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
  235. }
  236. if ensapi := os.Getenv(SWARM_ENV_ENS_API); ensapi != "" {
  237. currentConfig.EnsAPIs = strings.Split(ensapi, ",")
  238. }
  239. if ensaddr := os.Getenv(SWARM_ENV_ENS_ADDR); ensaddr != "" {
  240. currentConfig.EnsRoot = common.HexToAddress(ensaddr)
  241. }
  242. if cors := os.Getenv(SWARM_ENV_CORS); cors != "" {
  243. currentConfig.Cors = cors
  244. }
  245. if bootnodes := os.Getenv(SWARM_ENV_BOOTNODES); bootnodes != "" {
  246. currentConfig.BootNodes = bootnodes
  247. }
  248. return currentConfig
  249. }
  250. // dumpConfig is the dumpconfig command.
  251. // writes a default config to STDOUT
  252. func dumpConfig(ctx *cli.Context) error {
  253. cfg, err := buildConfig(ctx)
  254. if err != nil {
  255. utils.Fatalf(fmt.Sprintf("Uh oh - dumpconfig triggered an error %v", err))
  256. }
  257. comment := ""
  258. out, err := tomlSettings.Marshal(&cfg)
  259. if err != nil {
  260. return err
  261. }
  262. io.WriteString(os.Stdout, comment)
  263. os.Stdout.Write(out)
  264. return nil
  265. }
  266. //deprecated flags checked here
  267. func checkDeprecated(ctx *cli.Context) {
  268. // exit if the deprecated --ethapi flag is set
  269. if ctx.GlobalString(DeprecatedEthAPIFlag.Name) != "" {
  270. utils.Fatalf("--ethapi is no longer a valid command line flag, please use --ens-api and/or --swap-api.")
  271. }
  272. // warn if --ens-api flag is set
  273. if ctx.GlobalString(DeprecatedEnsAddrFlag.Name) != "" {
  274. log.Warn("--ens-addr is no longer a valid command line flag, please use --ens-api to specify contract address.")
  275. }
  276. }
  277. //validate configuration parameters
  278. func validateConfig(cfg *bzzapi.Config) (err error) {
  279. for _, ensAPI := range cfg.EnsAPIs {
  280. if ensAPI != "" {
  281. if err := validateEnsAPIs(ensAPI); err != nil {
  282. return fmt.Errorf("invalid format [tld:][contract-addr@]url for ENS API endpoint configuration %q: %v", ensAPI, err)
  283. }
  284. }
  285. }
  286. return nil
  287. }
  288. //validate EnsAPIs configuration parameter
  289. func validateEnsAPIs(s string) (err error) {
  290. // missing contract address
  291. if strings.HasPrefix(s, "@") {
  292. return errors.New("missing contract address")
  293. }
  294. // missing url
  295. if strings.HasSuffix(s, "@") {
  296. return errors.New("missing url")
  297. }
  298. // missing tld
  299. if strings.HasPrefix(s, ":") {
  300. return errors.New("missing tld")
  301. }
  302. // missing url
  303. if strings.HasSuffix(s, ":") {
  304. return errors.New("missing url")
  305. }
  306. return nil
  307. }
  308. //print a Config as string
  309. func printConfig(config *bzzapi.Config) string {
  310. out, err := tomlSettings.Marshal(&config)
  311. if err != nil {
  312. return fmt.Sprintf("Something is not right with the configuration: %v", err)
  313. }
  314. return string(out)
  315. }