func DefaultStateSyncConfig() *StateSyncConfig {
	return &StateSyncConfig{
		TrustPeriod:         168 * time.Hour,
		DiscoveryTime:       15 * time.Second,
		ChunkRequestTimeout: 15 * time.Second,
		Fetchers:            4,
	}
}
DefaultStateSyncConfig returns a default configuration for the state sync service
package config
import (
	"encoding/hex"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"time"
	tmjson "github.com/tendermint/tendermint/libs/json"
	"github.com/tendermint/tendermint/libs/log"
	tmos "github.com/tendermint/tendermint/libs/os"
	"github.com/tendermint/tendermint/types"
)
const (
	FuzzModeDrop = iota
	FuzzModeDelay
	DefaultLogLevel = "info"
	ModeFull      = "full"
	ModeValidator = "validator"
	ModeSeed      = "seed"
	BlockSyncV0 = "v0"
	MempoolV0 = "v0"
	MempoolV1 = "v1"
)
var (
	DefaultTendermintDir = ".tendermint"
	defaultConfigDir     = "config"
	defaultDataDir       = "data"
	defaultConfigFileName  = "config.toml"
	defaultGenesisJSONName = "genesis.json"
	defaultMode             = ModeFull
	defaultPrivValKeyName   = "priv_validator_key.json"
	defaultPrivValStateName = "priv_validator_state.json"
	defaultNodeKeyName = "node_key.json"
	defaultConfigFilePath   = filepath.Join(defaultConfigDir, defaultConfigFileName)
	defaultGenesisJSONPath  = filepath.Join(defaultConfigDir, defaultGenesisJSONName)
	defaultPrivValKeyPath   = filepath.Join(defaultConfigDir, defaultPrivValKeyName)
	defaultPrivValStatePath = filepath.Join(defaultDataDir, defaultPrivValStateName)
	defaultNodeKeyPath = filepath.Join(defaultConfigDir, defaultNodeKeyName)
)
type Config struct {
	BaseConfig `mapstructure:",squash"`
	RPC             *RPCConfig             `mapstructure:"rpc"`
	P2P             *P2PConfig             `mapstructure:"p2p"`
	Mempool         *MempoolConfig         `mapstructure:"mempool"`
	StateSync       *StateSyncConfig       `mapstructure:"statesync"`
	BlockSync       *BlockSyncConfig       `mapstructure:"blocksync"`
	Consensus       *ConsensusConfig       `mapstructure:"consensus"`
	TxIndex         *TxIndexConfig         `mapstructure:"tx-index"`
	Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
	PrivValidator   *PrivValidatorConfig   `mapstructure:"priv-validator"`
}
func DefaultConfig() *Config {
	return &Config{
		BaseConfig:      DefaultBaseConfig(),
		RPC:             DefaultRPCConfig(),
		P2P:             DefaultP2PConfig(),
		Mempool:         DefaultMempoolConfig(),
		StateSync:       DefaultStateSyncConfig(),
		BlockSync:       DefaultBlockSyncConfig(),
		Consensus:       DefaultConsensusConfig(),
		TxIndex:         DefaultTxIndexConfig(),
		Instrumentation: DefaultInstrumentationConfig(),
		PrivValidator:   DefaultPrivValidatorConfig(),
	}
}
func DefaultValidatorConfig() *Config {
	cfg := DefaultConfig()
	cfg.Mode = ModeValidator
	return cfg
}
func TestConfig() *Config {
	return &Config{
		BaseConfig:      TestBaseConfig(),
		RPC:             TestRPCConfig(),
		P2P:             TestP2PConfig(),
		Mempool:         TestMempoolConfig(),
		StateSync:       TestStateSyncConfig(),
		BlockSync:       TestBlockSyncConfig(),
		Consensus:       TestConsensusConfig(),
		TxIndex:         TestTxIndexConfig(),
		Instrumentation: TestInstrumentationConfig(),
		PrivValidator:   DefaultPrivValidatorConfig(),
	}
}
func (cfg *Config) SetRoot(root string) *Config {
	cfg.BaseConfig.RootDir = root
	cfg.RPC.RootDir = root
	cfg.P2P.RootDir = root
	cfg.Mempool.RootDir = root
	cfg.Consensus.RootDir = root
	cfg.PrivValidator.RootDir = root
	return cfg
}
func (cfg *Config) ValidateBasic() error {
	if err := cfg.BaseConfig.ValidateBasic(); err != nil {
		return err
	}
	if err := cfg.RPC.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [rpc] section: %w", err)
	}
	if err := cfg.Mempool.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [mempool] section: %w", err)
	}
	if err := cfg.StateSync.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [statesync] section: %w", err)
	}
	if err := cfg.BlockSync.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [blocksync] section: %w", err)
	}
	if err := cfg.Consensus.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [consensus] section: %w", err)
	}
	if err := cfg.Instrumentation.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [instrumentation] section: %w", err)
	}
	return nil
}
type BaseConfig struct {  
	chainID string
	RootDir string `mapstructure:"home"`
	ProxyApp string `mapstructure:"proxy-app"`
	Moniker string `mapstructure:"moniker"`
	Mode string `mapstructure:"mode"`
	DBBackend string `mapstructure:"db-backend"`
	DBPath string `mapstructure:"db-dir"`
	LogLevel string `mapstructure:"log-level"`
	LogFormat string `mapstructure:"log-format"`
	Genesis string `mapstructure:"genesis-file"`
	NodeKey string `mapstructure:"node-key-file"`
	ABCI string `mapstructure:"abci"`
	FilterPeers bool `mapstructure:"filter-peers"`  
	Other map[string]interface{} `mapstructure:",remain"`
}
func DefaultBaseConfig() BaseConfig {
	return BaseConfig{
		Genesis:     defaultGenesisJSONPath,
		NodeKey:     defaultNodeKeyPath,
		Mode:        defaultMode,
		Moniker:     defaultMoniker,
		ProxyApp:    "tcp://127.0.0.1:26658",
		ABCI:        "socket",
		LogLevel:    DefaultLogLevel,
		LogFormat:   log.LogFormatPlain,
		FilterPeers: false,
		DBBackend:   "goleveldb",
		DBPath:      "data",
	}
}
func TestBaseConfig() BaseConfig {
	cfg := DefaultBaseConfig()
	cfg.chainID = "tendermint_test"
	cfg.Mode = ModeValidator
	cfg.ProxyApp = "kvstore"
	cfg.DBBackend = "memdb"
	return cfg
}
func (cfg BaseConfig) ChainID() string {
	return cfg.chainID
}
func (cfg BaseConfig) GenesisFile() string {
	return rootify(cfg.Genesis, cfg.RootDir)
}
func (cfg BaseConfig) NodeKeyFile() string {
	return rootify(cfg.NodeKey, cfg.RootDir)
}
func (cfg BaseConfig) LoadNodeKeyID() (types.NodeID, error) {
	jsonBytes, err := ioutil.ReadFile(cfg.NodeKeyFile())
	if err != nil {
		return "", err
	}
	nodeKey := types.NodeKey{}
	err = tmjson.Unmarshal(jsonBytes, &nodeKey)
	if err != nil {
		return "", err
	}
	nodeKey.ID = types.NodeIDFromPubKey(nodeKey.PubKey())
	return nodeKey.ID, nil
}
func (cfg BaseConfig) LoadOrGenNodeKeyID() (types.NodeID, error) {
	if tmos.FileExists(cfg.NodeKeyFile()) {
		nodeKey, err := cfg.LoadNodeKeyID()
		if err != nil {
			return "", err
		}
		return nodeKey, nil
	}
	nodeKey := types.GenNodeKey()
	if err := nodeKey.SaveAs(cfg.NodeKeyFile()); err != nil {
		return "", err
	}
	return nodeKey.ID, nil
}
func (cfg BaseConfig) DBDir() string {
	return rootify(cfg.DBPath, cfg.RootDir)
}
func (cfg BaseConfig) ValidateBasic() error {
	switch cfg.LogFormat {
	case log.LogFormatJSON, log.LogFormatText, log.LogFormatPlain:
	default:
		return errors.New("unknown log format (must be 'plain', 'text' or 'json')")
	}
	switch cfg.Mode {
	case ModeFull, ModeValidator, ModeSeed:
	case "":
		return errors.New("no mode has been set")
	default:
		return fmt.Errorf("unknown mode: %v", cfg.Mode)
	}
	if fs, ok := cfg.Other["fastsync"]; ok {
		if _, ok := fs.(map[string]interface{}); ok {
			return fmt.Errorf("a configuration section named 'fastsync' was found in the " +
				"configuration file. The 'fastsync' section has been renamed to " +
				"'blocksync', please update the 'fastsync' field in your configuration file to 'blocksync'")
		}
	}
	if fs, ok := cfg.Other["fast-sync"]; ok {
		if fs != "" {
			return fmt.Errorf("a parameter named 'fast-sync' was found in the " +
				"configuration file. The parameter to enable or disable quickly syncing with a blockchain" +
				"has moved to the [blocksync] section of the configuration file as blocksync.enable. " +
				"Please move the 'fast-sync' field in your configuration file to 'blocksync.enable'")
		}
	}
	return nil
}
type PrivValidatorConfig struct {
	RootDir string `mapstructure:"home"`
	Key string `mapstructure:"key-file"`
	State string `mapstructure:"state-file"`
	ListenAddr string `mapstructure:"laddr"`
	ClientCertificate string `mapstructure:"client-certificate-file"`
	ClientKey string `mapstructure:"client-key-file"`
	RootCA string `mapstructure:"root-ca-file"`
}
func DefaultPrivValidatorConfig() *PrivValidatorConfig {
	return &PrivValidatorConfig{
		Key:   defaultPrivValKeyPath,
		State: defaultPrivValStatePath,
	}
}
func (cfg *PrivValidatorConfig) ClientKeyFile() string {
	return rootify(cfg.ClientKey, cfg.RootDir)
}
func (cfg *PrivValidatorConfig) ClientCertificateFile() string {
	return rootify(cfg.ClientCertificate, cfg.RootDir)
}
func (cfg *PrivValidatorConfig) RootCAFile() string {
	return rootify(cfg.RootCA, cfg.RootDir)
}
func (cfg *PrivValidatorConfig) KeyFile() string {
	return rootify(cfg.Key, cfg.RootDir)
}
func (cfg *PrivValidatorConfig) StateFile() string {
	return rootify(cfg.State, cfg.RootDir)
}
func (cfg *PrivValidatorConfig) AreSecurityOptionsPresent() bool {
	switch {
	case cfg.RootCA == "":
		return false
	case cfg.ClientKey == "":
		return false
	case cfg.ClientCertificate == "":
		return false
	default:
		return true
	}
}
type RPCConfig struct {
	RootDir string `mapstructure:"home"`
	ListenAddress string `mapstructure:"laddr"`
	CORSAllowedOrigins []string `mapstructure:"cors-allowed-origins"`
	CORSAllowedMethods []string `mapstructure:"cors-allowed-methods"`
	CORSAllowedHeaders []string `mapstructure:"cors-allowed-headers"`
	Unsafe bool `mapstructure:"unsafe"`
	MaxOpenConnections int `mapstructure:"max-open-connections"`
	MaxSubscriptionClients int `mapstructure:"max-subscription-clients"`
	MaxSubscriptionsPerClient int `mapstructure:"max-subscriptions-per-client"`
	TimeoutBroadcastTxCommit time.Duration `mapstructure:"timeout-broadcast-tx-commit"`
	MaxBodyBytes int64 `mapstructure:"max-body-bytes"`
	MaxHeaderBytes int `mapstructure:"max-header-bytes"`
	TLSCertFile string `mapstructure:"tls-cert-file"`
	TLSKeyFile string `mapstructure:"tls-key-file"`
	PprofListenAddress string `mapstructure:"pprof-laddr"`
}
func DefaultRPCConfig() *RPCConfig {
	return &RPCConfig{
		ListenAddress:      "tcp://127.0.0.1:26657",
		CORSAllowedOrigins: []string{},
		CORSAllowedMethods: []string{http.MethodHead, http.MethodGet, http.MethodPost},
		CORSAllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"},
		Unsafe:             false,
		MaxOpenConnections: 900,
		MaxSubscriptionClients:    100,
		MaxSubscriptionsPerClient: 5,
		TimeoutBroadcastTxCommit:  10 * time.Second,
		MaxBodyBytes:   int64(1000000),  
		MaxHeaderBytes: 1 << 20,         
		TLSCertFile: "",
		TLSKeyFile:  "",
	}
}
func TestRPCConfig() *RPCConfig {
	cfg := DefaultRPCConfig()
	cfg.ListenAddress = "tcp://127.0.0.1:36657"
	cfg.Unsafe = true
	return cfg
}
func (cfg *RPCConfig) ValidateBasic() error {
	if cfg.MaxOpenConnections < 0 {
		return errors.New("max-open-connections can't be negative")
	}
	if cfg.MaxSubscriptionClients < 0 {
		return errors.New("max-subscription-clients can't be negative")
	}
	if cfg.MaxSubscriptionsPerClient < 0 {
		return errors.New("max-subscriptions-per-client can't be negative")
	}
	if cfg.TimeoutBroadcastTxCommit < 0 {
		return errors.New("timeout-broadcast-tx-commit can't be negative")
	}
	if cfg.MaxBodyBytes < 0 {
		return errors.New("max-body-bytes can't be negative")
	}
	if cfg.MaxHeaderBytes < 0 {
		return errors.New("max-header-bytes can't be negative")
	}
	return nil
}
func (cfg *RPCConfig) IsCorsEnabled() bool {
	return len(cfg.CORSAllowedOrigins) != 0
}
func (cfg RPCConfig) KeyFile() string {
	path := cfg.TLSKeyFile
	if filepath.IsAbs(path) {
		return path
	}
	return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
}
func (cfg RPCConfig) CertFile() string {
	path := cfg.TLSCertFile
	if filepath.IsAbs(path) {
		return path
	}
	return rootify(filepath.Join(defaultConfigDir, path), cfg.RootDir)
}
func (cfg RPCConfig) IsTLSEnabled() bool {
	return cfg.TLSCertFile != "" && cfg.TLSKeyFile != ""
}
type P2PConfig struct {  
	RootDir string `mapstructure:"home"`
	ListenAddress string `mapstructure:"laddr"`
	ExternalAddress string `mapstructure:"external-address"`
	Seeds string `mapstructure:"seeds"`
	BootstrapPeers string `mapstructure:"bootstrap-peers"`
	PersistentPeers string `mapstructure:"persistent-peers"`
	UPNP bool `mapstructure:"upnp"`
	MaxConnections uint16 `mapstructure:"max-connections"`
	MaxIncomingConnectionAttempts uint `mapstructure:"max-incoming-connection-attempts"`
	PexReactor bool `mapstructure:"pex"`
	PrivatePeerIDs string `mapstructure:"private-peer-ids"`
	AllowDuplicateIP bool `mapstructure:"allow-duplicate-ip"`
	HandshakeTimeout time.Duration `mapstructure:"handshake-timeout"`
	DialTimeout      time.Duration `mapstructure:"dial-timeout"`
	TestDialFail bool `mapstructure:"test-dial-fail"`
	QueueType string `mapstructure:"queue-type"`
}
func DefaultP2PConfig() *P2PConfig {
	return &P2PConfig{
		ListenAddress:                 "tcp://0.0.0.0:26656",
		ExternalAddress:               "",
		UPNP:                          false,
		MaxConnections:                64,
		MaxIncomingConnectionAttempts: 100,
		PexReactor:                    true,
		AllowDuplicateIP:              false,
		HandshakeTimeout:              20 * time.Second,
		DialTimeout:                   3 * time.Second,
		TestDialFail:                  false,
		QueueType:                     "priority",
	}
}
func TestP2PConfig() *P2PConfig {
	cfg := DefaultP2PConfig()
	cfg.ListenAddress = "tcp://127.0.0.1:36656"
	cfg.AllowDuplicateIP = true
	return cfg
}
type MempoolConfig struct {
	Version   string `mapstructure:"version"`
	RootDir   string `mapstructure:"home"`
	Recheck   bool   `mapstructure:"recheck"`
	Broadcast bool   `mapstructure:"broadcast"`
	Size int `mapstructure:"size"`
	MaxTxsBytes int64 `mapstructure:"max-txs-bytes"`
	CacheSize int `mapstructure:"cache-size"`
	KeepInvalidTxsInCache bool `mapstructure:"keep-invalid-txs-in-cache"`
	MaxTxBytes int `mapstructure:"max-tx-bytes"`
	MaxBatchBytes int `mapstructure:"max-batch-bytes"`
	TTLDuration time.Duration `mapstructure:"ttl-duration"`
	TTLNumBlocks int64 `mapstructure:"ttl-num-blocks"`
}
func DefaultMempoolConfig() *MempoolConfig {
	return &MempoolConfig{
		Version:   MempoolV1,
		Recheck:   true,
		Broadcast: true,
		Size:         5000,
		MaxTxsBytes:  1024 * 1024 * 1024,  
		CacheSize:    10000,
		MaxTxBytes:   1024 * 1024,  
		TTLDuration:  0 * time.Second,
		TTLNumBlocks: 0,
	}
}
func TestMempoolConfig() *MempoolConfig {
	cfg := DefaultMempoolConfig()
	cfg.CacheSize = 1000
	return cfg
}
func (cfg *MempoolConfig) ValidateBasic() error {
	if cfg.Size < 0 {
		return errors.New("size can't be negative")
	}
	if cfg.MaxTxsBytes < 0 {
		return errors.New("max-txs-bytes can't be negative")
	}
	if cfg.CacheSize < 0 {
		return errors.New("cache-size can't be negative")
	}
	if cfg.MaxTxBytes < 0 {
		return errors.New("max-tx-bytes can't be negative")
	}
	if cfg.TTLDuration < 0 {
		return errors.New("ttl-duration can't be negative")
	}
	if cfg.TTLNumBlocks < 0 {
		return errors.New("ttl-num-blocks can't be negative")
	}
	return nil
}
type StateSyncConfig struct {
	Enable bool `mapstructure:"enable"`
	UseP2P bool `mapstructure:"use-p2p"`
	RPCServers []string `mapstructure:"rpc-servers"`
	TrustHeight int64  `mapstructure:"trust-height"`
	TrustHash   string `mapstructure:"trust-hash"`
	TrustPeriod time.Duration `mapstructure:"trust-period"`
	DiscoveryTime time.Duration `mapstructure:"discovery-time"`
	TempDir string `mapstructure:"temp-dir"`
	ChunkRequestTimeout time.Duration `mapstructure:"chunk-request-timeout"`
	Fetchers int32 `mapstructure:"fetchers"`
}
func (cfg *StateSyncConfig) TrustHashBytes() []byte {
	bytes, err := hex.DecodeString(cfg.TrustHash)
	if err != nil {
		panic(err)
	}
	return bytes
}