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.

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