github.com/number571/tendermint@v0.34.11-gost/config/config.go (about)

     1  package config
     2  
     3  import (
     4  	"encoding/hex"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"os"
    10  	"path/filepath"
    11  	"time"
    12  
    13  	tmjson "github.com/number571/tendermint/libs/json"
    14  	"github.com/number571/tendermint/libs/log"
    15  	tmos "github.com/number571/tendermint/libs/os"
    16  	"github.com/number571/tendermint/types"
    17  )
    18  
    19  const (
    20  	// FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep
    21  	FuzzModeDrop = iota
    22  	// FuzzModeDelay is a mode in which we randomly sleep
    23  	FuzzModeDelay
    24  
    25  	// DefaultLogLevel defines a default log level as INFO.
    26  	DefaultLogLevel = "info"
    27  
    28  	ModeFull      = "full"
    29  	ModeValidator = "validator"
    30  	ModeSeed      = "seed"
    31  
    32  	BlockchainV0 = "v0"
    33  	BlockchainV2 = "v2"
    34  
    35  	MempoolV0 = "v0"
    36  	MempoolV1 = "v1"
    37  )
    38  
    39  // NOTE: Most of the structs & relevant comments + the
    40  // default configuration options were used to manually
    41  // generate the config.toml. Please reflect any changes
    42  // made here in the defaultConfigTemplate constant in
    43  // config/toml.go
    44  // NOTE: libs/cli must know to look in the config dir!
    45  var (
    46  	DefaultTendermintDir = ".tendermint"
    47  	defaultConfigDir     = "config"
    48  	defaultDataDir       = "data"
    49  
    50  	defaultConfigFileName  = "config.toml"
    51  	defaultGenesisJSONName = "genesis.json"
    52  
    53  	defaultMode             = ModeFull
    54  	defaultPrivValKeyName   = "priv_validator_key.json"
    55  	defaultPrivValStateName = "priv_validator_state.json"
    56  
    57  	defaultNodeKeyName  = "node_key.json"
    58  	defaultAddrBookName = "addrbook.json"
    59  
    60  	defaultConfigFilePath   = filepath.Join(defaultConfigDir, defaultConfigFileName)
    61  	defaultGenesisJSONPath  = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
    62  	defaultPrivValKeyPath   = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
    63  	defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
    64  
    65  	defaultNodeKeyPath  = filepath.Join(defaultConfigDir, defaultNodeKeyName)
    66  	defaultAddrBookPath = filepath.Join(defaultConfigDir, defaultAddrBookName)
    67  )
    68  
    69  // Config defines the top level configuration for a Tendermint node
    70  type Config struct {
    71  	// Top level options use an anonymous struct
    72  	BaseConfig `mapstructure:",squash"`
    73  
    74  	// Options for services
    75  	RPC             *RPCConfig             `mapstructure:"rpc"`
    76  	P2P             *P2PConfig             `mapstructure:"p2p"`
    77  	Mempool         *MempoolConfig         `mapstructure:"mempool"`
    78  	StateSync       *StateSyncConfig       `mapstructure:"statesync"`
    79  	FastSync        *FastSyncConfig        `mapstructure:"fastsync"`
    80  	Consensus       *ConsensusConfig       `mapstructure:"consensus"`
    81  	TxIndex         *TxIndexConfig         `mapstructure:"tx-index"`
    82  	Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
    83  	PrivValidator   *PrivValidatorConfig   `mapstructure:"priv-validator"`
    84  }
    85  
    86  // DefaultConfig returns a default configuration for a Tendermint node
    87  func DefaultConfig() *Config {
    88  	return &Config{
    89  		BaseConfig:      DefaultBaseConfig(),
    90  		RPC:             DefaultRPCConfig(),
    91  		P2P:             DefaultP2PConfig(),
    92  		Mempool:         DefaultMempoolConfig(),
    93  		StateSync:       DefaultStateSyncConfig(),
    94  		FastSync:        DefaultFastSyncConfig(),
    95  		Consensus:       DefaultConsensusConfig(),
    96  		TxIndex:         DefaultTxIndexConfig(),
    97  		Instrumentation: DefaultInstrumentationConfig(),
    98  		PrivValidator:   DefaultPrivValidatorConfig(),
    99  	}
   100  }
   101  
   102  // DefaultValidatorConfig returns default config with mode as validator
   103  func DefaultValidatorConfig() *Config {
   104  	cfg := DefaultConfig()
   105  	cfg.Mode = ModeValidator
   106  	return cfg
   107  }
   108  
   109  // TestConfig returns a configuration that can be used for testing
   110  func TestConfig() *Config {
   111  	return &Config{
   112  		BaseConfig:      TestBaseConfig(),
   113  		RPC:             TestRPCConfig(),
   114  		P2P:             TestP2PConfig(),
   115  		Mempool:         TestMempoolConfig(),
   116  		StateSync:       TestStateSyncConfig(),
   117  		FastSync:        TestFastSyncConfig(),
   118  		Consensus:       TestConsensusConfig(),
   119  		TxIndex:         TestTxIndexConfig(),
   120  		Instrumentation: TestInstrumentationConfig(),
   121  		PrivValidator:   DefaultPrivValidatorConfig(),
   122  	}
   123  }
   124  
   125  // SetRoot sets the RootDir for all Config structs
   126  func (cfg *Config) SetRoot(root string) *Config {
   127  	cfg.BaseConfig.RootDir = root
   128  	cfg.RPC.RootDir = root
   129  	cfg.P2P.RootDir = root
   130  	cfg.Mempool.RootDir = root
   131  	cfg.Consensus.RootDir = root
   132  	cfg.PrivValidator.RootDir = root
   133  	return cfg
   134  }
   135  
   136  // ValidateBasic performs basic validation (checking param bounds, etc.) and
   137  // returns an error if any check fails.
   138  func (cfg *Config) ValidateBasic() error {
   139  	if err := cfg.BaseConfig.ValidateBasic(); err != nil {
   140  		return err
   141  	}
   142  	if err := cfg.RPC.ValidateBasic(); err != nil {
   143  		return fmt.Errorf("error in [rpc] section: %w", err)
   144  	}
   145  	if err := cfg.P2P.ValidateBasic(); err != nil {
   146  		return fmt.Errorf("error in [p2p] section: %w", err)
   147  	}
   148  	if err := cfg.Mempool.ValidateBasic(); err != nil {
   149  		return fmt.Errorf("error in [mempool] section: %w", err)
   150  	}
   151  	if err := cfg.StateSync.ValidateBasic(); err != nil {
   152  		return fmt.Errorf("error in [statesync] section: %w", err)
   153  	}
   154  	if err := cfg.FastSync.ValidateBasic(); err != nil {
   155  		return fmt.Errorf("error in [fastsync] section: %w", err)
   156  	}
   157  	if err := cfg.Consensus.ValidateBasic(); err != nil {
   158  		return fmt.Errorf("error in [consensus] section: %w", err)
   159  	}
   160  	if err := cfg.Instrumentation.ValidateBasic(); err != nil {
   161  		return fmt.Errorf("error in [instrumentation] section: %w", err)
   162  	}
   163  	return nil
   164  }
   165  
   166  //-----------------------------------------------------------------------------
   167  // BaseConfig
   168  
   169  // BaseConfig defines the base configuration for a Tendermint node
   170  type BaseConfig struct { //nolint: maligned
   171  	// chainID is unexposed and immutable but here for convenience
   172  	chainID string
   173  
   174  	// The root directory for all data.
   175  	// This should be set in viper so it can unmarshal into this struct
   176  	RootDir string `mapstructure:"home"`
   177  
   178  	// TCP or UNIX socket address of the ABCI application,
   179  	// or the name of an ABCI application compiled in with the Tendermint binary
   180  	ProxyApp string `mapstructure:"proxy-app"`
   181  
   182  	// A custom human readable name for this node
   183  	Moniker string `mapstructure:"moniker"`
   184  
   185  	// Mode of Node: full | validator | seed
   186  	// * validator
   187  	//   - all reactors
   188  	//   - with priv_validator_key.json, priv_validator_state.json
   189  	// * full
   190  	//   - all reactors
   191  	//   - No priv_validator_key.json, priv_validator_state.json
   192  	// * seed
   193  	//   - only P2P, PEX Reactor
   194  	//   - No priv_validator_key.json, priv_validator_state.json
   195  	Mode string `mapstructure:"mode"`
   196  
   197  	// If this node is many blocks behind the tip of the chain, FastSync
   198  	// allows them to catchup quickly by downloading blocks in parallel
   199  	// and verifying their commits
   200  	FastSyncMode bool `mapstructure:"fast-sync"`
   201  
   202  	// Database backend: goleveldb | cleveldb | boltdb | rocksdb
   203  	// * goleveldb (github.com/syndtr/goleveldb - most popular implementation)
   204  	//   - pure go
   205  	//   - stable
   206  	// * cleveldb (uses levigo wrapper)
   207  	//   - fast
   208  	//   - requires gcc
   209  	//   - use cleveldb build tag (go build -tags cleveldb)
   210  	// * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt)
   211  	//   - EXPERIMENTAL
   212  	//   - may be faster is some use-cases (random reads - indexer)
   213  	//   - use boltdb build tag (go build -tags boltdb)
   214  	// * rocksdb (uses github.com/tecbot/gorocksdb)
   215  	//   - EXPERIMENTAL
   216  	//   - requires gcc
   217  	//   - use rocksdb build tag (go build -tags rocksdb)
   218  	// * badgerdb (uses github.com/dgraph-io/badger)
   219  	//   - EXPERIMENTAL
   220  	//   - use badgerdb build tag (go build -tags badgerdb)
   221  	DBBackend string `mapstructure:"db-backend"`
   222  
   223  	// Database directory
   224  	DBPath string `mapstructure:"db-dir"`
   225  
   226  	// Output level for logging
   227  	LogLevel string `mapstructure:"log-level"`
   228  
   229  	// Output format: 'plain' (colored text) or 'json'
   230  	LogFormat string `mapstructure:"log-format"`
   231  
   232  	// Path to the JSON file containing the initial validator set and other meta data
   233  	Genesis string `mapstructure:"genesis-file"`
   234  
   235  	// A JSON file containing the private key to use for p2p authenticated encryption
   236  	NodeKey string `mapstructure:"node-key-file"`
   237  
   238  	// Mechanism to connect to the ABCI application: socket | grpc
   239  	ABCI string `mapstructure:"abci"`
   240  
   241  	// If true, query the ABCI app on connecting to a new peer
   242  	// so the app can decide if we should keep the connection or not
   243  	FilterPeers bool `mapstructure:"filter-peers"` // false
   244  }
   245  
   246  // DefaultBaseConfig returns a default base configuration for a Tendermint node
   247  func DefaultBaseConfig() BaseConfig {
   248  	return BaseConfig{
   249  		Genesis:      defaultGenesisJSONPath,
   250  		NodeKey:      defaultNodeKeyPath,
   251  		Mode:         defaultMode,
   252  		Moniker:      defaultMoniker,
   253  		ProxyApp:     "tcp://127.0.0.1:26658",
   254  		ABCI:         "socket",
   255  		LogLevel:     DefaultLogLevel,
   256  		LogFormat:    log.LogFormatPlain,
   257  		FastSyncMode: true,
   258  		FilterPeers:  false,
   259  		DBBackend:    "goleveldb",
   260  		DBPath:       "data",
   261  	}
   262  }
   263  
   264  // TestBaseConfig returns a base configuration for testing a Tendermint node
   265  func TestBaseConfig() BaseConfig {
   266  	cfg := DefaultBaseConfig()
   267  	cfg.chainID = "tendermint_test"
   268  	cfg.Mode = ModeValidator
   269  	cfg.ProxyApp = "kvstore"
   270  	cfg.FastSyncMode = false
   271  	cfg.DBBackend = "memdb"
   272  	return cfg
   273  }
   274  
   275  func (cfg BaseConfig) ChainID() string {
   276  	return cfg.chainID
   277  }
   278  
   279  // GenesisFile returns the full path to the genesis.json file
   280  func (cfg BaseConfig) GenesisFile() string {
   281  	return rootify(cfg.Genesis, cfg.RootDir)
   282  }
   283  
   284  // NodeKeyFile returns the full path to the node_key.json file
   285  func (cfg BaseConfig) NodeKeyFile() string {
   286  	return rootify(cfg.NodeKey, cfg.RootDir)
   287  }
   288  
   289  // LoadNodeKey loads NodeKey located in filePath.
   290  func (cfg BaseConfig) LoadNodeKeyID() (types.NodeID, error) {
   291  	jsonBytes, err := ioutil.ReadFile(cfg.NodeKeyFile())
   292  	if err != nil {
   293  		return "", err
   294  	}
   295  	nodeKey := types.NodeKey{}
   296  	err = tmjson.Unmarshal(jsonBytes, &nodeKey)
   297  	if err != nil {
   298  		return "", err
   299  	}
   300  	nodeKey.ID = types.NodeIDFromPubKey(nodeKey.PubKey())
   301  	return nodeKey.ID, nil
   302  }
   303  
   304  // LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If
   305  // the file does not exist, it generates and saves a new NodeKey.
   306  func (cfg BaseConfig) LoadOrGenNodeKeyID() (types.NodeID, error) {
   307  	if tmos.FileExists(cfg.NodeKeyFile()) {
   308  		nodeKey, err := cfg.LoadNodeKeyID()
   309  		if err != nil {
   310  			return "", err
   311  		}
   312  		return nodeKey, nil
   313  	}
   314  
   315  	nodeKey := types.GenNodeKey()
   316  
   317  	if err := nodeKey.SaveAs(cfg.NodeKeyFile()); err != nil {
   318  		return "", err
   319  	}
   320  
   321  	return nodeKey.ID, nil
   322  }
   323  
   324  // DBDir returns the full path to the database directory
   325  func (cfg BaseConfig) DBDir() string {
   326  	return rootify(cfg.DBPath, cfg.RootDir)
   327  }
   328  
   329  // ValidateBasic performs basic validation (checking param bounds, etc.) and
   330  // returns an error if any check fails.
   331  func (cfg BaseConfig) ValidateBasic() error {
   332  	switch cfg.LogFormat {
   333  	case log.LogFormatJSON, log.LogFormatText, log.LogFormatPlain:
   334  	default:
   335  		return errors.New("unknown log format (must be 'plain', 'text' or 'json')")
   336  	}
   337  
   338  	switch cfg.Mode {
   339  	case ModeFull, ModeValidator, ModeSeed:
   340  	case "":
   341  		return errors.New("no mode has been set")
   342  
   343  	default:
   344  		return fmt.Errorf("unknown mode: %v", cfg.Mode)
   345  	}
   346  
   347  	return nil
   348  }
   349  
   350  //-----------------------------------------------------------------------------
   351  // PrivValidatorConfig
   352  
   353  // PrivValidatorConfig defines the configuration parameters for running a validator
   354  type PrivValidatorConfig struct {
   355  	RootDir string `mapstructure:"home"`
   356  
   357  	// Path to the JSON file containing the private key to use as a validator in the consensus protocol
   358  	Key string `mapstructure:"key-file"`
   359  
   360  	// Path to the JSON file containing the last sign state of a validator
   361  	State string `mapstructure:"state-file"`
   362  
   363  	// TCP or UNIX socket address for Tendermint to listen on for
   364  	// connections from an external PrivValidator process
   365  	ListenAddr string `mapstructure:"laddr"`
   366  
   367  	// Client certificate generated while creating needed files for secure connection.
   368  	// If a remote validator address is provided but no certificate, the connection will be insecure
   369  	ClientCertificate string `mapstructure:"client-certificate-file"`
   370  
   371  	// Client key generated while creating certificates for secure connection
   372  	ClientKey string `mapstructure:"client-key-file"`
   373  
   374  	// Path Root Certificate Authority used to sign both client and server certificates
   375  	RootCA string `mapstructure:"root-ca-file"`
   376  }
   377  
   378  // DefaultBaseConfig returns a default private validator configuration
   379  // for a Tendermint node.
   380  func DefaultPrivValidatorConfig() *PrivValidatorConfig {
   381  	return &PrivValidatorConfig{
   382  		Key:   defaultPrivValKeyPath,
   383  		State: defaultPrivValStatePath,
   384  	}
   385  }
   386  
   387  // ClientKeyFile returns the full path to the priv_validator_key.json file
   388  func (cfg *PrivValidatorConfig) ClientKeyFile() string {
   389  	return rootify(cfg.ClientKey, cfg.RootDir)
   390  }
   391  
   392  // ClientCertificateFile returns the full path to the priv_validator_key.json file
   393  func (cfg *PrivValidatorConfig) ClientCertificateFile() string {
   394  	return rootify(cfg.ClientCertificate, cfg.RootDir)
   395  }
   396  
   397  // CertificateAuthorityFile returns the full path to the priv_validator_key.json file
   398  func (cfg *PrivValidatorConfig) RootCAFile() string {
   399  	return rootify(cfg.RootCA, cfg.RootDir)
   400  }
   401  
   402  // KeyFile returns the full path to the priv_validator_key.json file
   403  func (cfg *PrivValidatorConfig) KeyFile() string {
   404  	return rootify(cfg.Key, cfg.RootDir)
   405  }
   406  
   407  // StateFile returns the full path to the priv_validator_state.json file
   408  func (cfg *PrivValidatorConfig) StateFile() string {
   409  	return rootify(cfg.State, cfg.RootDir)
   410  }
   411  
   412  func (cfg *PrivValidatorConfig) AreSecurityOptionsPresent() bool {
   413  	switch {
   414  	case cfg.RootCA == "":
   415  		return false
   416  	case cfg.ClientKey == "":
   417  		return false
   418  	case cfg.ClientCertificate == "":
   419  		return false
   420  	default:
   421  		return true
   422  	}
   423  }
   424  
   425  //-----------------------------------------------------------------------------
   426  // RPCConfig
   427  
   428  // RPCConfig defines the configuration options for the Tendermint RPC server
   429  type RPCConfig struct {
   430  	RootDir string `mapstructure:"home"`
   431  
   432  	// TCP or UNIX socket address for the RPC server to listen on
   433  	ListenAddress string `mapstructure:"laddr"`
   434  
   435  	// A list of origins a cross-domain request can be executed from.
   436  	// If the special '*' value is present in the list, all origins will be allowed.
   437  	// An origin may contain a wildcard (*) to replace 0 or more characters (i.e.: http://*.domain.com).
   438  	// Only one wildcard can be used per origin.
   439  	CORSAllowedOrigins []string `mapstructure:"cors-allowed-origins"`
   440  
   441  	// A list of methods the client is allowed to use with cross-domain requests.
   442  	CORSAllowedMethods []string `mapstructure:"cors-allowed-methods"`
   443  
   444  	// A list of non simple headers the client is allowed to use with cross-domain requests.
   445  	CORSAllowedHeaders []string `mapstructure:"cors-allowed-headers"`
   446  
   447  	// TCP or UNIX socket address for the gRPC server to listen on
   448  	// NOTE: This server only supports /broadcast_tx_commit
   449  	// Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
   450  	GRPCListenAddress string `mapstructure:"grpc-laddr"`
   451  
   452  	// Maximum number of simultaneous connections.
   453  	// Does not include RPC (HTTP&WebSocket) connections. See max-open-connections
   454  	// If you want to accept a larger number than the default, make sure
   455  	// you increase your OS limits.
   456  	// 0 - unlimited.
   457  	// Deprecated: gRPC in the RPC layer of Tendermint will be removed in 0.36.
   458  	GRPCMaxOpenConnections int `mapstructure:"grpc-max-open-connections"`
   459  
   460  	// Activate unsafe RPC commands like /dial-persistent-peers and /unsafe-flush-mempool
   461  	Unsafe bool `mapstructure:"unsafe"`
   462  
   463  	// Maximum number of simultaneous connections (including WebSocket).
   464  	// Does not include gRPC connections. See grpc-max-open-connections
   465  	// If you want to accept a larger number than the default, make sure
   466  	// you increase your OS limits.
   467  	// 0 - unlimited.
   468  	// Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
   469  	// 1024 - 40 - 10 - 50 = 924 = ~900
   470  	MaxOpenConnections int `mapstructure:"max-open-connections"`
   471  
   472  	// Maximum number of unique clientIDs that can /subscribe
   473  	// If you're using /broadcast_tx_commit, set to the estimated maximum number
   474  	// of broadcast_tx_commit calls per block.
   475  	MaxSubscriptionClients int `mapstructure:"max-subscription-clients"`
   476  
   477  	// Maximum number of unique queries a given client can /subscribe to
   478  	// If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set
   479  	// to the estimated maximum number of broadcast_tx_commit calls per block.
   480  	MaxSubscriptionsPerClient int `mapstructure:"max-subscriptions-per-client"`
   481  
   482  	// How long to wait for a tx to be committed during /broadcast_tx_commit
   483  	// WARNING: Using a value larger than 10s will result in increasing the
   484  	// global HTTP write timeout, which applies to all connections and endpoints.
   485  	// See https://github.com/number571/tendermint/issues/3435
   486  	TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout-broadcast-tx-commit"`
   487  
   488  	// Maximum size of request body, in bytes
   489  	MaxBodyBytes int64 `mapstructure:"max-body-bytes"`
   490  
   491  	// Maximum size of request header, in bytes
   492  	MaxHeaderBytes int `mapstructure:"max-header-bytes"`
   493  
   494  	// The path to a file containing certificate that is used to create the HTTPS server.
   495  	// Might be either absolute path or path related to Tendermint's config directory.
   496  	//
   497  	// If the certificate is signed by a certificate authority,
   498  	// the certFile should be the concatenation of the server's certificate, any intermediates,
   499  	// and the CA's certificate.
   500  	//
   501  	// NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
   502  	// Otherwise, HTTP server is run.
   503  	TLSCertFile string `mapstructure:"tls-cert-file"`
   504  
   505  	// The path to a file containing matching private key that is used to create the HTTPS server.
   506  	// Might be either absolute path or path related to tendermint's config directory.
   507  	//
   508  	// NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
   509  	// Otherwise, HTTP server is run.
   510  	TLSKeyFile string `mapstructure:"tls-key-file"`
   511  
   512  	// pprof listen address (https://golang.org/pkg/net/http/pprof)
   513  	PprofListenAddress string `mapstructure:"pprof-laddr"`
   514  }
   515  
   516  // DefaultRPCConfig returns a default configuration for the RPC server
   517  func DefaultRPCConfig() *RPCConfig {
   518  	return &RPCConfig{
   519  		ListenAddress:          "tcp://127.0.0.1:26657",
   520  		CORSAllowedOrigins:     []string{},
   521  		CORSAllowedMethods:     []string{http.MethodHead, http.MethodGet, http.MethodPost},
   522  		CORSAllowedHeaders:     []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
   523  		GRPCListenAddress:      "",
   524  		GRPCMaxOpenConnections: 900,
   525  
   526  		Unsafe:             false,
   527  		MaxOpenConnections: 900,
   528  
   529  		MaxSubscriptionClients:    100,
   530  		MaxSubscriptionsPerClient: 5,
   531  		TimeoutBroadcastTxCommit:  10 * time.Second,
   532  
   533  		MaxBodyBytes:   int64(1000000), // 1MB
   534  		MaxHeaderBytes: 1 << 20,        // same as the net/http default
   535  
   536  		TLSCertFile: "",
   537  		TLSKeyFile:  "",
   538  	}
   539  }
   540  
   541  // TestRPCConfig returns a configuration for testing the RPC server
   542  func TestRPCConfig() *RPCConfig {
   543  	cfg := DefaultRPCConfig()
   544  	cfg.ListenAddress = "tcp://127.0.0.1:36657"
   545  	cfg.GRPCListenAddress = "tcp://127.0.0.1:36658"
   546  	cfg.Unsafe = true
   547  	return cfg
   548  }
   549  
   550  // ValidateBasic performs basic validation (checking param bounds, etc.) and
   551  // returns an error if any check fails.
   552  func (cfg *RPCConfig) ValidateBasic() error {
   553  	if cfg.GRPCMaxOpenConnections < 0 {
   554  		return errors.New("grpc-max-open-connections can't be negative")
   555  	}
   556  	if cfg.MaxOpenConnections < 0 {
   557  		return errors.New("max-open-connections can't be negative")
   558  	}
   559  	if cfg.MaxSubscriptionClients < 0 {
   560  		return errors.New("max-subscription-clients can't be negative")
   561  	}
   562  	if cfg.MaxSubscriptionsPerClient < 0 {
   563  		return errors.New("max-subscriptions-per-client can't be negative")
   564  	}
   565  	if cfg.TimeoutBroadcastTxCommit < 0 {
   566  		return errors.New("timeout-broadcast-tx-commit can't be negative")
   567  	}
   568  	if cfg.MaxBodyBytes < 0 {
   569  		return errors.New("max-body-bytes can't be negative")
   570  	}
   571  	if cfg.MaxHeaderBytes < 0 {
   572  		return errors.New("max-header-bytes can't be negative")
   573  	}
   574  	return nil
   575  }
   576  
   577  // IsCorsEnabled returns true if cross-origin resource sharing is enabled.
   578  func (cfg *RPCConfig) IsCorsEnabled() bool {
   579  	return len(cfg.CORSAllowedOrigins) != 0
   580  }
   581  
   582  func (cfg RPCConfig) KeyFile() string {
   583  	path := cfg.TLSKeyFile
   584  	if filepath.IsAbs(path) {
   585  		return path
   586  	}
   587  	return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
   588  }
   589  
   590  func (cfg RPCConfig) CertFile() string {
   591  	path := cfg.TLSCertFile
   592  	if filepath.IsAbs(path) {
   593  		return path
   594  	}
   595  	return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
   596  }
   597  
   598  func (cfg RPCConfig) IsTLSEnabled() bool {
   599  	return cfg.TLSCertFile != "" && cfg.TLSKeyFile != ""
   600  }
   601  
   602  //-----------------------------------------------------------------------------
   603  // P2PConfig
   604  
   605  // P2PConfig defines the configuration options for the Tendermint peer-to-peer networking layer
   606  type P2PConfig struct { //nolint: maligned
   607  	RootDir string `mapstructure:"home"`
   608  
   609  	// Address to listen for incoming connections
   610  	ListenAddress string `mapstructure:"laddr"`
   611  
   612  	// Address to advertise to peers for them to dial
   613  	ExternalAddress string `mapstructure:"external-address"`
   614  
   615  	// Comma separated list of seed nodes to connect to
   616  	// We only use these if we can’t connect to peers in the addrbook
   617  	// NOTE: not used by the new PEX reactor. Please use BootstrapPeers instead.
   618  	// TODO: Remove once p2p refactor is complete
   619  	// ref: https://github.com/number571/tendermint/issues/5670
   620  	Seeds string `mapstructure:"seeds"`
   621  
   622  	// Comma separated list of peers to be added to the peer store
   623  	// on startup. Either BootstrapPeers or PersistentPeers are
   624  	// needed for peer discovery
   625  	BootstrapPeers string `mapstructure:"bootstrap-peers"`
   626  
   627  	// Comma separated list of nodes to keep persistent connections to
   628  	PersistentPeers string `mapstructure:"persistent-peers"`
   629  
   630  	// UPNP port forwarding
   631  	UPNP bool `mapstructure:"upnp"`
   632  
   633  	// Path to address book
   634  	AddrBook string `mapstructure:"addr-book-file"`
   635  
   636  	// Set true for strict address routability rules
   637  	// Set false for private or local networks
   638  	AddrBookStrict bool `mapstructure:"addr-book-strict"`
   639  
   640  	// Maximum number of inbound peers
   641  	//
   642  	// TODO: Remove once p2p refactor is complete in favor of MaxConnections.
   643  	// ref: https://github.com/number571/tendermint/issues/5670
   644  	MaxNumInboundPeers int `mapstructure:"max-num-inbound-peers"`
   645  
   646  	// Maximum number of outbound peers to connect to, excluding persistent peers.
   647  	//
   648  	// TODO: Remove once p2p refactor is complete in favor of MaxConnections.
   649  	// ref: https://github.com/number571/tendermint/issues/5670
   650  	MaxNumOutboundPeers int `mapstructure:"max-num-outbound-peers"`
   651  
   652  	// MaxConnections defines the maximum number of connected peers (inbound and
   653  	// outbound).
   654  	MaxConnections uint16 `mapstructure:"max-connections"`
   655  
   656  	// MaxIncomingConnectionAttempts rate limits the number of incoming connection
   657  	// attempts per IP address.
   658  	MaxIncomingConnectionAttempts uint `mapstructure:"max-incoming-connection-attempts"`
   659  
   660  	// List of node IDs, to which a connection will be (re)established ignoring any existing limits
   661  	UnconditionalPeerIDs string `mapstructure:"unconditional-peer-ids"`
   662  
   663  	// Maximum pause when redialing a persistent peer (if zero, exponential backoff is used)
   664  	PersistentPeersMaxDialPeriod time.Duration `mapstructure:"persistent-peers-max-dial-period"`
   665  
   666  	// Time to wait before flushing messages out on the connection
   667  	FlushThrottleTimeout time.Duration `mapstructure:"flush-throttle-timeout"`
   668  
   669  	// Maximum size of a message packet payload, in bytes
   670  	MaxPacketMsgPayloadSize int `mapstructure:"max-packet-msg-payload-size"`
   671  
   672  	// Rate at which packets can be sent, in bytes/second
   673  	SendRate int64 `mapstructure:"send-rate"`
   674  
   675  	// Rate at which packets can be received, in bytes/second
   676  	RecvRate int64 `mapstructure:"recv-rate"`
   677  
   678  	// Set true to enable the peer-exchange reactor
   679  	PexReactor bool `mapstructure:"pex"`
   680  
   681  	// Comma separated list of peer IDs to keep private (will not be gossiped to
   682  	// other peers)
   683  	PrivatePeerIDs string `mapstructure:"private-peer-ids"`
   684  
   685  	// Toggle to disable guard against peers connecting from the same ip.
   686  	AllowDuplicateIP bool `mapstructure:"allow-duplicate-ip"`
   687  
   688  	// Peer connection configuration.
   689  	HandshakeTimeout time.Duration `mapstructure:"handshake-timeout"`
   690  	DialTimeout      time.Duration `mapstructure:"dial-timeout"`
   691  
   692  	// Testing params.
   693  	// Force dial to fail
   694  	TestDialFail bool `mapstructure:"test-dial-fail"`
   695  
   696  	// DisableLegacy is used mostly for testing to enable or disable the legacy
   697  	// P2P stack.
   698  	DisableLegacy bool `mapstructure:"disable-legacy"`
   699  
   700  	// Makes it possible to configure which queue backend the p2p
   701  	// layer uses. Options are: "fifo", "priority" and "wdrr",
   702  	// with the default being "fifo".
   703  	QueueType string `mapstructure:"queue-type"`
   704  }
   705  
   706  // DefaultP2PConfig returns a default configuration for the peer-to-peer layer
   707  func DefaultP2PConfig() *P2PConfig {
   708  	return &P2PConfig{
   709  		ListenAddress:                 "tcp://0.0.0.0:26656",
   710  		ExternalAddress:               "",
   711  		UPNP:                          false,
   712  		AddrBook:                      defaultAddrBookPath,
   713  		AddrBookStrict:                true,
   714  		MaxNumInboundPeers:            40,
   715  		MaxNumOutboundPeers:           10,
   716  		MaxConnections:                64,
   717  		MaxIncomingConnectionAttempts: 100,
   718  		PersistentPeersMaxDialPeriod:  0 * time.Second,
   719  		FlushThrottleTimeout:          100 * time.Millisecond,
   720  		// The MTU (Maximum Transmission Unit) for Ethernet is 1500 bytes.
   721  		// The IP header and the TCP header take up 20 bytes each at least (unless
   722  		// optional header fields are used) and thus the max for (non-Jumbo frame)
   723  		// Ethernet is 1500 - 20 -20 = 1460
   724  		// Source: https://stackoverflow.com/a/3074427/820520
   725  
   726  		// APPEND:
   727  		// In new version Tendermint is UseLegacy
   728  		// where default value is false! 
   729  		DisableLegacy: true,
   730  
   731  		MaxPacketMsgPayloadSize: 1400,
   732  		SendRate:                5120000, // 5 mB/s
   733  		RecvRate:                5120000, // 5 mB/s
   734  		PexReactor:              true,
   735  		AllowDuplicateIP:        false,
   736  		HandshakeTimeout:        20 * time.Second,
   737  		DialTimeout:             3 * time.Second,
   738  		TestDialFail:            false,
   739  		QueueType:               "priority",
   740  	}
   741  }
   742  
   743  // TestP2PConfig returns a configuration for testing the peer-to-peer layer
   744  func TestP2PConfig() *P2PConfig {
   745  	cfg := DefaultP2PConfig()
   746  	cfg.ListenAddress = "tcp://127.0.0.1:36656"
   747  	cfg.FlushThrottleTimeout = 10 * time.Millisecond
   748  	cfg.AllowDuplicateIP = true
   749  	return cfg
   750  }
   751  
   752  // AddrBookFile returns the full path to the address book
   753  func (cfg *P2PConfig) AddrBookFile() string {
   754  	return rootify(cfg.AddrBook, cfg.RootDir)
   755  }
   756  
   757  // ValidateBasic performs basic validation (checking param bounds, etc.) and
   758  // returns an error if any check fails.
   759  func (cfg *P2PConfig) ValidateBasic() error {
   760  	if cfg.MaxNumInboundPeers < 0 {
   761  		return errors.New("max-num-inbound-peers can't be negative")
   762  	}
   763  	if cfg.MaxNumOutboundPeers < 0 {
   764  		return errors.New("max-num-outbound-peers can't be negative")
   765  	}
   766  	if cfg.FlushThrottleTimeout < 0 {
   767  		return errors.New("flush-throttle-timeout can't be negative")
   768  	}
   769  	if cfg.PersistentPeersMaxDialPeriod < 0 {
   770  		return errors.New("persistent-peers-max-dial-period can't be negative")
   771  	}
   772  	if cfg.MaxPacketMsgPayloadSize < 0 {
   773  		return errors.New("max-packet-msg-payload-size can't be negative")
   774  	}
   775  	if cfg.SendRate < 0 {
   776  		return errors.New("send-rate can't be negative")
   777  	}
   778  	if cfg.RecvRate < 0 {
   779  		return errors.New("recv-rate can't be negative")
   780  	}
   781  	return nil
   782  }
   783  
   784  //-----------------------------------------------------------------------------
   785  // MempoolConfig
   786  
   787  // MempoolConfig defines the configuration options for the Tendermint mempool.
   788  type MempoolConfig struct {
   789  	Version   string `mapstructure:"version"`
   790  	RootDir   string `mapstructure:"home"`
   791  	Recheck   bool   `mapstructure:"recheck"`
   792  	Broadcast bool   `mapstructure:"broadcast"`
   793  
   794  	// Maximum number of transactions in the mempool
   795  	Size int `mapstructure:"size"`
   796  
   797  	// Limit the total size of all txs in the mempool.
   798  	// This only accounts for raw transactions (e.g. given 1MB transactions and
   799  	// max-txs-bytes=5MB, mempool will only accept 5 transactions).
   800  	MaxTxsBytes int64 `mapstructure:"max-txs-bytes"`
   801  
   802  	// Size of the cache (used to filter transactions we saw earlier) in transactions
   803  	CacheSize int `mapstructure:"cache-size"`
   804  
   805  	// Do not remove invalid transactions from the cache (default: false)
   806  	// Set to true if it's not possible for any invalid transaction to become
   807  	// valid again in the future.
   808  	KeepInvalidTxsInCache bool `mapstructure:"keep-invalid-txs-in-cache"`
   809  
   810  	// Maximum size of a single transaction
   811  	// NOTE: the max size of a tx transmitted over the network is {max-tx-bytes}.
   812  	MaxTxBytes int `mapstructure:"max-tx-bytes"`
   813  
   814  	// Maximum size of a batch of transactions to send to a peer
   815  	// Including space needed by encoding (one varint per transaction).
   816  	// XXX: Unused due to https://github.com/number571/tendermint/issues/5796
   817  	MaxBatchBytes int `mapstructure:"max-batch-bytes"`
   818  
   819  	// TTLDuration, if non-zero, defines the maximum amount of time a transaction
   820  	// can exist for in the mempool.
   821  	//
   822  	// Note, if TTLNumBlocks is also defined, a transaction will be removed if it
   823  	// has existed in the mempool at least TTLNumBlocks number of blocks or if it's
   824  	// insertion time into the mempool is beyond TTLDuration.
   825  	TTLDuration time.Duration `mapstructure:"ttl-duration"`
   826  
   827  	// TTLNumBlocks, if non-zero, defines the maximum number of blocks a transaction
   828  	// can exist for in the mempool.
   829  	//
   830  	// Note, if TTLDuration is also defined, a transaction will be removed if it
   831  	// has existed in the mempool at least TTLNumBlocks number of blocks or if
   832  	// it's insertion time into the mempool is beyond TTLDuration.
   833  	TTLNumBlocks int64 `mapstructure:"ttl-num-blocks"`
   834  }
   835  
   836  // DefaultMempoolConfig returns a default configuration for the Tendermint mempool.
   837  func DefaultMempoolConfig() *MempoolConfig {
   838  	return &MempoolConfig{
   839  		Version:   MempoolV1,
   840  		Recheck:   true,
   841  		Broadcast: true,
   842  		// Each signature verification takes .5ms, Size reduced until we implement
   843  		// ABCI Recheck
   844  		Size:         5000,
   845  		MaxTxsBytes:  1024 * 1024 * 1024, // 1GB
   846  		CacheSize:    10000,
   847  		MaxTxBytes:   1024 * 1024, // 1MB
   848  		TTLDuration:  0 * time.Second,
   849  		TTLNumBlocks: 0,
   850  	}
   851  }
   852  
   853  // TestMempoolConfig returns a configuration for testing the Tendermint mempool
   854  func TestMempoolConfig() *MempoolConfig {
   855  	cfg := DefaultMempoolConfig()
   856  	cfg.CacheSize = 1000
   857  	return cfg
   858  }
   859  
   860  // ValidateBasic performs basic validation (checking param bounds, etc.) and
   861  // returns an error if any check fails.
   862  func (cfg *MempoolConfig) ValidateBasic() error {
   863  	if cfg.Size < 0 {
   864  		return errors.New("size can't be negative")
   865  	}
   866  	if cfg.MaxTxsBytes < 0 {
   867  		return errors.New("max-txs-bytes can't be negative")
   868  	}
   869  	if cfg.CacheSize < 0 {
   870  		return errors.New("cache-size can't be negative")
   871  	}
   872  	if cfg.MaxTxBytes < 0 {
   873  		return errors.New("max-tx-bytes can't be negative")
   874  	}
   875  	if cfg.TTLDuration < 0 {
   876  		return errors.New("ttl-duration can't be negative")
   877  	}
   878  	if cfg.TTLNumBlocks < 0 {
   879  		return errors.New("ttl-num-blocks can't be negative")
   880  	}
   881  
   882  	return nil
   883  }
   884  
   885  //-----------------------------------------------------------------------------
   886  // StateSyncConfig
   887  
   888  // StateSyncConfig defines the configuration for the Tendermint state sync service
   889  type StateSyncConfig struct {
   890  	Enable              bool          `mapstructure:"enable"`
   891  	TempDir             string        `mapstructure:"temp-dir"`
   892  	RPCServers          []string      `mapstructure:"rpc-servers"`
   893  	TrustPeriod         time.Duration `mapstructure:"trust-period"`
   894  	TrustHeight         int64         `mapstructure:"trust-height"`
   895  	TrustHash           string        `mapstructure:"trust-hash"`
   896  	DiscoveryTime       time.Duration `mapstructure:"discovery-time"`
   897  	ChunkRequestTimeout time.Duration `mapstructure:"chunk-request-timeout"`
   898  	Fetchers            int32         `mapstructure:"fetchers"`
   899  }
   900  
   901  func (cfg *StateSyncConfig) TrustHashBytes() []byte {
   902  	// validated in ValidateBasic, so we can safely panic here
   903  	bytes, err := hex.DecodeString(cfg.TrustHash)
   904  	if err != nil {
   905  		panic(err)
   906  	}
   907  	return bytes
   908  }
   909  
   910  // DefaultStateSyncConfig returns a default configuration for the state sync service
   911  func DefaultStateSyncConfig() *StateSyncConfig {
   912  	return &StateSyncConfig{
   913  		TrustPeriod:         168 * time.Hour,
   914  		DiscoveryTime:       15 * time.Second,
   915  		ChunkRequestTimeout: 15 * time.Second,
   916  		Fetchers:            4,
   917  	}
   918  }
   919  
   920  // TestFastSyncConfig returns a default configuration for the state sync service
   921  func TestStateSyncConfig() *StateSyncConfig {
   922  	return DefaultStateSyncConfig()
   923  }
   924  
   925  // ValidateBasic performs basic validation.
   926  func (cfg *StateSyncConfig) ValidateBasic() error {
   927  	if cfg.Enable {
   928  		if len(cfg.RPCServers) == 0 {
   929  			return errors.New("rpc-servers is required")
   930  		}
   931  
   932  		if len(cfg.RPCServers) < 2 {
   933  			return errors.New("at least two rpc-servers entries is required")
   934  		}
   935  
   936  		for _, server := range cfg.RPCServers {
   937  			if len(server) == 0 {
   938  				return errors.New("found empty rpc-servers entry")
   939  			}
   940  		}
   941  
   942  		if cfg.DiscoveryTime != 0 && cfg.DiscoveryTime < 5*time.Second {
   943  			return errors.New("discovery time must be 0s or greater than five seconds")
   944  		}
   945  
   946  		if cfg.TrustPeriod <= 0 {
   947  			return errors.New("trusted-period is required")
   948  		}
   949  
   950  		if cfg.TrustHeight <= 0 {
   951  			return errors.New("trusted-height is required")
   952  		}
   953  
   954  		if len(cfg.TrustHash) == 0 {
   955  			return errors.New("trusted-hash is required")
   956  		}
   957  
   958  		_, err := hex.DecodeString(cfg.TrustHash)
   959  		if err != nil {
   960  			return fmt.Errorf("invalid trusted-hash: %w", err)
   961  		}
   962  
   963  		if cfg.ChunkRequestTimeout < 5*time.Second {
   964  			return errors.New("chunk-request-timeout must be at least 5 seconds")
   965  		}
   966  
   967  		if cfg.Fetchers <= 0 {
   968  			return errors.New("fetchers is required")
   969  		}
   970  	}
   971  
   972  	return nil
   973  }
   974  
   975  //-----------------------------------------------------------------------------
   976  // FastSyncConfig
   977  
   978  // FastSyncConfig defines the configuration for the Tendermint fast sync service
   979  type FastSyncConfig struct {
   980  	Version string `mapstructure:"version"`
   981  }
   982  
   983  // DefaultFastSyncConfig returns a default configuration for the fast sync service
   984  func DefaultFastSyncConfig() *FastSyncConfig {
   985  	return &FastSyncConfig{
   986  		Version: BlockchainV0,
   987  	}
   988  }
   989  
   990  // TestFastSyncConfig returns a default configuration for the fast sync.
   991  func TestFastSyncConfig() *FastSyncConfig {
   992  	return DefaultFastSyncConfig()
   993  }
   994  
   995  // ValidateBasic performs basic validation.
   996  func (cfg *FastSyncConfig) ValidateBasic() error {
   997  	switch cfg.Version {
   998  	case BlockchainV0:
   999  		return nil
  1000  	case BlockchainV2:
  1001  		return errors.New("fastsync version v2 is no longer supported. Please use v0")
  1002  	default:
  1003  		return fmt.Errorf("unknown fastsync version %s", cfg.Version)
  1004  	}
  1005  }
  1006  
  1007  //-----------------------------------------------------------------------------
  1008  // ConsensusConfig
  1009  
  1010  // ConsensusConfig defines the configuration for the Tendermint consensus service,
  1011  // including timeouts and details about the WAL and the block structure.
  1012  type ConsensusConfig struct {
  1013  	RootDir string `mapstructure:"home"`
  1014  	WalPath string `mapstructure:"wal-file"`
  1015  	walFile string // overrides WalPath if set
  1016  
  1017  	// TODO: remove timeout configs, these should be global not local
  1018  	// How long we wait for a proposal block before prevoting nil
  1019  	TimeoutPropose time.Duration `mapstructure:"timeout-propose"`
  1020  	// How much timeout-propose increases with each round
  1021  	TimeoutProposeDelta time.Duration `mapstructure:"timeout-propose-delta"`
  1022  	// How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
  1023  	TimeoutPrevote time.Duration `mapstructure:"timeout-prevote"`
  1024  	// How much the timeout-prevote increases with each round
  1025  	TimeoutPrevoteDelta time.Duration `mapstructure:"timeout-prevote-delta"`
  1026  	// How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
  1027  	TimeoutPrecommit time.Duration `mapstructure:"timeout-precommit"`
  1028  	// How much the timeout-precommit increases with each round
  1029  	TimeoutPrecommitDelta time.Duration `mapstructure:"timeout-precommit-delta"`
  1030  	// How long we wait after committing a block, before starting on the new
  1031  	// height (this gives us a chance to receive some more precommits, even
  1032  	// though we already have +2/3).
  1033  	TimeoutCommit time.Duration `mapstructure:"timeout-commit"`
  1034  
  1035  	// Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
  1036  	SkipTimeoutCommit bool `mapstructure:"skip-timeout-commit"`
  1037  
  1038  	// EmptyBlocks mode and possible interval between empty blocks
  1039  	CreateEmptyBlocks         bool          `mapstructure:"create-empty-blocks"`
  1040  	CreateEmptyBlocksInterval time.Duration `mapstructure:"create-empty-blocks-interval"`
  1041  
  1042  	// Reactor sleep duration parameters
  1043  	PeerGossipSleepDuration     time.Duration `mapstructure:"peer-gossip-sleep-duration"`
  1044  	PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer-query-maj23-sleep-duration"`
  1045  
  1046  	DoubleSignCheckHeight int64 `mapstructure:"double-sign-check-height"`
  1047  }
  1048  
  1049  // DefaultConsensusConfig returns a default configuration for the consensus service
  1050  func DefaultConsensusConfig() *ConsensusConfig {
  1051  	return &ConsensusConfig{
  1052  		WalPath:                     filepath.Join(defaultDataDir, "cs.wal", "wal"),
  1053  		TimeoutPropose:              3000 * time.Millisecond,
  1054  		TimeoutProposeDelta:         500 * time.Millisecond,
  1055  		TimeoutPrevote:              1000 * time.Millisecond,
  1056  		TimeoutPrevoteDelta:         500 * time.Millisecond,
  1057  		TimeoutPrecommit:            1000 * time.Millisecond,
  1058  		TimeoutPrecommitDelta:       500 * time.Millisecond,
  1059  		TimeoutCommit:               1000 * time.Millisecond,
  1060  		SkipTimeoutCommit:           false,
  1061  		CreateEmptyBlocks:           true,
  1062  		CreateEmptyBlocksInterval:   0 * time.Second,
  1063  		PeerGossipSleepDuration:     100 * time.Millisecond,
  1064  		PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
  1065  		DoubleSignCheckHeight:       int64(0),
  1066  	}
  1067  }
  1068  
  1069  // TestConsensusConfig returns a configuration for testing the consensus service
  1070  func TestConsensusConfig() *ConsensusConfig {
  1071  	cfg := DefaultConsensusConfig()
  1072  	cfg.TimeoutPropose = 40 * time.Millisecond
  1073  	cfg.TimeoutProposeDelta = 1 * time.Millisecond
  1074  	cfg.TimeoutPrevote = 10 * time.Millisecond
  1075  	cfg.TimeoutPrevoteDelta = 1 * time.Millisecond
  1076  	cfg.TimeoutPrecommit = 10 * time.Millisecond
  1077  	cfg.TimeoutPrecommitDelta = 1 * time.Millisecond
  1078  	cfg.TimeoutCommit = 10 * time.Millisecond
  1079  	cfg.SkipTimeoutCommit = true
  1080  	cfg.PeerGossipSleepDuration = 5 * time.Millisecond
  1081  	cfg.PeerQueryMaj23SleepDuration = 250 * time.Millisecond
  1082  	cfg.DoubleSignCheckHeight = int64(0)
  1083  	return cfg
  1084  }
  1085  
  1086  // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
  1087  func (cfg *ConsensusConfig) WaitForTxs() bool {
  1088  	return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
  1089  }
  1090  
  1091  // Propose returns the amount of time to wait for a proposal
  1092  func (cfg *ConsensusConfig) Propose(round int32) time.Duration {
  1093  	return time.Duration(
  1094  		cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round),
  1095  	) * time.Nanosecond
  1096  }
  1097  
  1098  // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
  1099  func (cfg *ConsensusConfig) Prevote(round int32) time.Duration {
  1100  	return time.Duration(
  1101  		cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round),
  1102  	) * time.Nanosecond
  1103  }
  1104  
  1105  // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
  1106  func (cfg *ConsensusConfig) Precommit(round int32) time.Duration {
  1107  	return time.Duration(
  1108  		cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round),
  1109  	) * time.Nanosecond
  1110  }
  1111  
  1112  // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits
  1113  // for a single block (ie. a commit).
  1114  func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
  1115  	return t.Add(cfg.TimeoutCommit)
  1116  }
  1117  
  1118  // WalFile returns the full path to the write-ahead log file
  1119  func (cfg *ConsensusConfig) WalFile() string {
  1120  	if cfg.walFile != "" {
  1121  		return cfg.walFile
  1122  	}
  1123  	return rootify(cfg.WalPath, cfg.RootDir)
  1124  }
  1125  
  1126  // SetWalFile sets the path to the write-ahead log file
  1127  func (cfg *ConsensusConfig) SetWalFile(walFile string) {
  1128  	cfg.walFile = walFile
  1129  }
  1130  
  1131  // ValidateBasic performs basic validation (checking param bounds, etc.) and
  1132  // returns an error if any check fails.
  1133  func (cfg *ConsensusConfig) ValidateBasic() error {
  1134  	if cfg.TimeoutPropose < 0 {
  1135  		return errors.New("timeout-propose can't be negative")
  1136  	}
  1137  	if cfg.TimeoutProposeDelta < 0 {
  1138  		return errors.New("timeout-propose-delta can't be negative")
  1139  	}
  1140  	if cfg.TimeoutPrevote < 0 {
  1141  		return errors.New("timeout-prevote can't be negative")
  1142  	}
  1143  	if cfg.TimeoutPrevoteDelta < 0 {
  1144  		return errors.New("timeout-prevote-delta can't be negative")
  1145  	}
  1146  	if cfg.TimeoutPrecommit < 0 {
  1147  		return errors.New("timeout-precommit can't be negative")
  1148  	}
  1149  	if cfg.TimeoutPrecommitDelta < 0 {
  1150  		return errors.New("timeout-precommit-delta can't be negative")
  1151  	}
  1152  	if cfg.TimeoutCommit < 0 {
  1153  		return errors.New("timeout-commit can't be negative")
  1154  	}
  1155  	if cfg.CreateEmptyBlocksInterval < 0 {
  1156  		return errors.New("create-empty-blocks-interval can't be negative")
  1157  	}
  1158  	if cfg.PeerGossipSleepDuration < 0 {
  1159  		return errors.New("peer-gossip-sleep-duration can't be negative")
  1160  	}
  1161  	if cfg.PeerQueryMaj23SleepDuration < 0 {
  1162  		return errors.New("peer-query-maj23-sleep-duration can't be negative")
  1163  	}
  1164  	if cfg.DoubleSignCheckHeight < 0 {
  1165  		return errors.New("double-sign-check-height can't be negative")
  1166  	}
  1167  	return nil
  1168  }
  1169  
  1170  //-----------------------------------------------------------------------------
  1171  // TxIndexConfig
  1172  // Remember that Event has the following structure:
  1173  // type: [
  1174  //  key: value,
  1175  //  ...
  1176  // ]
  1177  //
  1178  // CompositeKeys are constructed by `type.key`
  1179  // TxIndexConfig defines the configuration for the transaction indexer,
  1180  // including composite keys to index.
  1181  type TxIndexConfig struct {
  1182  	// The backend database list to back the indexer.
  1183  	// If list contains `null`, meaning no indexer service will be used.
  1184  	//
  1185  	// Options:
  1186  	//   1) "null" - no indexer services.
  1187  	//   2) "kv" (default) - the simplest possible indexer,
  1188  	//      backed by key-value storage (defaults to levelDB; see DBBackend).
  1189  	//   3) "psql" - the indexer services backed by PostgreSQL.
  1190  	Indexer []string `mapstructure:"indexer"`
  1191  
  1192  	// The PostgreSQL connection configuration, the connection format:
  1193  	// postgresql://<user>:<password>@<host>:<port>/<db>?<opts>
  1194  	PsqlConn string `mapstructure:"psql-conn"`
  1195  }
  1196  
  1197  // DefaultTxIndexConfig returns a default configuration for the transaction indexer.
  1198  func DefaultTxIndexConfig() *TxIndexConfig {
  1199  	return &TxIndexConfig{
  1200  		Indexer: []string{"kv"},
  1201  	}
  1202  }
  1203  
  1204  // TestTxIndexConfig returns a default configuration for the transaction indexer.
  1205  func TestTxIndexConfig() *TxIndexConfig {
  1206  	return DefaultTxIndexConfig()
  1207  }
  1208  
  1209  //-----------------------------------------------------------------------------
  1210  // InstrumentationConfig
  1211  
  1212  // InstrumentationConfig defines the configuration for metrics reporting.
  1213  type InstrumentationConfig struct {
  1214  	// When true, Prometheus metrics are served under /metrics on
  1215  	// PrometheusListenAddr.
  1216  	// Check out the documentation for the list of available metrics.
  1217  	Prometheus bool `mapstructure:"prometheus"`
  1218  
  1219  	// Address to listen for Prometheus collector(s) connections.
  1220  	PrometheusListenAddr string `mapstructure:"prometheus-listen-addr"`
  1221  
  1222  	// Maximum number of simultaneous connections.
  1223  	// If you want to accept a larger number than the default, make sure
  1224  	// you increase your OS limits.
  1225  	// 0 - unlimited.
  1226  	MaxOpenConnections int `mapstructure:"max-open-connections"`
  1227  
  1228  	// Instrumentation namespace.
  1229  	Namespace string `mapstructure:"namespace"`
  1230  }
  1231  
  1232  // DefaultInstrumentationConfig returns a default configuration for metrics
  1233  // reporting.
  1234  func DefaultInstrumentationConfig() *InstrumentationConfig {
  1235  	return &InstrumentationConfig{
  1236  		Prometheus:           false,
  1237  		PrometheusListenAddr: ":26660",
  1238  		MaxOpenConnections:   3,
  1239  		Namespace:            "tendermint",
  1240  	}
  1241  }
  1242  
  1243  // TestInstrumentationConfig returns a default configuration for metrics
  1244  // reporting.
  1245  func TestInstrumentationConfig() *InstrumentationConfig {
  1246  	return DefaultInstrumentationConfig()
  1247  }
  1248  
  1249  // ValidateBasic performs basic validation (checking param bounds, etc.) and
  1250  // returns an error if any check fails.
  1251  func (cfg *InstrumentationConfig) ValidateBasic() error {
  1252  	if cfg.MaxOpenConnections < 0 {
  1253  		return errors.New("max-open-connections can't be negative")
  1254  	}
  1255  	return nil
  1256  }
  1257  
  1258  //-----------------------------------------------------------------------------
  1259  // Utils
  1260  
  1261  // helper function to make config creation independent of root dir
  1262  func rootify(path, root string) string {
  1263  	if filepath.IsAbs(path) {
  1264  		return path
  1265  	}
  1266  	return filepath.Join(root, path)
  1267  }
  1268  
  1269  //-----------------------------------------------------------------------------
  1270  // Moniker
  1271  
  1272  var defaultMoniker = getDefaultMoniker()
  1273  
  1274  // getDefaultMoniker returns a default moniker, which is the host name. If runtime
  1275  // fails to get the host name, "anonymous" will be returned.
  1276  func getDefaultMoniker() string {
  1277  	moniker, err := os.Hostname()
  1278  	if err != nil {
  1279  		moniker = "anonymous"
  1280  	}
  1281  	return moniker
  1282  }