config.go 13 KB

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