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.

860 lines
29 KiB

  1. package config
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "github.com/pkg/errors"
  8. )
  9. const (
  10. // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep
  11. FuzzModeDrop = iota
  12. // FuzzModeDelay is a mode in which we randomly sleep
  13. FuzzModeDelay
  14. // LogFormatPlain is a format for colored text
  15. LogFormatPlain = "plain"
  16. // LogFormatJSON is a format for json output
  17. LogFormatJSON = "json"
  18. )
  19. // NOTE: Most of the structs & relevant comments + the
  20. // default configuration options were used to manually
  21. // generate the config.toml. Please reflect any changes
  22. // made here in the defaultConfigTemplate constant in
  23. // config/toml.go
  24. // NOTE: libs/cli must know to look in the config dir!
  25. var (
  26. DefaultTendermintDir = ".tendermint"
  27. defaultConfigDir = "config"
  28. defaultDataDir = "data"
  29. defaultConfigFileName = "config.toml"
  30. defaultGenesisJSONName = "genesis.json"
  31. defaultPrivValKeyName = "priv_validator_key.json"
  32. defaultPrivValStateName = "priv_validator_state.json"
  33. defaultNodeKeyName = "node_key.json"
  34. defaultAddrBookName = "addrbook.json"
  35. defaultConfigFilePath = filepath.Join(defaultConfigDir, defaultConfigFileName)
  36. defaultGenesisJSONPath = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
  37. defaultPrivValKeyPath = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
  38. defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
  39. defaultNodeKeyPath = filepath.Join(defaultConfigDir, defaultNodeKeyName)
  40. defaultAddrBookPath = filepath.Join(defaultConfigDir, defaultAddrBookName)
  41. )
  42. var (
  43. oldPrivVal = "priv_validator.json"
  44. oldPrivValPath = filepath.Join(defaultConfigDir, oldPrivVal)
  45. )
  46. // Config defines the top level configuration for a Tendermint node
  47. type Config struct {
  48. // Top level options use an anonymous struct
  49. BaseConfig `mapstructure:",squash"`
  50. // Options for services
  51. RPC *RPCConfig `mapstructure:"rpc"`
  52. P2P *P2PConfig `mapstructure:"p2p"`
  53. Mempool *MempoolConfig `mapstructure:"mempool"`
  54. Consensus *ConsensusConfig `mapstructure:"consensus"`
  55. TxIndex *TxIndexConfig `mapstructure:"tx_index"`
  56. Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
  57. }
  58. // DefaultConfig returns a default configuration for a Tendermint node
  59. func DefaultConfig() *Config {
  60. return &Config{
  61. BaseConfig: DefaultBaseConfig(),
  62. RPC: DefaultRPCConfig(),
  63. P2P: DefaultP2PConfig(),
  64. Mempool: DefaultMempoolConfig(),
  65. Consensus: DefaultConsensusConfig(),
  66. TxIndex: DefaultTxIndexConfig(),
  67. Instrumentation: DefaultInstrumentationConfig(),
  68. }
  69. }
  70. // TestConfig returns a configuration that can be used for testing
  71. func TestConfig() *Config {
  72. return &Config{
  73. BaseConfig: TestBaseConfig(),
  74. RPC: TestRPCConfig(),
  75. P2P: TestP2PConfig(),
  76. Mempool: TestMempoolConfig(),
  77. Consensus: TestConsensusConfig(),
  78. TxIndex: TestTxIndexConfig(),
  79. Instrumentation: TestInstrumentationConfig(),
  80. }
  81. }
  82. // SetRoot sets the RootDir for all Config structs
  83. func (cfg *Config) SetRoot(root string) *Config {
  84. cfg.BaseConfig.RootDir = root
  85. cfg.RPC.RootDir = root
  86. cfg.P2P.RootDir = root
  87. cfg.Mempool.RootDir = root
  88. cfg.Consensus.RootDir = root
  89. return cfg
  90. }
  91. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  92. // returns an error if any check fails.
  93. func (cfg *Config) ValidateBasic() error {
  94. if err := cfg.BaseConfig.ValidateBasic(); err != nil {
  95. return err
  96. }
  97. if err := cfg.RPC.ValidateBasic(); err != nil {
  98. return errors.Wrap(err, "Error in [rpc] section")
  99. }
  100. if err := cfg.P2P.ValidateBasic(); err != nil {
  101. return errors.Wrap(err, "Error in [p2p] section")
  102. }
  103. if err := cfg.Mempool.ValidateBasic(); err != nil {
  104. return errors.Wrap(err, "Error in [mempool] section")
  105. }
  106. if err := cfg.Consensus.ValidateBasic(); err != nil {
  107. return errors.Wrap(err, "Error in [consensus] section")
  108. }
  109. return errors.Wrap(
  110. cfg.Instrumentation.ValidateBasic(),
  111. "Error in [instrumentation] section",
  112. )
  113. }
  114. //-----------------------------------------------------------------------------
  115. // BaseConfig
  116. // BaseConfig defines the base configuration for a Tendermint node
  117. type BaseConfig struct {
  118. // chainID is unexposed and immutable but here for convenience
  119. chainID string
  120. // The root directory for all data.
  121. // This should be set in viper so it can unmarshal into this struct
  122. RootDir string `mapstructure:"home"`
  123. // TCP or UNIX socket address of the ABCI application,
  124. // or the name of an ABCI application compiled in with the Tendermint binary
  125. ProxyApp string `mapstructure:"proxy_app"`
  126. // A custom human readable name for this node
  127. Moniker string `mapstructure:"moniker"`
  128. // If this node is many blocks behind the tip of the chain, FastSync
  129. // allows them to catchup quickly by downloading blocks in parallel
  130. // and verifying their commits
  131. FastSync bool `mapstructure:"fast_sync"`
  132. // Database backend: leveldb | memdb | cleveldb
  133. DBBackend string `mapstructure:"db_backend"`
  134. // Database directory
  135. DBPath string `mapstructure:"db_dir"`
  136. // Output level for logging
  137. LogLevel string `mapstructure:"log_level"`
  138. // Output format: 'plain' (colored text) or 'json'
  139. LogFormat string `mapstructure:"log_format"`
  140. // Path to the JSON file containing the initial validator set and other meta data
  141. Genesis string `mapstructure:"genesis_file"`
  142. // Path to the JSON file containing the private key to use as a validator in the consensus protocol
  143. PrivValidatorKey string `mapstructure:"priv_validator_key_file"`
  144. // Path to the JSON file containing the last sign state of a validator
  145. PrivValidatorState string `mapstructure:"priv_validator_state_file"`
  146. // TCP or UNIX socket address for Tendermint to listen on for
  147. // connections from an external PrivValidator process
  148. PrivValidatorListenAddr string `mapstructure:"priv_validator_laddr"`
  149. // A JSON file containing the private key to use for p2p authenticated encryption
  150. NodeKey string `mapstructure:"node_key_file"`
  151. // Mechanism to connect to the ABCI application: socket | grpc
  152. ABCI string `mapstructure:"abci"`
  153. // TCP or UNIX socket address for the profiling server to listen on
  154. ProfListenAddress string `mapstructure:"prof_laddr"`
  155. // If true, query the ABCI app on connecting to a new peer
  156. // so the app can decide if we should keep the connection or not
  157. FilterPeers bool `mapstructure:"filter_peers"` // false
  158. }
  159. // DefaultBaseConfig returns a default base configuration for a Tendermint node
  160. func DefaultBaseConfig() BaseConfig {
  161. return BaseConfig{
  162. Genesis: defaultGenesisJSONPath,
  163. PrivValidatorKey: defaultPrivValKeyPath,
  164. PrivValidatorState: defaultPrivValStatePath,
  165. NodeKey: defaultNodeKeyPath,
  166. Moniker: defaultMoniker,
  167. ProxyApp: "tcp://127.0.0.1:26658",
  168. ABCI: "socket",
  169. LogLevel: DefaultPackageLogLevels(),
  170. LogFormat: LogFormatPlain,
  171. ProfListenAddress: "",
  172. FastSync: true,
  173. FilterPeers: false,
  174. DBBackend: "leveldb",
  175. DBPath: "data",
  176. }
  177. }
  178. // TestBaseConfig returns a base configuration for testing a Tendermint node
  179. func TestBaseConfig() BaseConfig {
  180. cfg := DefaultBaseConfig()
  181. cfg.chainID = "tendermint_test"
  182. cfg.ProxyApp = "kvstore"
  183. cfg.FastSync = false
  184. cfg.DBBackend = "memdb"
  185. return cfg
  186. }
  187. func (cfg BaseConfig) ChainID() string {
  188. return cfg.chainID
  189. }
  190. // GenesisFile returns the full path to the genesis.json file
  191. func (cfg BaseConfig) GenesisFile() string {
  192. return rootify(cfg.Genesis, cfg.RootDir)
  193. }
  194. // PrivValidatorKeyFile returns the full path to the priv_validator_key.json file
  195. func (cfg BaseConfig) PrivValidatorKeyFile() string {
  196. return rootify(cfg.PrivValidatorKey, cfg.RootDir)
  197. }
  198. // PrivValidatorFile returns the full path to the priv_validator_state.json file
  199. func (cfg BaseConfig) PrivValidatorStateFile() string {
  200. return rootify(cfg.PrivValidatorState, cfg.RootDir)
  201. }
  202. // OldPrivValidatorFile returns the full path of the priv_validator.json from pre v0.28.0.
  203. // TODO: eventually remove.
  204. func (cfg BaseConfig) OldPrivValidatorFile() string {
  205. return rootify(oldPrivValPath, cfg.RootDir)
  206. }
  207. // NodeKeyFile returns the full path to the node_key.json file
  208. func (cfg BaseConfig) NodeKeyFile() string {
  209. return rootify(cfg.NodeKey, cfg.RootDir)
  210. }
  211. // DBDir returns the full path to the database directory
  212. func (cfg BaseConfig) DBDir() string {
  213. return rootify(cfg.DBPath, cfg.RootDir)
  214. }
  215. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  216. // returns an error if any check fails.
  217. func (cfg BaseConfig) ValidateBasic() error {
  218. switch cfg.LogFormat {
  219. case LogFormatPlain, LogFormatJSON:
  220. default:
  221. return errors.New("unknown log_format (must be 'plain' or 'json')")
  222. }
  223. return nil
  224. }
  225. // DefaultLogLevel returns a default log level of "error"
  226. func DefaultLogLevel() string {
  227. return "error"
  228. }
  229. // DefaultPackageLogLevels returns a default log level setting so all packages
  230. // log at "error", while the `state` and `main` packages log at "info"
  231. func DefaultPackageLogLevels() string {
  232. return fmt.Sprintf("main:info,state:info,*:%s", DefaultLogLevel())
  233. }
  234. //-----------------------------------------------------------------------------
  235. // RPCConfig
  236. // RPCConfig defines the configuration options for the Tendermint RPC server
  237. type RPCConfig struct {
  238. RootDir string `mapstructure:"home"`
  239. // TCP or UNIX socket address for the RPC server to listen on
  240. ListenAddress string `mapstructure:"laddr"`
  241. // A list of origins a cross-domain request can be executed from.
  242. // If the special '*' value is present in the list, all origins will be allowed.
  243. // An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com).
  244. // Only one wildcard can be used per origin.
  245. CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"`
  246. // A list of methods the client is allowed to use with cross-domain requests.
  247. CORSAllowedMethods []string `mapstructure:"cors_allowed_methods"`
  248. // A list of non simple headers the client is allowed to use with cross-domain requests.
  249. CORSAllowedHeaders []string `mapstructure:"cors_allowed_headers"`
  250. // TCP or UNIX socket address for the gRPC server to listen on
  251. // NOTE: This server only supports /broadcast_tx_commit
  252. GRPCListenAddress string `mapstructure:"grpc_laddr"`
  253. // Maximum number of simultaneous connections.
  254. // Does not include RPC (HTTP&WebSocket) connections. See max_open_connections
  255. // If you want to accept a larger number than the default, make sure
  256. // you increase your OS limits.
  257. // 0 - unlimited.
  258. GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"`
  259. // Activate unsafe RPC commands like /dial_persistent_peers and /unsafe_flush_mempool
  260. Unsafe bool `mapstructure:"unsafe"`
  261. // Maximum number of simultaneous connections (including WebSocket).
  262. // Does not include gRPC connections. See grpc_max_open_connections
  263. // If you want to accept a larger number than the default, make sure
  264. // you increase your OS limits.
  265. // 0 - unlimited.
  266. // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  267. // 1024 - 40 - 10 - 50 = 924 = ~900
  268. MaxOpenConnections int `mapstructure:"max_open_connections"`
  269. }
  270. // DefaultRPCConfig returns a default configuration for the RPC server
  271. func DefaultRPCConfig() *RPCConfig {
  272. return &RPCConfig{
  273. ListenAddress: "tcp://0.0.0.0:26657",
  274. CORSAllowedOrigins: []string{},
  275. CORSAllowedMethods: []string{"HEAD", "GET", "POST"},
  276. CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
  277. GRPCListenAddress: "",
  278. GRPCMaxOpenConnections: 900,
  279. Unsafe: false,
  280. MaxOpenConnections: 900,
  281. }
  282. }
  283. // TestRPCConfig returns a configuration for testing the RPC server
  284. func TestRPCConfig() *RPCConfig {
  285. cfg := DefaultRPCConfig()
  286. cfg.ListenAddress = "tcp://0.0.0.0:36657"
  287. cfg.GRPCListenAddress = "tcp://0.0.0.0:36658"
  288. cfg.Unsafe = true
  289. return cfg
  290. }
  291. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  292. // returns an error if any check fails.
  293. func (cfg *RPCConfig) ValidateBasic() error {
  294. if cfg.GRPCMaxOpenConnections < 0 {
  295. return errors.New("grpc_max_open_connections can't be negative")
  296. }
  297. if cfg.MaxOpenConnections < 0 {
  298. return errors.New("max_open_connections can't be negative")
  299. }
  300. return nil
  301. }
  302. // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
  303. func (cfg *RPCConfig) IsCorsEnabled() bool {
  304. return len(cfg.CORSAllowedOrigins) != 0
  305. }
  306. //-----------------------------------------------------------------------------
  307. // P2PConfig
  308. // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
  309. type P2PConfig struct {
  310. RootDir string `mapstructure:"home"`
  311. // Address to listen for incoming connections
  312. ListenAddress string `mapstructure:"laddr"`
  313. // Address to advertise to peers for them to dial
  314. ExternalAddress string `mapstructure:"external_address"`
  315. // Comma separated list of seed nodes to connect to
  316. // We only use these if we can’t connect to peers in the addrbook
  317. Seeds string `mapstructure:"seeds"`
  318. // Comma separated list of nodes to keep persistent connections to
  319. PersistentPeers string `mapstructure:"persistent_peers"`
  320. // UPNP port forwarding
  321. UPNP bool `mapstructure:"upnp"`
  322. // Path to address book
  323. AddrBook string `mapstructure:"addr_book_file"`
  324. // Set true for strict address routability rules
  325. // Set false for private or local networks
  326. AddrBookStrict bool `mapstructure:"addr_book_strict"`
  327. // Maximum number of inbound peers
  328. MaxNumInboundPeers int `mapstructure:"max_num_inbound_peers"`
  329. // Maximum number of outbound peers to connect to, excluding persistent peers
  330. MaxNumOutboundPeers int `mapstructure:"max_num_outbound_peers"`
  331. // Time to wait before flushing messages out on the connection
  332. FlushThrottleTimeout time.Duration `mapstructure:"flush_throttle_timeout"`
  333. // Maximum size of a message packet payload, in bytes
  334. MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
  335. // Rate at which packets can be sent, in bytes/second
  336. SendRate int64 `mapstructure:"send_rate"`
  337. // Rate at which packets can be received, in bytes/second
  338. RecvRate int64 `mapstructure:"recv_rate"`
  339. // Set true to enable the peer-exchange reactor
  340. PexReactor bool `mapstructure:"pex"`
  341. // Seed mode, in which node constantly crawls the network and looks for
  342. // peers. If another node asks it for addresses, it responds and disconnects.
  343. //
  344. // Does not work if the peer-exchange reactor is disabled.
  345. SeedMode bool `mapstructure:"seed_mode"`
  346. // Comma separated list of peer IDs to keep private (will not be gossiped to
  347. // other peers)
  348. PrivatePeerIDs string `mapstructure:"private_peer_ids"`
  349. // Toggle to disable guard against peers connecting from the same ip.
  350. AllowDuplicateIP bool `mapstructure:"allow_duplicate_ip"`
  351. // Peer connection configuration.
  352. HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
  353. DialTimeout time.Duration `mapstructure:"dial_timeout"`
  354. // Testing params.
  355. // Force dial to fail
  356. TestDialFail bool `mapstructure:"test_dial_fail"`
  357. // FUzz connection
  358. TestFuzz bool `mapstructure:"test_fuzz"`
  359. TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"`
  360. }
  361. // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
  362. func DefaultP2PConfig() *P2PConfig {
  363. return &P2PConfig{
  364. ListenAddress: "tcp://0.0.0.0:26656",
  365. ExternalAddress: "",
  366. UPNP: false,
  367. AddrBook: defaultAddrBookPath,
  368. AddrBookStrict: true,
  369. MaxNumInboundPeers: 40,
  370. MaxNumOutboundPeers: 10,
  371. FlushThrottleTimeout: 100 * time.Millisecond,
  372. MaxPacketMsgPayloadSize: 1024, // 1 kB
  373. SendRate: 5120000, // 5 mB/s
  374. RecvRate: 5120000, // 5 mB/s
  375. PexReactor: true,
  376. SeedMode: false,
  377. AllowDuplicateIP: false,
  378. HandshakeTimeout: 20 * time.Second,
  379. DialTimeout: 3 * time.Second,
  380. TestDialFail: false,
  381. TestFuzz: false,
  382. TestFuzzConfig: DefaultFuzzConnConfig(),
  383. }
  384. }
  385. // TestP2PConfig returns a configuration for testing the peer-to-peer layer
  386. func TestP2PConfig() *P2PConfig {
  387. cfg := DefaultP2PConfig()
  388. cfg.ListenAddress = "tcp://0.0.0.0:36656"
  389. cfg.FlushThrottleTimeout = 10 * time.Millisecond
  390. cfg.AllowDuplicateIP = true
  391. return cfg
  392. }
  393. // AddrBookFile returns the full path to the address book
  394. func (cfg *P2PConfig) AddrBookFile() string {
  395. return rootify(cfg.AddrBook, cfg.RootDir)
  396. }
  397. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  398. // returns an error if any check fails.
  399. func (cfg *P2PConfig) ValidateBasic() error {
  400. if cfg.MaxNumInboundPeers < 0 {
  401. return errors.New("max_num_inbound_peers can't be negative")
  402. }
  403. if cfg.MaxNumOutboundPeers < 0 {
  404. return errors.New("max_num_outbound_peers can't be negative")
  405. }
  406. if cfg.FlushThrottleTimeout < 0 {
  407. return errors.New("flush_throttle_timeout can't be negative")
  408. }
  409. if cfg.MaxPacketMsgPayloadSize < 0 {
  410. return errors.New("max_packet_msg_payload_size can't be negative")
  411. }
  412. if cfg.SendRate < 0 {
  413. return errors.New("send_rate can't be negative")
  414. }
  415. if cfg.RecvRate < 0 {
  416. return errors.New("recv_rate can't be negative")
  417. }
  418. return nil
  419. }
  420. // FuzzConnConfig is a FuzzedConnection configuration.
  421. type FuzzConnConfig struct {
  422. Mode int
  423. MaxDelay time.Duration
  424. ProbDropRW float64
  425. ProbDropConn float64
  426. ProbSleep float64
  427. }
  428. // DefaultFuzzConnConfig returns the default config.
  429. func DefaultFuzzConnConfig() *FuzzConnConfig {
  430. return &FuzzConnConfig{
  431. Mode: FuzzModeDrop,
  432. MaxDelay: 3 * time.Second,
  433. ProbDropRW: 0.2,
  434. ProbDropConn: 0.00,
  435. ProbSleep: 0.00,
  436. }
  437. }
  438. //-----------------------------------------------------------------------------
  439. // MempoolConfig
  440. // MempoolConfig defines the configuration options for the Tendermint mempool
  441. type MempoolConfig struct {
  442. RootDir string `mapstructure:"home"`
  443. Recheck bool `mapstructure:"recheck"`
  444. Broadcast bool `mapstructure:"broadcast"`
  445. WalPath string `mapstructure:"wal_dir"`
  446. Size int `mapstructure:"size"`
  447. CacheSize int `mapstructure:"cache_size"`
  448. }
  449. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool
  450. func DefaultMempoolConfig() *MempoolConfig {
  451. return &MempoolConfig{
  452. Recheck: true,
  453. Broadcast: true,
  454. WalPath: "",
  455. // Each signature verification takes .5ms, size reduced until we implement
  456. // ABCI Recheck
  457. Size: 5000,
  458. CacheSize: 10000,
  459. }
  460. }
  461. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  462. func TestMempoolConfig() *MempoolConfig {
  463. cfg := DefaultMempoolConfig()
  464. cfg.CacheSize = 1000
  465. return cfg
  466. }
  467. // WalDir returns the full path to the mempool's write-ahead log
  468. func (cfg *MempoolConfig) WalDir() string {
  469. return rootify(cfg.WalPath, cfg.RootDir)
  470. }
  471. // WalEnabled returns true if the WAL is enabled.
  472. func (cfg *MempoolConfig) WalEnabled() bool {
  473. return cfg.WalPath != ""
  474. }
  475. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  476. // returns an error if any check fails.
  477. func (cfg *MempoolConfig) ValidateBasic() error {
  478. if cfg.Size < 0 {
  479. return errors.New("size can't be negative")
  480. }
  481. if cfg.CacheSize < 0 {
  482. return errors.New("cache_size can't be negative")
  483. }
  484. return nil
  485. }
  486. //-----------------------------------------------------------------------------
  487. // ConsensusConfig
  488. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  489. // including timeouts and details about the WAL and the block structure.
  490. type ConsensusConfig struct {
  491. RootDir string `mapstructure:"home"`
  492. WalPath string `mapstructure:"wal_file"`
  493. walFile string // overrides WalPath if set
  494. TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
  495. TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
  496. TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
  497. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
  498. TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
  499. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
  500. TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
  501. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  502. SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
  503. // EmptyBlocks mode and possible interval between empty blocks
  504. CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"`
  505. CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
  506. // Reactor sleep duration parameters
  507. PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"`
  508. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
  509. // Block time parameters. Corresponds to the minimum time increment between consecutive blocks.
  510. BlockTimeIota time.Duration `mapstructure:"blocktime_iota"`
  511. }
  512. // DefaultConsensusConfig returns a default configuration for the consensus service
  513. func DefaultConsensusConfig() *ConsensusConfig {
  514. return &ConsensusConfig{
  515. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  516. TimeoutPropose: 3000 * time.Millisecond,
  517. TimeoutProposeDelta: 500 * time.Millisecond,
  518. TimeoutPrevote: 1000 * time.Millisecond,
  519. TimeoutPrevoteDelta: 500 * time.Millisecond,
  520. TimeoutPrecommit: 1000 * time.Millisecond,
  521. TimeoutPrecommitDelta: 500 * time.Millisecond,
  522. TimeoutCommit: 1000 * time.Millisecond,
  523. SkipTimeoutCommit: false,
  524. CreateEmptyBlocks: true,
  525. CreateEmptyBlocksInterval: 0 * time.Second,
  526. PeerGossipSleepDuration: 100 * time.Millisecond,
  527. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  528. BlockTimeIota: 1000 * time.Millisecond,
  529. }
  530. }
  531. // TestConsensusConfig returns a configuration for testing the consensus service
  532. func TestConsensusConfig() *ConsensusConfig {
  533. cfg := DefaultConsensusConfig()
  534. cfg.TimeoutPropose = 40 * time.Millisecond
  535. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  536. cfg.TimeoutPrevote = 10 * time.Millisecond
  537. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  538. cfg.TimeoutPrecommit = 10 * time.Millisecond
  539. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  540. cfg.TimeoutCommit = 10 * time.Millisecond
  541. cfg.SkipTimeoutCommit = true
  542. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  543. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  544. cfg.BlockTimeIota = 10 * time.Millisecond
  545. return cfg
  546. }
  547. // MinValidVoteTime returns the minimum acceptable block time.
  548. // See the [BFT time spec](https://godoc.org/github.com/tendermint/tendermint/docs/spec/consensus/bft-time.md).
  549. func (cfg *ConsensusConfig) MinValidVoteTime(lastBlockTime time.Time) time.Time {
  550. return lastBlockTime.Add(cfg.BlockTimeIota)
  551. }
  552. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  553. func (cfg *ConsensusConfig) WaitForTxs() bool {
  554. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  555. }
  556. // Propose returns the amount of time to wait for a proposal
  557. func (cfg *ConsensusConfig) Propose(round int) time.Duration {
  558. return time.Duration(
  559. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  560. ) * time.Nanosecond
  561. }
  562. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  563. func (cfg *ConsensusConfig) Prevote(round int) time.Duration {
  564. return time.Duration(
  565. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  566. ) * time.Nanosecond
  567. }
  568. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  569. func (cfg *ConsensusConfig) Precommit(round int) time.Duration {
  570. return time.Duration(
  571. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  572. ) * time.Nanosecond
  573. }
  574. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits for a single block (ie. a commit).
  575. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  576. return t.Add(cfg.TimeoutCommit)
  577. }
  578. // WalFile returns the full path to the write-ahead log file
  579. func (cfg *ConsensusConfig) WalFile() string {
  580. if cfg.walFile != "" {
  581. return cfg.walFile
  582. }
  583. return rootify(cfg.WalPath, cfg.RootDir)
  584. }
  585. // SetWalFile sets the path to the write-ahead log file
  586. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  587. cfg.walFile = walFile
  588. }
  589. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  590. // returns an error if any check fails.
  591. func (cfg *ConsensusConfig) ValidateBasic() error {
  592. if cfg.TimeoutPropose < 0 {
  593. return errors.New("timeout_propose can't be negative")
  594. }
  595. if cfg.TimeoutProposeDelta < 0 {
  596. return errors.New("timeout_propose_delta can't be negative")
  597. }
  598. if cfg.TimeoutPrevote < 0 {
  599. return errors.New("timeout_prevote can't be negative")
  600. }
  601. if cfg.TimeoutPrevoteDelta < 0 {
  602. return errors.New("timeout_prevote_delta can't be negative")
  603. }
  604. if cfg.TimeoutPrecommit < 0 {
  605. return errors.New("timeout_precommit can't be negative")
  606. }
  607. if cfg.TimeoutPrecommitDelta < 0 {
  608. return errors.New("timeout_precommit_delta can't be negative")
  609. }
  610. if cfg.TimeoutCommit < 0 {
  611. return errors.New("timeout_commit can't be negative")
  612. }
  613. if cfg.CreateEmptyBlocksInterval < 0 {
  614. return errors.New("create_empty_blocks_interval can't be negative")
  615. }
  616. if cfg.PeerGossipSleepDuration < 0 {
  617. return errors.New("peer_gossip_sleep_duration can't be negative")
  618. }
  619. if cfg.PeerQueryMaj23SleepDuration < 0 {
  620. return errors.New("peer_query_maj23_sleep_duration can't be negative")
  621. }
  622. if cfg.BlockTimeIota < 0 {
  623. return errors.New("blocktime_iota can't be negative")
  624. }
  625. return nil
  626. }
  627. //-----------------------------------------------------------------------------
  628. // TxIndexConfig
  629. // TxIndexConfig defines the configuration for the transaction indexer,
  630. // including tags to index.
  631. type TxIndexConfig struct {
  632. // What indexer to use for transactions
  633. //
  634. // Options:
  635. // 1) "null"
  636. // 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend).
  637. Indexer string `mapstructure:"indexer"`
  638. // Comma-separated list of tags to index (by default the only tag is "tx.hash")
  639. //
  640. // You can also index transactions by height by adding "tx.height" tag here.
  641. //
  642. // It's recommended to index only a subset of tags due to possible memory
  643. // bloat. This is, of course, depends on the indexer's DB and the volume of
  644. // transactions.
  645. IndexTags string `mapstructure:"index_tags"`
  646. // When set to true, tells indexer to index all tags (predefined tags:
  647. // "tx.hash", "tx.height" and all tags from DeliverTx responses).
  648. //
  649. // Note this may be not desirable (see the comment above). IndexTags has a
  650. // precedence over IndexAllTags (i.e. when given both, IndexTags will be
  651. // indexed).
  652. IndexAllTags bool `mapstructure:"index_all_tags"`
  653. }
  654. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  655. func DefaultTxIndexConfig() *TxIndexConfig {
  656. return &TxIndexConfig{
  657. Indexer: "kv",
  658. IndexTags: "",
  659. IndexAllTags: false,
  660. }
  661. }
  662. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  663. func TestTxIndexConfig() *TxIndexConfig {
  664. return DefaultTxIndexConfig()
  665. }
  666. //-----------------------------------------------------------------------------
  667. // InstrumentationConfig
  668. // InstrumentationConfig defines the configuration for metrics reporting.
  669. type InstrumentationConfig struct {
  670. // When true, Prometheus metrics are served under /metrics on
  671. // PrometheusListenAddr.
  672. // Check out the documentation for the list of available metrics.
  673. Prometheus bool `mapstructure:"prometheus"`
  674. // Address to listen for Prometheus collector(s) connections.
  675. PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"`
  676. // Maximum number of simultaneous connections.
  677. // If you want to accept a larger number than the default, make sure
  678. // you increase your OS limits.
  679. // 0 - unlimited.
  680. MaxOpenConnections int `mapstructure:"max_open_connections"`
  681. // Instrumentation namespace.
  682. Namespace string `mapstructure:"namespace"`
  683. }
  684. // DefaultInstrumentationConfig returns a default configuration for metrics
  685. // reporting.
  686. func DefaultInstrumentationConfig() *InstrumentationConfig {
  687. return &InstrumentationConfig{
  688. Prometheus: false,
  689. PrometheusListenAddr: ":26660",
  690. MaxOpenConnections: 3,
  691. Namespace: "tendermint",
  692. }
  693. }
  694. // TestInstrumentationConfig returns a default configuration for metrics
  695. // reporting.
  696. func TestInstrumentationConfig() *InstrumentationConfig {
  697. return DefaultInstrumentationConfig()
  698. }
  699. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  700. // returns an error if any check fails.
  701. func (cfg *InstrumentationConfig) ValidateBasic() error {
  702. if cfg.MaxOpenConnections < 0 {
  703. return errors.New("max_open_connections can't be negative")
  704. }
  705. return nil
  706. }
  707. //-----------------------------------------------------------------------------
  708. // Utils
  709. // helper function to make config creation independent of root dir
  710. func rootify(path, root string) string {
  711. if filepath.IsAbs(path) {
  712. return path
  713. }
  714. return filepath.Join(root, path)
  715. }
  716. //-----------------------------------------------------------------------------
  717. // Moniker
  718. var defaultMoniker = getDefaultMoniker()
  719. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  720. // fails to get the host name, "anonymous" will be returned.
  721. func getDefaultMoniker() string {
  722. moniker, err := os.Hostname()
  723. if err != nil {
  724. moniker = "anonymous"
  725. }
  726. return moniker
  727. }