config.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. //override settings provided by environment variables
  92. config = envVarsOverride(config)
  93. //override settings provided by command line
  94. config = cmdLineOverride(config, ctx)
  95. return
  96. }
  97. //finally, after the configuration build phase is finished, initialize
  98. func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context) {
  99. //at this point, all vars should be set in the Config
  100. //get the account for the provided swarm account
  101. prvkey := getAccount(config.BzzAccount, ctx, stack)
  102. //set the resolved config path (geth --datadir)
  103. config.Path = stack.InstanceDir()
  104. //finally, initialize the configuration
  105. config.Init(prvkey)
  106. //configuration phase completed here
  107. log.Debug("Starting Swarm with the following parameters:")
  108. //after having created the config, print it to screen
  109. log.Debug(printConfig(config))
  110. }
  111. //override the current config with whatever is in the config file, if a config file has been provided
  112. func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) {
  113. var err error
  114. //only do something if the -config flag has been set
  115. if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) {
  116. var filepath string
  117. if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" {
  118. utils.Fatalf("Config file flag provided with invalid file path")
  119. }
  120. f, err := os.Open(filepath)
  121. if err != nil {
  122. return nil, err
  123. }
  124. defer f.Close()
  125. //decode the TOML file into a Config struct
  126. //note that we are decoding into the existing defaultConfig;
  127. //if an entry is not present in the file, the default entry is kept
  128. err = tomlSettings.NewDecoder(f).Decode(&config)
  129. // Add file name to errors that have a line number.
  130. if _, ok := err.(*toml.LineError); ok {
  131. err = errors.New(filepath + ", " + err.Error())
  132. }
  133. }
  134. return config, err
  135. }
  136. //override the current config with whatever is provided through the command line
  137. //most values are not allowed a zero value (empty string), if not otherwise noted
  138. func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Config {
  139. if keyid := ctx.GlobalString(SwarmAccountFlag.Name); keyid != "" {
  140. currentConfig.BzzAccount = keyid
  141. }
  142. if chbookaddr := ctx.GlobalString(ChequebookAddrFlag.Name); chbookaddr != "" {
  143. currentConfig.Contract = common.HexToAddress(chbookaddr)
  144. }
  145. if networkid := ctx.GlobalString(SwarmNetworkIdFlag.Name); networkid != "" {
  146. if id, _ := strconv.Atoi(networkid); id != 0 {
  147. currentConfig.NetworkId = uint64(id)
  148. }
  149. }
  150. if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
  151. if datadir := ctx.GlobalString(utils.DataDirFlag.Name); datadir != "" {
  152. currentConfig.Path = datadir
  153. }
  154. }
  155. bzzport := ctx.GlobalString(SwarmPortFlag.Name)
  156. if len(bzzport) > 0 {
  157. currentConfig.Port = bzzport
  158. }
  159. if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
  160. currentConfig.ListenAddr = bzzaddr
  161. }
  162. if ctx.GlobalIsSet(SwarmSwapEnabledFlag.Name) {
  163. currentConfig.SwapEnabled = true
  164. }
  165. if ctx.GlobalIsSet(SwarmSyncEnabledFlag.Name) {
  166. currentConfig.SyncEnabled = true
  167. }
  168. currentConfig.SwapApi = ctx.GlobalString(SwarmSwapAPIFlag.Name)
  169. if currentConfig.SwapEnabled && currentConfig.SwapApi == "" {
  170. utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
  171. }
  172. if ctx.GlobalIsSet(EnsAPIFlag.Name) {
  173. ensAPIs := ctx.GlobalStringSlice(EnsAPIFlag.Name)
  174. // preserve backward compatibility to disable ENS with --ens-api=""
  175. if len(ensAPIs) == 1 && ensAPIs[0] == "" {
  176. ensAPIs = nil
  177. }
  178. currentConfig.EnsAPIs = ensAPIs
  179. }
  180. if ensaddr := ctx.GlobalString(DeprecatedEnsAddrFlag.Name); ensaddr != "" {
  181. currentConfig.EnsRoot = common.HexToAddress(ensaddr)
  182. }
  183. if cors := ctx.GlobalString(CorsStringFlag.Name); cors != "" {
  184. currentConfig.Cors = cors
  185. }
  186. if ctx.GlobalIsSet(utils.BootnodesFlag.Name) {
  187. currentConfig.BootNodes = ctx.GlobalString(utils.BootnodesFlag.Name)
  188. }
  189. return currentConfig
  190. }
  191. //override the current config with whatver is provided in environment variables
  192. //most values are not allowed a zero value (empty string), if not otherwise noted
  193. func envVarsOverride(currentConfig *bzzapi.Config) (config *bzzapi.Config) {
  194. if keyid := os.Getenv(SWARM_ENV_ACCOUNT); keyid != "" {
  195. currentConfig.BzzAccount = keyid
  196. }
  197. if chbookaddr := os.Getenv(SWARM_ENV_CHEQUEBOOK_ADDR); chbookaddr != "" {
  198. currentConfig.Contract = common.HexToAddress(chbookaddr)
  199. }
  200. if networkid := os.Getenv(SWARM_ENV_NETWORK_ID); networkid != "" {
  201. if id, _ := strconv.Atoi(networkid); id != 0 {
  202. currentConfig.NetworkId = uint64(id)
  203. }
  204. }
  205. if datadir := os.Getenv(GETH_ENV_DATADIR); datadir != "" {
  206. currentConfig.Path = datadir
  207. }
  208. bzzport := os.Getenv(SWARM_ENV_PORT)
  209. if len(bzzport) > 0 {
  210. currentConfig.Port = bzzport
  211. }
  212. if bzzaddr := os.Getenv(SWARM_ENV_LISTEN_ADDR); bzzaddr != "" {
  213. currentConfig.ListenAddr = bzzaddr
  214. }
  215. if swapenable := os.Getenv(SWARM_ENV_SWAP_ENABLE); swapenable != "" {
  216. if swap, err := strconv.ParseBool(swapenable); err != nil {
  217. currentConfig.SwapEnabled = swap
  218. }
  219. }
  220. if syncenable := os.Getenv(SWARM_ENV_SYNC_ENABLE); syncenable != "" {
  221. if sync, err := strconv.ParseBool(syncenable); err != nil {
  222. currentConfig.SyncEnabled = sync
  223. }
  224. }
  225. if swapapi := os.Getenv(SWARM_ENV_SWAP_API); swapapi != "" {
  226. currentConfig.SwapApi = swapapi
  227. }
  228. if currentConfig.SwapEnabled && currentConfig.SwapApi == "" {
  229. utils.Fatalf(SWARM_ERR_SWAP_SET_NO_API)
  230. }
  231. if ensapi := os.Getenv(SWARM_ENV_ENS_API); ensapi != "" {
  232. currentConfig.EnsAPIs = strings.Split(ensapi, ",")
  233. }
  234. if ensaddr := os.Getenv(SWARM_ENV_ENS_ADDR); ensaddr != "" {
  235. currentConfig.EnsRoot = common.HexToAddress(ensaddr)
  236. }
  237. if cors := os.Getenv(SWARM_ENV_CORS); cors != "" {
  238. currentConfig.Cors = cors
  239. }
  240. if bootnodes := os.Getenv(SWARM_ENV_BOOTNODES); bootnodes != "" {
  241. currentConfig.BootNodes = bootnodes
  242. }
  243. return currentConfig
  244. }
  245. // dumpConfig is the dumpconfig command.
  246. // writes a default config to STDOUT
  247. func dumpConfig(ctx *cli.Context) error {
  248. cfg, err := buildConfig(ctx)
  249. if err != nil {
  250. utils.Fatalf(fmt.Sprintf("Uh oh - dumpconfig triggered an error %v", err))
  251. }
  252. comment := ""
  253. out, err := tomlSettings.Marshal(&cfg)
  254. if err != nil {
  255. return err
  256. }
  257. io.WriteString(os.Stdout, comment)
  258. os.Stdout.Write(out)
  259. return nil
  260. }
  261. //deprecated flags checked here
  262. func checkDeprecated(ctx *cli.Context) {
  263. // exit if the deprecated --ethapi flag is set
  264. if ctx.GlobalString(DeprecatedEthAPIFlag.Name) != "" {
  265. utils.Fatalf("--ethapi is no longer a valid command line flag, please use --ens-api and/or --swap-api.")
  266. }
  267. // warn if --ens-api flag is set
  268. if ctx.GlobalString(DeprecatedEnsAddrFlag.Name) != "" {
  269. log.Warn("--ens-addr is no longer a valid command line flag, please use --ens-api to specify contract address.")
  270. }
  271. }
  272. //print a Config as string
  273. func printConfig(config *bzzapi.Config) string {
  274. out, err := tomlSettings.Marshal(&config)
  275. if err != nil {
  276. return (fmt.Sprintf("Something is not right with the configuration: %v", err))
  277. }
  278. return string(out)
  279. }