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.

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