config.go 12 KB

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