config.go 12 KB

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