config.go 13 KB

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