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.

398 lines
13 KiB

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