config.go 12 KB

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