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.

865 lines
30 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. MaxTxsBytes int64 `mapstructure:"max_txs_bytes"`
  448. CacheSize int `mapstructure:"cache_size"`
  449. }
  450. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool
  451. func DefaultMempoolConfig() *MempoolConfig {
  452. return &MempoolConfig{
  453. Recheck: true,
  454. Broadcast: true,
  455. WalPath: "",
  456. // Each signature verification takes .5ms, Size reduced until we implement
  457. // ABCI Recheck
  458. Size: 5000,
  459. MaxTxsBytes: 1024 * 1024 * 1024, // 1GB
  460. CacheSize: 10000,
  461. }
  462. }
  463. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  464. func TestMempoolConfig() *MempoolConfig {
  465. cfg := DefaultMempoolConfig()
  466. cfg.CacheSize = 1000
  467. return cfg
  468. }
  469. // WalDir returns the full path to the mempool's write-ahead log
  470. func (cfg *MempoolConfig) WalDir() string {
  471. return rootify(cfg.WalPath, cfg.RootDir)
  472. }
  473. // WalEnabled returns true if the WAL is enabled.
  474. func (cfg *MempoolConfig) WalEnabled() bool {
  475. return cfg.WalPath != ""
  476. }
  477. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  478. // returns an error if any check fails.
  479. func (cfg *MempoolConfig) ValidateBasic() error {
  480. if cfg.Size < 0 {
  481. return errors.New("size can't be negative")
  482. }
  483. if cfg.MaxTxsBytes < 0 {
  484. return errors.New("max_txs_bytes can't be negative")
  485. }
  486. if cfg.CacheSize < 0 {
  487. return errors.New("cache_size can't be negative")
  488. }
  489. return nil
  490. }
  491. //-----------------------------------------------------------------------------
  492. // ConsensusConfig
  493. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  494. // including timeouts and details about the WAL and the block structure.
  495. type ConsensusConfig struct {
  496. RootDir string `mapstructure:"home"`
  497. WalPath string `mapstructure:"wal_file"`
  498. walFile string // overrides WalPath if set
  499. TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
  500. TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
  501. TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
  502. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
  503. TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
  504. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
  505. TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
  506. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  507. SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
  508. // EmptyBlocks mode and possible interval between empty blocks
  509. CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"`
  510. CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
  511. // Reactor sleep duration parameters
  512. PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"`
  513. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
  514. // Block time parameters. Corresponds to the minimum time increment between consecutive blocks.
  515. BlockTimeIota time.Duration `mapstructure:"blocktime_iota"`
  516. }
  517. // DefaultConsensusConfig returns a default configuration for the consensus service
  518. func DefaultConsensusConfig() *ConsensusConfig {
  519. return &ConsensusConfig{
  520. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  521. TimeoutPropose: 3000 * time.Millisecond,
  522. TimeoutProposeDelta: 500 * time.Millisecond,
  523. TimeoutPrevote: 1000 * time.Millisecond,
  524. TimeoutPrevoteDelta: 500 * time.Millisecond,
  525. TimeoutPrecommit: 1000 * time.Millisecond,
  526. TimeoutPrecommitDelta: 500 * time.Millisecond,
  527. TimeoutCommit: 1000 * time.Millisecond,
  528. SkipTimeoutCommit: false,
  529. CreateEmptyBlocks: true,
  530. CreateEmptyBlocksInterval: 0 * time.Second,
  531. PeerGossipSleepDuration: 100 * time.Millisecond,
  532. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  533. BlockTimeIota: 1000 * time.Millisecond,
  534. }
  535. }
  536. // TestConsensusConfig returns a configuration for testing the consensus service
  537. func TestConsensusConfig() *ConsensusConfig {
  538. cfg := DefaultConsensusConfig()
  539. cfg.TimeoutPropose = 40 * time.Millisecond
  540. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  541. cfg.TimeoutPrevote = 10 * time.Millisecond
  542. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  543. cfg.TimeoutPrecommit = 10 * time.Millisecond
  544. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  545. cfg.TimeoutCommit = 10 * time.Millisecond
  546. cfg.SkipTimeoutCommit = true
  547. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  548. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  549. cfg.BlockTimeIota = 10 * time.Millisecond
  550. return cfg
  551. }
  552. // MinValidVoteTime returns the minimum acceptable block time.
  553. // See the [BFT time spec](https://godoc.org/github.com/tendermint/tendermint/docs/spec/consensus/bft-time.md).
  554. func (cfg *ConsensusConfig) MinValidVoteTime(lastBlockTime time.Time) time.Time {
  555. return lastBlockTime.Add(cfg.BlockTimeIota)
  556. }
  557. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  558. func (cfg *ConsensusConfig) WaitForTxs() bool {
  559. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  560. }
  561. // Propose returns the amount of time to wait for a proposal
  562. func (cfg *ConsensusConfig) Propose(round int) time.Duration {
  563. return time.Duration(
  564. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  565. ) * time.Nanosecond
  566. }
  567. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  568. func (cfg *ConsensusConfig) Prevote(round int) time.Duration {
  569. return time.Duration(
  570. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  571. ) * time.Nanosecond
  572. }
  573. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  574. func (cfg *ConsensusConfig) Precommit(round int) time.Duration {
  575. return time.Duration(
  576. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  577. ) * time.Nanosecond
  578. }
  579. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits for a single block (ie. a commit).
  580. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  581. return t.Add(cfg.TimeoutCommit)
  582. }
  583. // WalFile returns the full path to the write-ahead log file
  584. func (cfg *ConsensusConfig) WalFile() string {
  585. if cfg.walFile != "" {
  586. return cfg.walFile
  587. }
  588. return rootify(cfg.WalPath, cfg.RootDir)
  589. }
  590. // SetWalFile sets the path to the write-ahead log file
  591. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  592. cfg.walFile = walFile
  593. }
  594. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  595. // returns an error if any check fails.
  596. func (cfg *ConsensusConfig) ValidateBasic() error {
  597. if cfg.TimeoutPropose < 0 {
  598. return errors.New("timeout_propose can't be negative")
  599. }
  600. if cfg.TimeoutProposeDelta < 0 {
  601. return errors.New("timeout_propose_delta can't be negative")
  602. }
  603. if cfg.TimeoutPrevote < 0 {
  604. return errors.New("timeout_prevote can't be negative")
  605. }
  606. if cfg.TimeoutPrevoteDelta < 0 {
  607. return errors.New("timeout_prevote_delta can't be negative")
  608. }
  609. if cfg.TimeoutPrecommit < 0 {
  610. return errors.New("timeout_precommit can't be negative")
  611. }
  612. if cfg.TimeoutPrecommitDelta < 0 {
  613. return errors.New("timeout_precommit_delta can't be negative")
  614. }
  615. if cfg.TimeoutCommit < 0 {
  616. return errors.New("timeout_commit can't be negative")
  617. }
  618. if cfg.CreateEmptyBlocksInterval < 0 {
  619. return errors.New("create_empty_blocks_interval can't be negative")
  620. }
  621. if cfg.PeerGossipSleepDuration < 0 {
  622. return errors.New("peer_gossip_sleep_duration can't be negative")
  623. }
  624. if cfg.PeerQueryMaj23SleepDuration < 0 {
  625. return errors.New("peer_query_maj23_sleep_duration can't be negative")
  626. }
  627. if cfg.BlockTimeIota < 0 {
  628. return errors.New("blocktime_iota can't be negative")
  629. }
  630. return nil
  631. }
  632. //-----------------------------------------------------------------------------
  633. // TxIndexConfig
  634. // TxIndexConfig defines the configuration for the transaction indexer,
  635. // including tags to index.
  636. type TxIndexConfig struct {
  637. // What indexer to use for transactions
  638. //
  639. // Options:
  640. // 1) "null"
  641. // 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend).
  642. Indexer string `mapstructure:"indexer"`
  643. // Comma-separated list of tags to index (by default the only tag is "tx.hash")
  644. //
  645. // You can also index transactions by height by adding "tx.height" tag here.
  646. //
  647. // It's recommended to index only a subset of tags due to possible memory
  648. // bloat. This is, of course, depends on the indexer's DB and the volume of
  649. // transactions.
  650. IndexTags string `mapstructure:"index_tags"`
  651. // When set to true, tells indexer to index all tags (predefined tags:
  652. // "tx.hash", "tx.height" and all tags from DeliverTx responses).
  653. //
  654. // Note this may be not desirable (see the comment above). IndexTags has a
  655. // precedence over IndexAllTags (i.e. when given both, IndexTags will be
  656. // indexed).
  657. IndexAllTags bool `mapstructure:"index_all_tags"`
  658. }
  659. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  660. func DefaultTxIndexConfig() *TxIndexConfig {
  661. return &TxIndexConfig{
  662. Indexer: "kv",
  663. IndexTags: "",
  664. IndexAllTags: false,
  665. }
  666. }
  667. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  668. func TestTxIndexConfig() *TxIndexConfig {
  669. return DefaultTxIndexConfig()
  670. }
  671. //-----------------------------------------------------------------------------
  672. // InstrumentationConfig
  673. // InstrumentationConfig defines the configuration for metrics reporting.
  674. type InstrumentationConfig struct {
  675. // When true, Prometheus metrics are served under /metrics on
  676. // PrometheusListenAddr.
  677. // Check out the documentation for the list of available metrics.
  678. Prometheus bool `mapstructure:"prometheus"`
  679. // Address to listen for Prometheus collector(s) connections.
  680. PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"`
  681. // Maximum number of simultaneous connections.
  682. // If you want to accept a larger number than the default, make sure
  683. // you increase your OS limits.
  684. // 0 - unlimited.
  685. MaxOpenConnections int `mapstructure:"max_open_connections"`
  686. // Instrumentation namespace.
  687. Namespace string `mapstructure:"namespace"`
  688. }
  689. // DefaultInstrumentationConfig returns a default configuration for metrics
  690. // reporting.
  691. func DefaultInstrumentationConfig() *InstrumentationConfig {
  692. return &InstrumentationConfig{
  693. Prometheus: false,
  694. PrometheusListenAddr: ":26660",
  695. MaxOpenConnections: 3,
  696. Namespace: "tendermint",
  697. }
  698. }
  699. // TestInstrumentationConfig returns a default configuration for metrics
  700. // reporting.
  701. func TestInstrumentationConfig() *InstrumentationConfig {
  702. return DefaultInstrumentationConfig()
  703. }
  704. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  705. // returns an error if any check fails.
  706. func (cfg *InstrumentationConfig) ValidateBasic() error {
  707. if cfg.MaxOpenConnections < 0 {
  708. return errors.New("max_open_connections can't be negative")
  709. }
  710. return nil
  711. }
  712. //-----------------------------------------------------------------------------
  713. // Utils
  714. // helper function to make config creation independent of root dir
  715. func rootify(path, root string) string {
  716. if filepath.IsAbs(path) {
  717. return path
  718. }
  719. return filepath.Join(root, path)
  720. }
  721. //-----------------------------------------------------------------------------
  722. // Moniker
  723. var defaultMoniker = getDefaultMoniker()
  724. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  725. // fails to get the host name, "anonymous" will be returned.
  726. func getDefaultMoniker() string {
  727. moniker, err := os.Hostname()
  728. if err != nil {
  729. moniker = "anonymous"
  730. }
  731. return moniker
  732. }