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.

403 lines
14 KiB

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