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.

813 lines
28 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. // A list of origins a cross-domain request can be executed from.
  204. // If the special '*' value is present in the list, all origins will be allowed.
  205. // An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com).
  206. // Only one wildcard can be used per origin.
  207. CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"`
  208. // A list of methods the client is allowed to use with cross-domain requests.
  209. CORSAllowedMethods []string `mapstructure:"cors_allowed_methods"`
  210. // A list of non simple headers the client is allowed to use with cross-domain requests.
  211. CORSAllowedHeaders []string `mapstructure:"cors_allowed_headers"`
  212. // TCP or UNIX socket address for the gRPC server to listen on
  213. // NOTE: This server only supports /broadcast_tx_commit
  214. GRPCListenAddress string `mapstructure:"grpc_laddr"`
  215. // Maximum number of simultaneous connections.
  216. // Does not include RPC (HTTP&WebSocket) connections. See max_open_connections
  217. // If you want to accept more significant number than the default, make sure
  218. // you increase your OS limits.
  219. // 0 - unlimited.
  220. GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"`
  221. // Activate unsafe RPC commands like /dial_persistent_peers and /unsafe_flush_mempool
  222. Unsafe bool `mapstructure:"unsafe"`
  223. // Maximum number of simultaneous connections (including WebSocket).
  224. // Does not include gRPC connections. See grpc_max_open_connections
  225. // If you want to accept more significant number than the default, make sure
  226. // you increase your OS limits.
  227. // 0 - unlimited.
  228. // Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
  229. // 1024 - 40 - 10 - 50 = 924 = ~900
  230. MaxOpenConnections int `mapstructure:"max_open_connections"`
  231. }
  232. // DefaultRPCConfig returns a default configuration for the RPC server
  233. func DefaultRPCConfig() *RPCConfig {
  234. return &RPCConfig{
  235. ListenAddress: "tcp://0.0.0.0:26657",
  236. CORSAllowedOrigins: []string{},
  237. CORSAllowedMethods: []string{"HEAD", "GET", "POST"},
  238. CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
  239. GRPCListenAddress: "",
  240. GRPCMaxOpenConnections: 900,
  241. Unsafe: false,
  242. MaxOpenConnections: 900,
  243. }
  244. }
  245. // TestRPCConfig returns a configuration for testing the RPC server
  246. func TestRPCConfig() *RPCConfig {
  247. cfg := DefaultRPCConfig()
  248. cfg.ListenAddress = "tcp://0.0.0.0:36657"
  249. cfg.GRPCListenAddress = "tcp://0.0.0.0:36658"
  250. cfg.Unsafe = true
  251. return cfg
  252. }
  253. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  254. // returns an error if any check fails.
  255. func (cfg *RPCConfig) ValidateBasic() error {
  256. if cfg.GRPCMaxOpenConnections < 0 {
  257. return errors.New("grpc_max_open_connections can't be negative")
  258. }
  259. if cfg.MaxOpenConnections < 0 {
  260. return errors.New("max_open_connections can't be negative")
  261. }
  262. return nil
  263. }
  264. // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
  265. func (cfg *RPCConfig) IsCorsEnabled() bool {
  266. return len(cfg.CORSAllowedOrigins) != 0
  267. }
  268. //-----------------------------------------------------------------------------
  269. // P2PConfig
  270. // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
  271. type P2PConfig struct {
  272. RootDir string `mapstructure:"home"`
  273. // Address to listen for incoming connections
  274. ListenAddress string `mapstructure:"laddr"`
  275. // Address to advertise to peers for them to dial
  276. ExternalAddress string `mapstructure:"external_address"`
  277. // Comma separated list of seed nodes to connect to
  278. // We only use these if we can’t connect to peers in the addrbook
  279. Seeds string `mapstructure:"seeds"`
  280. // Comma separated list of nodes to keep persistent connections to
  281. PersistentPeers string `mapstructure:"persistent_peers"`
  282. // UPNP port forwarding
  283. UPNP bool `mapstructure:"upnp"`
  284. // Path to address book
  285. AddrBook string `mapstructure:"addr_book_file"`
  286. // Set true for strict address routability rules
  287. // Set false for private or local networks
  288. AddrBookStrict bool `mapstructure:"addr_book_strict"`
  289. // Maximum number of inbound peers
  290. MaxNumInboundPeers int `mapstructure:"max_num_inbound_peers"`
  291. // Maximum number of outbound peers to connect to, excluding persistent peers
  292. MaxNumOutboundPeers int `mapstructure:"max_num_outbound_peers"`
  293. // Time to wait before flushing messages out on the connection
  294. FlushThrottleTimeout time.Duration `mapstructure:"flush_throttle_timeout"`
  295. // Maximum size of a message packet payload, in bytes
  296. MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
  297. // Rate at which packets can be sent, in bytes/second
  298. SendRate int64 `mapstructure:"send_rate"`
  299. // Rate at which packets can be received, in bytes/second
  300. RecvRate int64 `mapstructure:"recv_rate"`
  301. // Set true to enable the peer-exchange reactor
  302. PexReactor bool `mapstructure:"pex"`
  303. // Seed mode, in which node constantly crawls the network and looks for
  304. // peers. If another node asks it for addresses, it responds and disconnects.
  305. //
  306. // Does not work if the peer-exchange reactor is disabled.
  307. SeedMode bool `mapstructure:"seed_mode"`
  308. // Comma separated list of peer IDs to keep private (will not be gossiped to
  309. // other peers)
  310. PrivatePeerIDs string `mapstructure:"private_peer_ids"`
  311. // Toggle to disable guard against peers connecting from the same ip.
  312. AllowDuplicateIP bool `mapstructure:"allow_duplicate_ip"`
  313. // Peer connection configuration.
  314. HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
  315. DialTimeout time.Duration `mapstructure:"dial_timeout"`
  316. // Testing params.
  317. // Force dial to fail
  318. TestDialFail bool `mapstructure:"test_dial_fail"`
  319. // FUzz connection
  320. TestFuzz bool `mapstructure:"test_fuzz"`
  321. TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"`
  322. }
  323. // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
  324. func DefaultP2PConfig() *P2PConfig {
  325. return &P2PConfig{
  326. ListenAddress: "tcp://0.0.0.0:26656",
  327. ExternalAddress: "",
  328. UPNP: false,
  329. AddrBook: defaultAddrBookPath,
  330. AddrBookStrict: true,
  331. MaxNumInboundPeers: 40,
  332. MaxNumOutboundPeers: 10,
  333. FlushThrottleTimeout: 100 * time.Millisecond,
  334. MaxPacketMsgPayloadSize: 1024, // 1 kB
  335. SendRate: 5120000, // 5 mB/s
  336. RecvRate: 5120000, // 5 mB/s
  337. PexReactor: true,
  338. SeedMode: false,
  339. AllowDuplicateIP: true, // so non-breaking yet
  340. HandshakeTimeout: 20 * time.Second,
  341. DialTimeout: 3 * time.Second,
  342. TestDialFail: false,
  343. TestFuzz: false,
  344. TestFuzzConfig: DefaultFuzzConnConfig(),
  345. }
  346. }
  347. // TestP2PConfig returns a configuration for testing the peer-to-peer layer
  348. func TestP2PConfig() *P2PConfig {
  349. cfg := DefaultP2PConfig()
  350. cfg.ListenAddress = "tcp://0.0.0.0:36656"
  351. cfg.FlushThrottleTimeout = 10 * time.Millisecond
  352. cfg.AllowDuplicateIP = true
  353. return cfg
  354. }
  355. // AddrBookFile returns the full path to the address book
  356. func (cfg *P2PConfig) AddrBookFile() string {
  357. return rootify(cfg.AddrBook, cfg.RootDir)
  358. }
  359. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  360. // returns an error if any check fails.
  361. func (cfg *P2PConfig) ValidateBasic() error {
  362. if cfg.MaxNumInboundPeers < 0 {
  363. return errors.New("max_num_inbound_peers can't be negative")
  364. }
  365. if cfg.MaxNumOutboundPeers < 0 {
  366. return errors.New("max_num_outbound_peers can't be negative")
  367. }
  368. if cfg.FlushThrottleTimeout < 0 {
  369. return errors.New("flush_throttle_timeout can't be negative")
  370. }
  371. if cfg.MaxPacketMsgPayloadSize < 0 {
  372. return errors.New("max_packet_msg_payload_size can't be negative")
  373. }
  374. if cfg.SendRate < 0 {
  375. return errors.New("send_rate can't be negative")
  376. }
  377. if cfg.RecvRate < 0 {
  378. return errors.New("recv_rate can't be negative")
  379. }
  380. return nil
  381. }
  382. // FuzzConnConfig is a FuzzedConnection configuration.
  383. type FuzzConnConfig struct {
  384. Mode int
  385. MaxDelay time.Duration
  386. ProbDropRW float64
  387. ProbDropConn float64
  388. ProbSleep float64
  389. }
  390. // DefaultFuzzConnConfig returns the default config.
  391. func DefaultFuzzConnConfig() *FuzzConnConfig {
  392. return &FuzzConnConfig{
  393. Mode: FuzzModeDrop,
  394. MaxDelay: 3 * time.Second,
  395. ProbDropRW: 0.2,
  396. ProbDropConn: 0.00,
  397. ProbSleep: 0.00,
  398. }
  399. }
  400. //-----------------------------------------------------------------------------
  401. // MempoolConfig
  402. // MempoolConfig defines the configuration options for the Tendermint mempool
  403. type MempoolConfig struct {
  404. RootDir string `mapstructure:"home"`
  405. Recheck bool `mapstructure:"recheck"`
  406. Broadcast bool `mapstructure:"broadcast"`
  407. WalPath string `mapstructure:"wal_dir"`
  408. Size int `mapstructure:"size"`
  409. CacheSize int `mapstructure:"cache_size"`
  410. }
  411. // DefaultMempoolConfig returns a default configuration for the Tendermint mempool
  412. func DefaultMempoolConfig() *MempoolConfig {
  413. return &MempoolConfig{
  414. Recheck: true,
  415. Broadcast: true,
  416. WalPath: "",
  417. // Each signature verification takes .5ms, size reduced until we implement
  418. // ABCI Recheck
  419. Size: 5000,
  420. CacheSize: 10000,
  421. }
  422. }
  423. // TestMempoolConfig returns a configuration for testing the Tendermint mempool
  424. func TestMempoolConfig() *MempoolConfig {
  425. cfg := DefaultMempoolConfig()
  426. cfg.CacheSize = 1000
  427. return cfg
  428. }
  429. // WalDir returns the full path to the mempool's write-ahead log
  430. func (cfg *MempoolConfig) WalDir() string {
  431. return rootify(cfg.WalPath, cfg.RootDir)
  432. }
  433. // WalEnabled returns true if the WAL is enabled.
  434. func (cfg *MempoolConfig) WalEnabled() bool {
  435. return cfg.WalPath != ""
  436. }
  437. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  438. // returns an error if any check fails.
  439. func (cfg *MempoolConfig) ValidateBasic() error {
  440. if cfg.Size < 0 {
  441. return errors.New("size can't be negative")
  442. }
  443. if cfg.CacheSize < 0 {
  444. return errors.New("cache_size can't be negative")
  445. }
  446. return nil
  447. }
  448. //-----------------------------------------------------------------------------
  449. // ConsensusConfig
  450. // ConsensusConfig defines the configuration for the Tendermint consensus service,
  451. // including timeouts and details about the WAL and the block structure.
  452. type ConsensusConfig struct {
  453. RootDir string `mapstructure:"home"`
  454. WalPath string `mapstructure:"wal_file"`
  455. walFile string // overrides WalPath if set
  456. TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
  457. TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
  458. TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
  459. TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
  460. TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
  461. TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
  462. TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
  463. // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  464. SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
  465. // EmptyBlocks mode and possible interval between empty blocks
  466. CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"`
  467. CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
  468. // Reactor sleep duration parameters
  469. PeerGossipSleepDuration time.Duration `mapstructure:"peer_gossip_sleep_duration"`
  470. PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
  471. // Block time parameters. Corresponds to the minimum time increment between consecutive blocks.
  472. BlockTimeIota time.Duration `mapstructure:"blocktime_iota"`
  473. }
  474. // DefaultConsensusConfig returns a default configuration for the consensus service
  475. func DefaultConsensusConfig() *ConsensusConfig {
  476. return &ConsensusConfig{
  477. WalPath: filepath.Join(defaultDataDir, "cs.wal", "wal"),
  478. TimeoutPropose: 3000 * time.Millisecond,
  479. TimeoutProposeDelta: 500 * time.Millisecond,
  480. TimeoutPrevote: 1000 * time.Millisecond,
  481. TimeoutPrevoteDelta: 500 * time.Millisecond,
  482. TimeoutPrecommit: 1000 * time.Millisecond,
  483. TimeoutPrecommitDelta: 500 * time.Millisecond,
  484. TimeoutCommit: 1000 * time.Millisecond,
  485. SkipTimeoutCommit: false,
  486. CreateEmptyBlocks: true,
  487. CreateEmptyBlocksInterval: 0 * time.Second,
  488. PeerGossipSleepDuration: 100 * time.Millisecond,
  489. PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  490. BlockTimeIota: 1000 * time.Millisecond,
  491. }
  492. }
  493. // TestConsensusConfig returns a configuration for testing the consensus service
  494. func TestConsensusConfig() *ConsensusConfig {
  495. cfg := DefaultConsensusConfig()
  496. cfg.TimeoutPropose = 40 * time.Millisecond
  497. cfg.TimeoutProposeDelta = 1 * time.Millisecond
  498. cfg.TimeoutPrevote = 10 * time.Millisecond
  499. cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  500. cfg.TimeoutPrecommit = 10 * time.Millisecond
  501. cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  502. cfg.TimeoutCommit = 10 * time.Millisecond
  503. cfg.SkipTimeoutCommit = true
  504. cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  505. cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  506. cfg.BlockTimeIota = 10 * time.Millisecond
  507. return cfg
  508. }
  509. // MinValidVoteTime returns the minimum acceptable block time.
  510. // See the [BFT time spec](https://godoc.org/github.com/tendermint/tendermint/docs/spec/consensus/bft-time.md).
  511. func (cfg *ConsensusConfig) MinValidVoteTime(lastBlockTime time.Time) time.Time {
  512. return lastBlockTime.Add(cfg.BlockTimeIota)
  513. }
  514. // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  515. func (cfg *ConsensusConfig) WaitForTxs() bool {
  516. return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  517. }
  518. // Propose returns the amount of time to wait for a proposal
  519. func (cfg *ConsensusConfig) Propose(round int) time.Duration {
  520. return time.Duration(
  521. cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  522. ) * time.Nanosecond
  523. }
  524. // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  525. func (cfg *ConsensusConfig) Prevote(round int) time.Duration {
  526. return time.Duration(
  527. cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  528. ) * time.Nanosecond
  529. }
  530. // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  531. func (cfg *ConsensusConfig) Precommit(round int) time.Duration {
  532. return time.Duration(
  533. cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  534. ) * time.Nanosecond
  535. }
  536. // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits for a single block (ie. a commit).
  537. func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  538. return t.Add(cfg.TimeoutCommit)
  539. }
  540. // WalFile returns the full path to the write-ahead log file
  541. func (cfg *ConsensusConfig) WalFile() string {
  542. if cfg.walFile != "" {
  543. return cfg.walFile
  544. }
  545. return rootify(cfg.WalPath, cfg.RootDir)
  546. }
  547. // SetWalFile sets the path to the write-ahead log file
  548. func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  549. cfg.walFile = walFile
  550. }
  551. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  552. // returns an error if any check fails.
  553. func (cfg *ConsensusConfig) ValidateBasic() error {
  554. if cfg.TimeoutPropose < 0 {
  555. return errors.New("timeout_propose can't be negative")
  556. }
  557. if cfg.TimeoutProposeDelta < 0 {
  558. return errors.New("timeout_propose_delta can't be negative")
  559. }
  560. if cfg.TimeoutPrevote < 0 {
  561. return errors.New("timeout_prevote can't be negative")
  562. }
  563. if cfg.TimeoutPrevoteDelta < 0 {
  564. return errors.New("timeout_prevote_delta can't be negative")
  565. }
  566. if cfg.TimeoutPrecommit < 0 {
  567. return errors.New("timeout_precommit can't be negative")
  568. }
  569. if cfg.TimeoutPrecommitDelta < 0 {
  570. return errors.New("timeout_precommit_delta can't be negative")
  571. }
  572. if cfg.TimeoutCommit < 0 {
  573. return errors.New("timeout_commit can't be negative")
  574. }
  575. if cfg.CreateEmptyBlocksInterval < 0 {
  576. return errors.New("create_empty_blocks_interval can't be negative")
  577. }
  578. if cfg.PeerGossipSleepDuration < 0 {
  579. return errors.New("peer_gossip_sleep_duration can't be negative")
  580. }
  581. if cfg.PeerQueryMaj23SleepDuration < 0 {
  582. return errors.New("peer_query_maj23_sleep_duration can't be negative")
  583. }
  584. if cfg.BlockTimeIota < 0 {
  585. return errors.New("blocktime_iota can't be negative")
  586. }
  587. return nil
  588. }
  589. //-----------------------------------------------------------------------------
  590. // TxIndexConfig
  591. // TxIndexConfig defines the configuration for the transaction indexer,
  592. // including tags to index.
  593. type TxIndexConfig struct {
  594. // What indexer to use for transactions
  595. //
  596. // Options:
  597. // 1) "null"
  598. // 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend).
  599. Indexer string `mapstructure:"indexer"`
  600. // Comma-separated list of tags to index (by default the only tag is "tx.hash")
  601. //
  602. // You can also index transactions by height by adding "tx.height" tag here.
  603. //
  604. // It's recommended to index only a subset of tags due to possible memory
  605. // bloat. This is, of course, depends on the indexer's DB and the volume of
  606. // transactions.
  607. IndexTags string `mapstructure:"index_tags"`
  608. // When set to true, tells indexer to index all tags (predefined tags:
  609. // "tx.hash", "tx.height" and all tags from DeliverTx responses).
  610. //
  611. // Note this may be not desirable (see the comment above). IndexTags has a
  612. // precedence over IndexAllTags (i.e. when given both, IndexTags will be
  613. // indexed).
  614. IndexAllTags bool `mapstructure:"index_all_tags"`
  615. }
  616. // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  617. func DefaultTxIndexConfig() *TxIndexConfig {
  618. return &TxIndexConfig{
  619. Indexer: "kv",
  620. IndexTags: "",
  621. IndexAllTags: false,
  622. }
  623. }
  624. // TestTxIndexConfig returns a default configuration for the transaction indexer.
  625. func TestTxIndexConfig() *TxIndexConfig {
  626. return DefaultTxIndexConfig()
  627. }
  628. //-----------------------------------------------------------------------------
  629. // InstrumentationConfig
  630. // InstrumentationConfig defines the configuration for metrics reporting.
  631. type InstrumentationConfig struct {
  632. // When true, Prometheus metrics are served under /metrics on
  633. // PrometheusListenAddr.
  634. // Check out the documentation for the list of available metrics.
  635. Prometheus bool `mapstructure:"prometheus"`
  636. // Address to listen for Prometheus collector(s) connections.
  637. PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"`
  638. // Maximum number of simultaneous connections.
  639. // If you want to accept more significant number than the default, make sure
  640. // you increase your OS limits.
  641. // 0 - unlimited.
  642. MaxOpenConnections int `mapstructure:"max_open_connections"`
  643. // Tendermint instrumentation namespace.
  644. Namespace string `mapstructure:"namespace"`
  645. }
  646. // DefaultInstrumentationConfig returns a default configuration for metrics
  647. // reporting.
  648. func DefaultInstrumentationConfig() *InstrumentationConfig {
  649. return &InstrumentationConfig{
  650. Prometheus: false,
  651. PrometheusListenAddr: ":26660",
  652. MaxOpenConnections: 3,
  653. Namespace: "tendermint",
  654. }
  655. }
  656. // TestInstrumentationConfig returns a default configuration for metrics
  657. // reporting.
  658. func TestInstrumentationConfig() *InstrumentationConfig {
  659. return DefaultInstrumentationConfig()
  660. }
  661. // ValidateBasic performs basic validation (checking param bounds, etc.) and
  662. // returns an error if any check fails.
  663. func (cfg *InstrumentationConfig) ValidateBasic() error {
  664. if cfg.MaxOpenConnections < 0 {
  665. return errors.New("max_open_connections can't be negative")
  666. }
  667. return nil
  668. }
  669. //-----------------------------------------------------------------------------
  670. // Utils
  671. // helper function to make config creation independent of root dir
  672. func rootify(path, root string) string {
  673. if filepath.IsAbs(path) {
  674. return path
  675. }
  676. return filepath.Join(root, path)
  677. }
  678. //-----------------------------------------------------------------------------
  679. // Moniker
  680. var defaultMoniker = getDefaultMoniker()
  681. // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  682. // fails to get the host name, "anonymous" will be returned.
  683. func getDefaultMoniker() string {
  684. moniker, err := os.Hostname()
  685. if err != nil {
  686. moniker = "anonymous"
  687. }
  688. return moniker
  689. }