config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. "time"
  26. "unicode"
  27. cli "gopkg.in/urfave/cli.v1"
  28. "github.com/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/node"
  32. "github.com/naoina/toml"
  33. bzzapi "github.com/ethereum/go-ethereum/swarm/api"
  34. )
  35. var (
  36. //flag definition for the dumpconfig command
  37. DumpConfigCommand = cli.Command{
  38. Action: utils.MigrateFlags(dumpConfig),
  39. Name: "dumpconfig",
  40. Usage: "Show configuration values",
  41. ArgsUsage: "",
  42. Flags: app.Flags,
  43. Category: "MISCELLANEOUS COMMANDS",
  44. Description: `The dumpconfig command shows configuration values.`,
  45. }
  46. //flag definition for the config file command
  47. SwarmTomlConfigPathFlag = cli.StringFlag{
  48. Name: "config",
  49. Usage: "TOML configuration file",
  50. }
  51. )
  52. //constants for environment variables
  53. const (
  54. SwarmEnvChequebookAddr = "SWARM_CHEQUEBOOK_ADDR"
  55. SwarmEnvAccount = "SWARM_ACCOUNT"
  56. SwarmEnvListenAddr = "SWARM_LISTEN_ADDR"
  57. SwarmEnvPort = "SWARM_PORT"
  58. SwarmEnvNetworkID = "SWARM_NETWORK_ID"
  59. SwarmEnvSwapEnable = "SWARM_SWAP_ENABLE"
  60. SwarmEnvSwapAPI = "SWARM_SWAP_API"
  61. SwarmEnvSyncDisable = "SWARM_SYNC_DISABLE"
  62. SwarmEnvSyncUpdateDelay = "SWARM_ENV_SYNC_UPDATE_DELAY"
  63. SwarmEnvMaxStreamPeerServers = "SWARM_ENV_MAX_STREAM_PEER_SERVERS"
  64. SwarmEnvLightNodeEnable = "SWARM_LIGHT_NODE_ENABLE"
  65. SwarmEnvDeliverySkipCheck = "SWARM_DELIVERY_SKIP_CHECK"
  66. SwarmEnvENSAPI = "SWARM_ENS_API"
  67. SwarmEnvENSAddr = "SWARM_ENS_ADDR"
  68. SwarmEnvCORS = "SWARM_CORS"
  69. SwarmEnvBootnodes = "SWARM_BOOTNODES"
  70. SwarmEnvPSSEnable = "SWARM_PSS_ENABLE"
  71. SwarmEnvStorePath = "SWARM_STORE_PATH"
  72. SwarmEnvStoreCapacity = "SWARM_STORE_CAPACITY"
  73. SwarmEnvStoreCacheCapacity = "SWARM_STORE_CACHE_CAPACITY"
  74. SwarmEnvBootnodeMode = "SWARM_BOOTNODE_MODE"
  75. SwarmAccessPassword = "SWARM_ACCESS_PASSWORD"
  76. SwarmAutoDefaultPath = "SWARM_AUTO_DEFAULTPATH"
  77. SwarmGlobalstoreAPI = "SWARM_GLOBALSTORE_API"
  78. GethEnvDataDir = "GETH_DATADIR"
  79. )
  80. // These settings ensure that TOML keys use the same names as Go struct fields.
  81. var tomlSettings = toml.Config{
  82. NormFieldName: func(rt reflect.Type, key string) string {
  83. return key
  84. },
  85. FieldToKey: func(rt reflect.Type, field string) string {
  86. return field
  87. },
  88. MissingField: func(rt reflect.Type, field string) error {
  89. link := ""
  90. if unicode.IsUpper(rune(rt.Name()[0])) && rt.PkgPath() != "main" {
  91. link = fmt.Sprintf(", check github.com/ethereum/go-ethereum/swarm/api/config.go for available fields")
  92. }
  93. return fmt.Errorf("field '%s' is not defined in %s%s", field, rt.String(), link)
  94. },
  95. }
  96. //before booting the swarm node, build the configuration
  97. func buildConfig(ctx *cli.Context) (config *bzzapi.Config, err error) {
  98. //start by creating a default config
  99. config = bzzapi.NewConfig()
  100. //first load settings from config file (if provided)
  101. config, err = configFileOverride(config, ctx)
  102. if err != nil {
  103. return nil, err
  104. }
  105. //override settings provided by environment variables
  106. config = envVarsOverride(config)
  107. //override settings provided by command line
  108. config = cmdLineOverride(config, ctx)
  109. //validate configuration parameters
  110. err = validateConfig(config)
  111. return
  112. }
  113. //finally, after the configuration build phase is finished, initialize
  114. func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context, nodeconfig *node.Config) error {
  115. //at this point, all vars should be set in the Config
  116. //get the account for the provided swarm account
  117. prvkey := getAccount(config.BzzAccount, ctx, stack)
  118. //set the resolved config path (geth --datadir)
  119. config.Path = expandPath(stack.InstanceDir())
  120. //finally, initialize the configuration
  121. err := config.Init(prvkey, nodeconfig.NodeKey())
  122. if err != nil {
  123. return err
  124. }
  125. //configuration phase completed here
  126. log.Debug("Starting Swarm with the following parameters:")
  127. //after having created the config, print it to screen
  128. log.Debug(printConfig(config))
  129. return nil
  130. }
  131. //configFileOverride overrides the current config with the config file, if a config file has been provided
  132. func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) {
  133. var err error
  134. //only do something if the -config flag has been set
  135. if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) {
  136. var filepath string
  137. if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" {
  138. utils.Fatalf("Config file flag provided with invalid file path")
  139. }
  140. var f *os.File
  141. f, err = os.Open(filepath)
  142. if err != nil {
  143. return nil, err
  144. }
  145. defer f.Close()
  146. //decode the TOML file into a Config struct
  147. //note that we are decoding into the existing defaultConfig;
  148. //if an entry is not present in the file, the default entry is kept
  149. err = tomlSettings.NewDecoder(f).Decode(&config)
  150. // Add file name to errors that have a line number.
  151. if _, ok := err.(*toml.LineError); ok {
  152. err = errors.New(filepath + ", " + err.Error())
  153. }
  154. }
  155. return config, err
  156. }
  157. // cmdLineOverride overrides the current config with whatever is provided through the command line
  158. // most values are not allowed a zero value (empty string), if not otherwise noted
  159. func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Config {
  160. if keyid := ctx.GlobalString(SwarmAccountFlag.Name); keyid != "" {
  161. currentConfig.BzzAccount = keyid
  162. }
  163. if chbookaddr := ctx.GlobalString(ChequebookAddrFlag.Name); chbookaddr != "" {
  164. currentConfig.Contract = common.HexToAddress(chbookaddr)
  165. }
  166. if networkid := ctx.GlobalString(SwarmNetworkIdFlag.Name); networkid != "" {
  167. id, err := strconv.ParseUint(networkid, 10, 64)
  168. if err != nil {
  169. utils.Fatalf("invalid cli flag %s: %v", SwarmNetworkIdFlag.Name, err)
  170. }
  171. if id != 0 {
  172. currentConfig.NetworkID = id
  173. }
  174. }
  175. if ctx.GlobalIsSet(utils.DataDirFlag.Name) {
  176. if datadir := ctx.GlobalString(utils.DataDirFlag.Name); datadir != "" {
  177. currentConfig.Path = expandPath(datadir)
  178. }
  179. }
  180. bzzport := ctx.GlobalString(SwarmPortFlag.Name)
  181. if len(bzzport) > 0 {
  182. currentConfig.Port = bzzport
  183. }
  184. if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
  185. currentConfig.ListenAddr = bzzaddr
  186. }
  187. if ctx.GlobalIsSet(SwarmSwapEnabledFlag.Name) {
  188. currentConfig.SwapEnabled = true
  189. }
  190. if ctx.GlobalIsSet(SwarmSyncDisabledFlag.Name) {
  191. currentConfig.SyncEnabled = false
  192. }
  193. if d := ctx.GlobalDuration(SwarmSyncUpdateDelay.Name); d > 0 {
  194. currentConfig.SyncUpdateDelay = d
  195. }
  196. // any value including 0 is acceptable
  197. currentConfig.MaxStreamPeerServers = ctx.GlobalInt(SwarmMaxStreamPeerServersFlag.Name)
  198. if ctx.GlobalIsSet(SwarmLightNodeEnabled.Name) {
  199. currentConfig.LightNodeEnabled = true
  200. }
  201. if ctx.GlobalIsSet(SwarmDeliverySkipCheckFlag.Name) {
  202. currentConfig.DeliverySkipCheck = true
  203. }
  204. currentConfig.SwapAPI = ctx.GlobalString(SwarmSwapAPIFlag.Name)
  205. if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
  206. utils.Fatalf(SwarmErrSwapSetNoAPI)
  207. }
  208. if ctx.GlobalIsSet(EnsAPIFlag.Name) {
  209. ensAPIs := ctx.GlobalStringSlice(EnsAPIFlag.Name)
  210. // preserve backward compatibility to disable ENS with --ens-api=""
  211. if len(ensAPIs) == 1 && ensAPIs[0] == "" {
  212. ensAPIs = nil
  213. }
  214. for i := range ensAPIs {
  215. ensAPIs[i] = expandPath(ensAPIs[i])
  216. }
  217. currentConfig.EnsAPIs = ensAPIs
  218. }
  219. if cors := ctx.GlobalString(CorsStringFlag.Name); cors != "" {
  220. currentConfig.Cors = cors
  221. }
  222. if storePath := ctx.GlobalString(SwarmStorePath.Name); storePath != "" {
  223. currentConfig.ChunkDbPath = storePath
  224. }
  225. if storeCapacity := ctx.GlobalUint64(SwarmStoreCapacity.Name); storeCapacity != 0 {
  226. currentConfig.DbCapacity = storeCapacity
  227. }
  228. if ctx.GlobalIsSet(SwarmStoreCacheCapacity.Name) {
  229. currentConfig.CacheCapacity = ctx.GlobalUint(SwarmStoreCacheCapacity.Name)
  230. }
  231. if ctx.GlobalIsSet(SwarmBootnodeModeFlag.Name) {
  232. currentConfig.BootnodeMode = ctx.GlobalBool(SwarmBootnodeModeFlag.Name)
  233. }
  234. if ctx.GlobalIsSet(SwarmGlobalStoreAPIFlag.Name) {
  235. currentConfig.GlobalStoreAPI = ctx.GlobalString(SwarmGlobalStoreAPIFlag.Name)
  236. }
  237. return currentConfig
  238. }
  239. // envVarsOverride overrides the current config with whatver is provided in environment variables
  240. // most values are not allowed a zero value (empty string), if not otherwise noted
  241. func envVarsOverride(currentConfig *bzzapi.Config) (config *bzzapi.Config) {
  242. if keyid := os.Getenv(SwarmEnvAccount); keyid != "" {
  243. currentConfig.BzzAccount = keyid
  244. }
  245. if chbookaddr := os.Getenv(SwarmEnvChequebookAddr); chbookaddr != "" {
  246. currentConfig.Contract = common.HexToAddress(chbookaddr)
  247. }
  248. if networkid := os.Getenv(SwarmEnvNetworkID); networkid != "" {
  249. id, err := strconv.ParseUint(networkid, 10, 64)
  250. if err != nil {
  251. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvNetworkID, err)
  252. }
  253. if id != 0 {
  254. currentConfig.NetworkID = id
  255. }
  256. }
  257. if datadir := os.Getenv(GethEnvDataDir); datadir != "" {
  258. currentConfig.Path = expandPath(datadir)
  259. }
  260. bzzport := os.Getenv(SwarmEnvPort)
  261. if len(bzzport) > 0 {
  262. currentConfig.Port = bzzport
  263. }
  264. if bzzaddr := os.Getenv(SwarmEnvListenAddr); bzzaddr != "" {
  265. currentConfig.ListenAddr = bzzaddr
  266. }
  267. if swapenable := os.Getenv(SwarmEnvSwapEnable); swapenable != "" {
  268. swap, err := strconv.ParseBool(swapenable)
  269. if err != nil {
  270. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvSwapEnable, err)
  271. }
  272. currentConfig.SwapEnabled = swap
  273. }
  274. if syncdisable := os.Getenv(SwarmEnvSyncDisable); syncdisable != "" {
  275. sync, err := strconv.ParseBool(syncdisable)
  276. if err != nil {
  277. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvSyncDisable, err)
  278. }
  279. currentConfig.SyncEnabled = !sync
  280. }
  281. if v := os.Getenv(SwarmEnvDeliverySkipCheck); v != "" {
  282. skipCheck, err := strconv.ParseBool(v)
  283. if err != nil {
  284. currentConfig.DeliverySkipCheck = skipCheck
  285. }
  286. }
  287. if v := os.Getenv(SwarmEnvSyncUpdateDelay); v != "" {
  288. d, err := time.ParseDuration(v)
  289. if err != nil {
  290. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvSyncUpdateDelay, err)
  291. }
  292. currentConfig.SyncUpdateDelay = d
  293. }
  294. if max := os.Getenv(SwarmEnvMaxStreamPeerServers); max != "" {
  295. m, err := strconv.Atoi(max)
  296. if err != nil {
  297. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvMaxStreamPeerServers, err)
  298. }
  299. currentConfig.MaxStreamPeerServers = m
  300. }
  301. if lne := os.Getenv(SwarmEnvLightNodeEnable); lne != "" {
  302. lightnode, err := strconv.ParseBool(lne)
  303. if err != nil {
  304. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvLightNodeEnable, err)
  305. }
  306. currentConfig.LightNodeEnabled = lightnode
  307. }
  308. if swapapi := os.Getenv(SwarmEnvSwapAPI); swapapi != "" {
  309. currentConfig.SwapAPI = swapapi
  310. }
  311. if currentConfig.SwapEnabled && currentConfig.SwapAPI == "" {
  312. utils.Fatalf(SwarmErrSwapSetNoAPI)
  313. }
  314. if ensapi := os.Getenv(SwarmEnvENSAPI); ensapi != "" {
  315. currentConfig.EnsAPIs = strings.Split(ensapi, ",")
  316. }
  317. if ensaddr := os.Getenv(SwarmEnvENSAddr); ensaddr != "" {
  318. currentConfig.EnsRoot = common.HexToAddress(ensaddr)
  319. }
  320. if cors := os.Getenv(SwarmEnvCORS); cors != "" {
  321. currentConfig.Cors = cors
  322. }
  323. if bm := os.Getenv(SwarmEnvBootnodeMode); bm != "" {
  324. bootnodeMode, err := strconv.ParseBool(bm)
  325. if err != nil {
  326. utils.Fatalf("invalid environment variable %s: %v", SwarmEnvBootnodeMode, err)
  327. }
  328. currentConfig.BootnodeMode = bootnodeMode
  329. }
  330. if api := os.Getenv(SwarmGlobalstoreAPI); api != "" {
  331. currentConfig.GlobalStoreAPI = api
  332. }
  333. return currentConfig
  334. }
  335. // dumpConfig is the dumpconfig command.
  336. // writes a default config to STDOUT
  337. func dumpConfig(ctx *cli.Context) error {
  338. cfg, err := buildConfig(ctx)
  339. if err != nil {
  340. utils.Fatalf(fmt.Sprintf("Uh oh - dumpconfig triggered an error %v", err))
  341. }
  342. comment := ""
  343. out, err := tomlSettings.Marshal(&cfg)
  344. if err != nil {
  345. return err
  346. }
  347. io.WriteString(os.Stdout, comment)
  348. os.Stdout.Write(out)
  349. return nil
  350. }
  351. //validate configuration parameters
  352. func validateConfig(cfg *bzzapi.Config) (err error) {
  353. for _, ensAPI := range cfg.EnsAPIs {
  354. if ensAPI != "" {
  355. if err := validateEnsAPIs(ensAPI); err != nil {
  356. return fmt.Errorf("invalid format [tld:][contract-addr@]url for ENS API endpoint configuration %q: %v", ensAPI, err)
  357. }
  358. }
  359. }
  360. return nil
  361. }
  362. //validate EnsAPIs configuration parameter
  363. func validateEnsAPIs(s string) (err error) {
  364. // missing contract address
  365. if strings.HasPrefix(s, "@") {
  366. return errors.New("missing contract address")
  367. }
  368. // missing url
  369. if strings.HasSuffix(s, "@") {
  370. return errors.New("missing url")
  371. }
  372. // missing tld
  373. if strings.HasPrefix(s, ":") {
  374. return errors.New("missing tld")
  375. }
  376. // missing url
  377. if strings.HasSuffix(s, ":") {
  378. return errors.New("missing url")
  379. }
  380. return nil
  381. }
  382. //print a Config as string
  383. func printConfig(config *bzzapi.Config) string {
  384. out, err := tomlSettings.Marshal(&config)
  385. if err != nil {
  386. return fmt.Sprintf("Something is not right with the configuration: %v", err)
  387. }
  388. return string(out)
  389. }