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.

930 lines
32 KiB

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