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.

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