You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

407 lines
14 KiB

  1. package config
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "text/template"
  8. cmn "github.com/tendermint/tendermint/libs/common"
  9. )
  10. var configTemplate *template.Template
  11. func init() {
  12. var err error
  13. if configTemplate, err = template.New("configFileTemplate").Parse(defaultConfigTemplate); err != nil {
  14. panic(err)
  15. }
  16. }
  17. /****** these are for production settings ***********/
  18. // EnsureRoot creates the root, config, and data directories if they don't exist,
  19. // and panics if it fails.
  20. func EnsureRoot(rootDir string) {
  21. if err := cmn.EnsureDir(rootDir, 0700); err != nil {
  22. cmn.PanicSanity(err.Error())
  23. }
  24. if err := cmn.EnsureDir(filepath.Join(rootDir, defaultConfigDir), 0700); err != nil {
  25. cmn.PanicSanity(err.Error())
  26. }
  27. if err := cmn.EnsureDir(filepath.Join(rootDir, defaultDataDir), 0700); err != nil {
  28. cmn.PanicSanity(err.Error())
  29. }
  30. configFilePath := filepath.Join(rootDir, defaultConfigFilePath)
  31. // Write default config file if missing.
  32. if !cmn.FileExists(configFilePath) {
  33. writeDefaultConfigFile(configFilePath)
  34. }
  35. }
  36. // XXX: this func should probably be called by cmd/tendermint/commands/init.go
  37. // alongside the writing of the genesis.json and priv_validator.json
  38. func writeDefaultConfigFile(configFilePath string) {
  39. WriteConfigFile(configFilePath, DefaultConfig())
  40. }
  41. // WriteConfigFile renders config using the template and writes it to configFilePath.
  42. func WriteConfigFile(configFilePath string, config *Config) {
  43. var buffer bytes.Buffer
  44. if err := configTemplate.Execute(&buffer, config); err != nil {
  45. panic(err)
  46. }
  47. cmn.MustWriteFile(configFilePath, buffer.Bytes(), 0644)
  48. }
  49. // Note: any changes to the comments/variables/mapstructure
  50. // must be reflected in the appropriate struct in config/config.go
  51. const defaultConfigTemplate = `# This is a TOML config file.
  52. # For more information, see https://github.com/toml-lang/toml
  53. ##### main base config options #####
  54. # TCP or UNIX socket address of the ABCI application,
  55. # or the name of an ABCI application compiled in with the Tendermint binary
  56. proxy_app = "{{ .BaseConfig.ProxyApp }}"
  57. # A custom human readable name for this node
  58. moniker = "{{ .BaseConfig.Moniker }}"
  59. # If this node is many blocks behind the tip of the chain, FastSync
  60. # allows them to catchup quickly by downloading blocks in parallel
  61. # and verifying their commits
  62. fast_sync = {{ .BaseConfig.FastSync }}
  63. # Database backend: leveldb | memdb | cleveldb
  64. db_backend = "{{ .BaseConfig.DBBackend }}"
  65. # Database directory
  66. db_dir = "{{ js .BaseConfig.DBPath }}"
  67. # Output level for logging, including package level options
  68. log_level = "{{ .BaseConfig.LogLevel }}"
  69. # Output format: 'plain' (colored text) or 'json'
  70. log_format = "{{ .BaseConfig.LogFormat }}"
  71. ##### additional base config options #####
  72. # Path to the JSON file containing the initial validator set and other meta data
  73. genesis_file = "{{ js .BaseConfig.Genesis }}"
  74. # Path to the JSON file containing the private key to use as a validator in the consensus protocol
  75. priv_validator_key_file = "{{ js .BaseConfig.PrivValidatorKey }}"
  76. # Path to the JSON file containing the last sign state of a validator
  77. priv_validator_state_file = "{{ js .BaseConfig.PrivValidatorState }}"
  78. # TCP or UNIX socket address for Tendermint to listen on for
  79. # connections from an external PrivValidator process
  80. priv_validator_laddr = "{{ .BaseConfig.PrivValidatorListenAddr }}"
  81. # Path to the JSON file containing the private key to use for node authentication in the p2p protocol
  82. node_key_file = "{{ js .BaseConfig.NodeKey }}"
  83. # Mechanism to connect to the ABCI application: socket | grpc
  84. abci = "{{ .BaseConfig.ABCI }}"
  85. # TCP or UNIX socket address for the profiling server to listen on
  86. prof_laddr = "{{ .BaseConfig.ProfListenAddress }}"
  87. # If true, query the ABCI app on connecting to a new peer
  88. # so the app can decide if we should keep the connection or not
  89. filter_peers = {{ .BaseConfig.FilterPeers }}
  90. ##### advanced configuration options #####
  91. ##### rpc server configuration options #####
  92. [rpc]
  93. # TCP or UNIX socket address for the RPC server to listen on
  94. laddr = "{{ .RPC.ListenAddress }}"
  95. # A list of origins a cross-domain request can be executed from
  96. # Default value '[]' disables cors support
  97. # Use '["*"]' to allow any origin
  98. cors_allowed_origins = [{{ range .RPC.CORSAllowedOrigins }}{{ printf "%q, " . }}{{end}}]
  99. # A list of methods the client is allowed to use with cross-domain requests
  100. cors_allowed_methods = [{{ range .RPC.CORSAllowedMethods }}{{ printf "%q, " . }}{{end}}]
  101. # A list of non simple headers the client is allowed to use with cross-domain requests
  102. cors_allowed_headers = [{{ range .RPC.CORSAllowedHeaders }}{{ printf "%q, " . }}{{end}}]
  103. # TCP or UNIX socket address for the gRPC server to listen on
  104. # NOTE: This server only supports /broadcast_tx_commit
  105. grpc_laddr = "{{ .RPC.GRPCListenAddress }}"
  106. # Maximum number of simultaneous connections.
  107. # Does not include RPC (HTTP&WebSocket) connections. See max_open_connections
  108. # If you want to accept a larger number than the default, make sure
  109. # you increase your OS limits.
  110. # 0 - unlimited.
  111. # Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  112. # 1024 - 40 - 10 - 50 = 924 = ~900
  113. grpc_max_open_connections = {{ .RPC.GRPCMaxOpenConnections }}
  114. # Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool
  115. unsafe = {{ .RPC.Unsafe }}
  116. # Maximum number of simultaneous connections (including WebSocket).
  117. # Does not include gRPC connections. See grpc_max_open_connections
  118. # If you want to accept a larger number than the default, make sure
  119. # you increase your OS limits.
  120. # 0 - unlimited.
  121. # Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  122. # 1024 - 40 - 10 - 50 = 924 = ~900
  123. max_open_connections = {{ .RPC.MaxOpenConnections }}
  124. ##### peer to peer configuration options #####
  125. [p2p]
  126. # Address to listen for incoming connections
  127. laddr = "{{ .P2P.ListenAddress }}"
  128. # Address to advertise to peers for them to dial
  129. # If empty, will use the same port as the laddr,
  130. # and will introspect on the listener or use UPnP
  131. # to figure out the address.
  132. external_address = "{{ .P2P.ExternalAddress }}"
  133. # Comma separated list of seed nodes to connect to
  134. seeds = "{{ .P2P.Seeds }}"
  135. # Comma separated list of nodes to keep persistent connections to
  136. persistent_peers = "{{ .P2P.PersistentPeers }}"
  137. # UPNP port forwarding
  138. upnp = {{ .P2P.UPNP }}
  139. # Path to address book
  140. addr_book_file = "{{ js .P2P.AddrBook }}"
  141. # Set true for strict address routability rules
  142. # Set false for private or local networks
  143. addr_book_strict = {{ .P2P.AddrBookStrict }}
  144. # Maximum number of inbound peers
  145. max_num_inbound_peers = {{ .P2P.MaxNumInboundPeers }}
  146. # Maximum number of outbound peers to connect to, excluding persistent peers
  147. max_num_outbound_peers = {{ .P2P.MaxNumOutboundPeers }}
  148. # Time to wait before flushing messages out on the connection
  149. flush_throttle_timeout = "{{ .P2P.FlushThrottleTimeout }}"
  150. # Maximum size of a message packet payload, in bytes
  151. max_packet_msg_payload_size = {{ .P2P.MaxPacketMsgPayloadSize }}
  152. # Rate at which packets can be sent, in bytes/second
  153. send_rate = {{ .P2P.SendRate }}
  154. # Rate at which packets can be received, in bytes/second
  155. recv_rate = {{ .P2P.RecvRate }}
  156. # Set true to enable the peer-exchange reactor
  157. pex = {{ .P2P.PexReactor }}
  158. # Seed mode, in which node constantly crawls the network and looks for
  159. # peers. If another node asks it for addresses, it responds and disconnects.
  160. #
  161. # Does not work if the peer-exchange reactor is disabled.
  162. seed_mode = {{ .P2P.SeedMode }}
  163. # Comma separated list of peer IDs to keep private (will not be gossiped to other peers)
  164. private_peer_ids = "{{ .P2P.PrivatePeerIDs }}"
  165. # Toggle to disable guard against peers connecting from the same ip.
  166. allow_duplicate_ip = {{ .P2P.AllowDuplicateIP }}
  167. # Peer connection configuration.
  168. handshake_timeout = "{{ .P2P.HandshakeTimeout }}"
  169. dial_timeout = "{{ .P2P.DialTimeout }}"
  170. ##### mempool configuration options #####
  171. [mempool]
  172. recheck = {{ .Mempool.Recheck }}
  173. broadcast = {{ .Mempool.Broadcast }}
  174. wal_dir = "{{ js .Mempool.WalPath }}"
  175. # size of the mempool
  176. size = {{ .Mempool.Size }}
  177. # size of the cache (used to filter transactions we saw earlier)
  178. cache_size = {{ .Mempool.CacheSize }}
  179. ##### consensus configuration options #####
  180. [consensus]
  181. wal_file = "{{ js .Consensus.WalPath }}"
  182. timeout_propose = "{{ .Consensus.TimeoutPropose }}"
  183. timeout_propose_delta = "{{ .Consensus.TimeoutProposeDelta }}"
  184. timeout_prevote = "{{ .Consensus.TimeoutPrevote }}"
  185. timeout_prevote_delta = "{{ .Consensus.TimeoutPrevoteDelta }}"
  186. timeout_precommit = "{{ .Consensus.TimeoutPrecommit }}"
  187. timeout_precommit_delta = "{{ .Consensus.TimeoutPrecommitDelta }}"
  188. timeout_commit = "{{ .Consensus.TimeoutCommit }}"
  189. # Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  190. skip_timeout_commit = {{ .Consensus.SkipTimeoutCommit }}
  191. # EmptyBlocks mode and possible interval between empty blocks
  192. create_empty_blocks = {{ .Consensus.CreateEmptyBlocks }}
  193. create_empty_blocks_interval = "{{ .Consensus.CreateEmptyBlocksInterval }}"
  194. # Reactor sleep duration parameters
  195. peer_gossip_sleep_duration = "{{ .Consensus.PeerGossipSleepDuration }}"
  196. peer_query_maj23_sleep_duration = "{{ .Consensus.PeerQueryMaj23SleepDuration }}"
  197. # Block time parameters. Corresponds to the minimum time increment between consecutive blocks.
  198. blocktime_iota = "{{ .Consensus.BlockTimeIota }}"
  199. ##### transactions indexer configuration options #####
  200. [tx_index]
  201. # What indexer to use for transactions
  202. #
  203. # Options:
  204. # 1) "null"
  205. # 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend).
  206. indexer = "{{ .TxIndex.Indexer }}"
  207. # Comma-separated list of tags to index (by default the only tag is "tx.hash")
  208. #
  209. # You can also index transactions by height by adding "tx.height" tag here.
  210. #
  211. # It's recommended to index only a subset of tags due to possible memory
  212. # bloat. This is, of course, depends on the indexer's DB and the volume of
  213. # transactions.
  214. index_tags = "{{ .TxIndex.IndexTags }}"
  215. # When set to true, tells indexer to index all tags (predefined tags:
  216. # "tx.hash", "tx.height" and all tags from DeliverTx responses).
  217. #
  218. # Note this may be not desirable (see the comment above). IndexTags has a
  219. # precedence over IndexAllTags (i.e. when given both, IndexTags will be
  220. # indexed).
  221. index_all_tags = {{ .TxIndex.IndexAllTags }}
  222. ##### instrumentation configuration options #####
  223. [instrumentation]
  224. # When true, Prometheus metrics are served under /metrics on
  225. # PrometheusListenAddr.
  226. # Check out the documentation for the list of available metrics.
  227. prometheus = {{ .Instrumentation.Prometheus }}
  228. # Address to listen for Prometheus collector(s) connections
  229. prometheus_listen_addr = "{{ .Instrumentation.PrometheusListenAddr }}"
  230. # Maximum number of simultaneous connections.
  231. # If you want to accept a larger number than the default, make sure
  232. # you increase your OS limits.
  233. # 0 - unlimited.
  234. max_open_connections = {{ .Instrumentation.MaxOpenConnections }}
  235. # Instrumentation namespace
  236. namespace = "{{ .Instrumentation.Namespace }}"
  237. `
  238. /****** these are for test settings ***********/
  239. func ResetTestRoot(testName string) *Config {
  240. return ResetTestRootWithChainID(testName, "")
  241. }
  242. func ResetTestRootWithChainID(testName string, chainID string) *Config {
  243. rootDir := os.ExpandEnv("$HOME/.tendermint_test")
  244. rootDir = filepath.Join(rootDir, testName)
  245. // Remove ~/.tendermint_test_bak
  246. if cmn.FileExists(rootDir + "_bak") {
  247. if err := os.RemoveAll(rootDir + "_bak"); err != nil {
  248. cmn.PanicSanity(err.Error())
  249. }
  250. }
  251. // Move ~/.tendermint_test to ~/.tendermint_test_bak
  252. if cmn.FileExists(rootDir) {
  253. if err := os.Rename(rootDir, rootDir+"_bak"); err != nil {
  254. cmn.PanicSanity(err.Error())
  255. }
  256. }
  257. // Create new dir
  258. if err := cmn.EnsureDir(rootDir, 0700); err != nil {
  259. cmn.PanicSanity(err.Error())
  260. }
  261. if err := cmn.EnsureDir(filepath.Join(rootDir, defaultConfigDir), 0700); err != nil {
  262. cmn.PanicSanity(err.Error())
  263. }
  264. if err := cmn.EnsureDir(filepath.Join(rootDir, defaultDataDir), 0700); err != nil {
  265. cmn.PanicSanity(err.Error())
  266. }
  267. baseConfig := DefaultBaseConfig()
  268. configFilePath := filepath.Join(rootDir, defaultConfigFilePath)
  269. genesisFilePath := filepath.Join(rootDir, baseConfig.Genesis)
  270. privKeyFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorKey)
  271. privStateFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorState)
  272. // Write default config file if missing.
  273. if !cmn.FileExists(configFilePath) {
  274. writeDefaultConfigFile(configFilePath)
  275. }
  276. if !cmn.FileExists(genesisFilePath) {
  277. if chainID == "" {
  278. chainID = "tendermint_test"
  279. }
  280. testGenesis := fmt.Sprintf(testGenesisFmt, chainID)
  281. cmn.MustWriteFile(genesisFilePath, []byte(testGenesis), 0644)
  282. }
  283. // we always overwrite the priv val
  284. cmn.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0644)
  285. cmn.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0644)
  286. config := TestConfig().SetRoot(rootDir)
  287. return config
  288. }
  289. var testGenesisFmt = `{
  290. "genesis_time": "2018-10-10T08:20:13.695936996Z",
  291. "chain_id": "%s",
  292. "validators": [
  293. {
  294. "pub_key": {
  295. "type": "tendermint/PubKeyEd25519",
  296. "value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="
  297. },
  298. "power": "10",
  299. "name": ""
  300. }
  301. ],
  302. "app_hash": ""
  303. }`
  304. var testPrivValidatorKey = `{
  305. "address": "A3258DCBF45DCA0DF052981870F2D1441A36D145",
  306. "pub_key": {
  307. "type": "tendermint/PubKeyEd25519",
  308. "value": "AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="
  309. },
  310. "priv_key": {
  311. "type": "tendermint/PrivKeyEd25519",
  312. "value": "EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ=="
  313. }
  314. }`
  315. var testPrivValidatorState = `{
  316. "height": "0",
  317. "round": "0",
  318. "step": 0
  319. }`