config.go 9.7 KB

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