func DefaultConsensusConfig() *ConsensusConfig {
	return &ConsensusConfig{
		WalPath:                     filepath.Join(defaultDataDir, "cs.wal", "wal"),
		TimeoutPropose:              3000 * time.Millisecond,
		TimeoutProposeDelta:         500 * time.Millisecond,
		TimeoutPrevote:              1000 * time.Millisecond,
		TimeoutPrevoteDelta:         500 * time.Millisecond,
		TimeoutPrecommit:            1000 * time.Millisecond,
		TimeoutPrecommitDelta:       500 * time.Millisecond,
		TimeoutCommit:               1000 * time.Millisecond,
		SkipTimeoutCommit:           false,
		CreateEmptyBlocks:           true,
		CreateEmptyBlocksInterval:   0 * time.Second,
		PeerGossipSleepDuration:     100 * time.Millisecond,
		PeerQueryMaj23SleepDuration: 2000 * time.Millisecond,
		DoubleSignCheckHeight:       int64(0),
	}
}
DefaultConsensusConfig returns a default configuration for the consensus service
package config
import (
	"encoding/hex"
	"errors"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"time"
	"github.com/line/ostracon/privval"
	"github.com/line/tm-db/v2/metadb"
)
const (
	FuzzModeDrop = iota
	FuzzModeDelay
	LogFormatPlain = "plain"
	LogFormatJSON = "json"
	DefaultLogLevel = "info"
	DefaultDBBackend = "goleveldb"
)
var (
	DefaultOstraconDir = ".ostracon"
	defaultConfigDir   = "config"
	defaultDataDir     = "data"
	defaultConfigFileName  = "config.toml"
	defaultGenesisJSONName = "genesis.json"
	defaultPrivValKeyName   = "priv_validator_key.json"
	defaultPrivValStateName = "priv_validator_state.json"
	defaultNodeKeyName  = "node_key.json"
	defaultAddrBookName = "addrbook.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)
	defaultAddrBookPath = filepath.Join(defaultConfigDir, defaultAddrBookName)
)
type Config struct {
	BaseConfig `mapstructure:",squash"`
	RPC             *RPCConfig             `mapstructure:"rpc"`
	P2P             *P2PConfig             `mapstructure:"p2p"`
	Mempool         *MempoolConfig         `mapstructure:"mempool"`
	StateSync       *StateSyncConfig       `mapstructure:"statesync"`
	FastSync        *FastSyncConfig        `mapstructure:"fastsync"`
	Consensus       *ConsensusConfig       `mapstructure:"consensus"`
	TxIndex         *TxIndexConfig         `mapstructure:"tx_index"`
	Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"`
}
func DefaultConfig() *Config {
	return &Config{
		BaseConfig:      DefaultBaseConfig(),
		RPC:             DefaultRPCConfig(),
		P2P:             DefaultP2PConfig(),
		Mempool:         DefaultMempoolConfig(),
		StateSync:       DefaultStateSyncConfig(),
		FastSync:        DefaultFastSyncConfig(),
		Consensus:       DefaultConsensusConfig(),
		TxIndex:         DefaultTxIndexConfig(),
		Instrumentation: DefaultInstrumentationConfig(),
	}
}
func TestConfig() *Config {
	return &Config{
		BaseConfig:      TestBaseConfig(),
		RPC:             TestRPCConfig(),
		P2P:             TestP2PConfig(),
		Mempool:         TestMempoolConfig(),
		StateSync:       TestStateSyncConfig(),
		FastSync:        TestFastSyncConfig(),
		Consensus:       TestConsensusConfig(),
		TxIndex:         TestTxIndexConfig(),
		Instrumentation: TestInstrumentationConfig(),
	}
}
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
	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.P2P.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [p2p] 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.FastSync.ValidateBasic(); err != nil {
		return fmt.Errorf("error in [fastsync] 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"`
	FastSyncMode bool `mapstructure:"fast_sync"`
	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"`
	PrivValidatorKey string `mapstructure:"priv_validator_key_file"`
	PrivValidatorState string `mapstructure:"priv_validator_state_file"`
	PrivValidatorListenAddr string `mapstructure:"priv_validator_laddr"`
	NodeKey string `mapstructure:"node_key_file"`
	ABCI string `mapstructure:"abci"`
	FilterPeers bool `mapstructure:"filter_peers"`  
	PrivKeyType string `mapstructure:"priv_key_type"`
}
func DefaultBaseConfig() BaseConfig {
	dbs := metadb.AvailableDBBackends()
	defaultDBBackend := DefaultDBBackend
	for _, b := range dbs {
		defaultDBBackend = string(b)
		if defaultDBBackend == DefaultDBBackend {
			break
		}
	}
	return BaseConfig{
		Genesis:            defaultGenesisJSONPath,
		PrivValidatorKey:   defaultPrivValKeyPath,
		PrivValidatorState: defaultPrivValStatePath,
		NodeKey:            defaultNodeKeyPath,
		Moniker:            defaultMoniker,
		ProxyApp:           "tcp://127.0.0.1:26658",
		ABCI:               "socket",
		LogLevel:           DefaultLogLevel,
		LogFormat:          LogFormatPlain,
		FastSyncMode:       true,
		FilterPeers:        false,
		DBBackend:          defaultDBBackend,
		DBPath:             "data",
		PrivKeyType:        privval.PrivKeyTypeEd25519,
	}
}
func TestBaseConfig() BaseConfig {
	cfg := DefaultBaseConfig()
	cfg.chainID = "ostracon_test"
	cfg.ProxyApp = "kvstore"
	cfg.FastSyncMode = false
	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) PrivValidatorKeyFile() string {
	return rootify(cfg.PrivValidatorKey, cfg.RootDir)
}
func (cfg BaseConfig) PrivValidatorStateFile() string {
	return rootify(cfg.PrivValidatorState, cfg.RootDir)
}
func (cfg BaseConfig) NodeKeyFile() string {
	return rootify(cfg.NodeKey, cfg.RootDir)
}
func (cfg BaseConfig) DBDir() string {
	return rootify(cfg.DBPath, cfg.RootDir)
}
func (cfg BaseConfig) PrivValidatorKeyType() string {
	return cfg.PrivKeyType
}
func (cfg BaseConfig) ValidateBasic() error {
	switch cfg.LogFormat {
	case LogFormatPlain, LogFormatJSON:
	default:
		return errors.New("unknown log_format (must be 'plain' or 'json')")
	}
	return nil
}
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"`
	GRPCListenAddress string `mapstructure:"grpc_laddr"`
	GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"`
	Unsafe bool `mapstructure:"unsafe"`
	MaxOpenConnections int `mapstructure:"max_open_connections"`
	ReadTimeout time.Duration `mapstructure:"read_timeout"`
	WriteTimeout time.Duration `mapstructure:"write_timeout"`
	IdleTimeout time.Duration `mapstructure:"idle_timeout"`
	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"},
		GRPCListenAddress:      "",
		GRPCMaxOpenConnections: 900,
		Unsafe:             false,
		MaxOpenConnections: 900,
		ReadTimeout:        10 * time.Second,
		WriteTimeout:       10 * time.Second,
		IdleTimeout:        60 * time.Second,
		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.GRPCListenAddress = "tcp://127.0.0.1:36658"
	cfg.Unsafe = true
	return cfg
}
func (cfg *RPCConfig) ValidateBasic() error {
	if cfg.GRPCMaxOpenConnections < 0 {
		return errors.New("grpc_max_open_connections can't be negative")
	}
	if cfg.MaxOpenConnections < 0 {
		return errors.New("max_open_connections can't be negative")
	}
	if cfg.ReadTimeout < 0 {
		return errors.New("read_timeout can't be negative")
	}
	if cfg.WriteTimeout < 0 {
		return errors.New("write_timeout can't be negative")
	}
	if cfg.IdleTimeout < 0 {
		return errors.New("idle_timeout 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"`
	PersistentPeers string `mapstructure:"persistent_peers"`
	UPNP bool `mapstructure:"upnp"`
	AddrBook string `mapstructure:"addr_book_file"`
	AddrBookStrict bool `mapstructure:"addr_book_strict"`
	MaxNumInboundPeers int `mapstructure:"max_num_inbound_peers"`
	MaxNumOutboundPeers int `mapstructure:"max_num_outbound_peers"`
	UnconditionalPeerIDs string `mapstructure:"unconditional_peer_ids"`
	PersistentPeersMaxDialPeriod time.Duration `mapstructure:"persistent_peers_max_dial_period"`
	FlushThrottleTimeout time.Duration `mapstructure:"flush_throttle_timeout"`
	MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
	SendRate int64 `mapstructure:"send_rate"`
	RecvRate int64 `mapstructure:"recv_rate"`
	PexReactor bool `mapstructure:"pex"`
	SeedMode bool `mapstructure:"seed_mode"`
	PrivatePeerIDs string `mapstructure:"private_peer_ids"`
	AllowDuplicateIP bool `mapstructure:"allow_duplicate_ip"`
	HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"`
	DialTimeout      time.Duration `mapstructure:"dial_timeout"`
	RecvAsync bool `mapstructure:"recv_async"`
	PexRecvBufSize        int `mapstructure:"pex_recv_buf_size"`
	EvidenceRecvBufSize   int `mapstructure:"evidence_recv_buf_size"`
	MempoolRecvBufSize    int `mapstructure:"mempool_recv_buf_size"`
	ConsensusRecvBufSize  int `mapstructure:"consensus_recv_buf_size"`
	BlockchainRecvBufSize int `mapstructure:"blockchain_recv_buf_size"`
	StatesyncRecvBufSize  int `mapstructure:"statesync_recv_buf_size"`
	TestDialFail bool `mapstructure:"test_dial_fail"`
	TestFuzz       bool            `mapstructure:"test_fuzz"`
	TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"`
}
func DefaultP2PConfig() *P2PConfig {
	return &P2PConfig{
		ListenAddress:                "tcp://0.0.0.0:26656",
		ExternalAddress:              "",
		UPNP:                         false,
		AddrBook:                     defaultAddrBookPath,
		AddrBookStrict:               true,
		MaxNumInboundPeers:           40,
		MaxNumOutboundPeers:          10,
		PersistentPeersMaxDialPeriod: 0 * time.Second,
		FlushThrottleTimeout:         100 * time.Millisecond,
		MaxPacketMsgPayloadSize:      1024,     
		SendRate:                     5120000,  
		RecvRate:                     5120000,  
		PexReactor:                   true,
		SeedMode:                     false,
		AllowDuplicateIP:             false,
		HandshakeTimeout:             20 * time.Second,
		DialTimeout:                  3 * time.Second,
		RecvAsync:                    true,
		PexRecvBufSize:               1000,
		EvidenceRecvBufSize:          1000,
		MempoolRecvBufSize:           1000,
		ConsensusRecvBufSize:         4000,
		BlockchainRecvBufSize:        1000,
		StatesyncRecvBufSize:         1000,
		TestDialFail:                 false,
		TestFuzz:                     false,
		TestFuzzConfig:               DefaultFuzzConnConfig(),
	}
}
func TestP2PConfig() *P2PConfig {
	cfg := DefaultP2PConfig()
	cfg.ListenAddress = "tcp://127.0.0.1:36656"
	cfg.FlushThrottleTimeout = 10 * time.Millisecond
	cfg.AllowDuplicateIP = true
	return cfg
}
func (cfg *P2PConfig) AddrBookFile() string {
	return rootify(cfg.AddrBook, cfg.RootDir)
}
func (cfg *P2PConfig) ValidateBasic() error {
	if cfg.MaxNumInboundPeers < 0 {
		return errors.New("max_num_inbound_peers can't be negative")
	}
	if cfg.MaxNumOutboundPeers < 0 {
		return errors.New("max_num_outbound_peers can't be negative")
	}
	if cfg.FlushThrottleTimeout < 0 {
		return errors.New("flush_throttle_timeout can't be negative")
	}
	if cfg.PersistentPeersMaxDialPeriod < 0 {
		return errors.New("persistent_peers_max_dial_period can't be negative")
	}
	if cfg.MaxPacketMsgPayloadSize < 0 {
		return errors.New("max_packet_msg_payload_size can't be negative")
	}
	if cfg.SendRate < 0 {
		return errors.New("send_rate can't be negative")
	}
	if cfg.RecvRate < 0 {
		return errors.New("recv_rate can't be negative")
	}
	return nil
}
type FuzzConnConfig struct {
	Mode         int
	MaxDelay     time.Duration
	ProbDropRW   float64
	ProbDropConn float64
	ProbSleep    float64
}
func DefaultFuzzConnConfig() *FuzzConnConfig {
	return &FuzzConnConfig{
		Mode:         FuzzModeDrop,
		MaxDelay:     3 * time.Second,
		ProbDropRW:   0.2,
		ProbDropConn: 0.00,
		ProbSleep:    0.00,
	}
}
type MempoolConfig struct {
	RootDir   string `mapstructure:"home"`
	Recheck   bool   `mapstructure:"recheck"`
	Broadcast bool   `mapstructure:"broadcast"`
	WalPath   string `mapstructure:"wal_dir"`
	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"`
}
func DefaultMempoolConfig() *MempoolConfig {
	return &MempoolConfig{
		Recheck:   true,
		Broadcast: true,
		WalPath:   "",
		Size:        5000,
		MaxTxsBytes: 1024 * 1024 * 1024,  
		CacheSize:   10000,
		MaxTxBytes:  1024 * 1024,  
	}
}
func TestMempoolConfig() *MempoolConfig {
	cfg := DefaultMempoolConfig()
	cfg.CacheSize = 1000
	return cfg
}
func (cfg *MempoolConfig) WalDir() string {
	return rootify(cfg.WalPath, cfg.RootDir)
}
func (cfg *MempoolConfig) WalEnabled() bool {
	return cfg.WalPath != ""
}
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")
	}
	return nil
}
type StateSyncConfig struct {
	Enable        bool          `mapstructure:"enable"`
	TempDir       string        `mapstructure:"temp_dir"`
	RPCServers    []string      `mapstructure:"rpc_servers"`
	TrustPeriod   time.Duration `mapstructure:"trust_period"`
	TrustHeight   int64         `mapstructure:"trust_height"`
	TrustHash     string        `mapstructure:"trust_hash"`
	DiscoveryTime time.Duration `mapstructure:"discovery_time"`
}
func (cfg *StateSyncConfig) TrustHashBytes() []byte {
	bytes, err := hex.DecodeString(cfg.TrustHash)
	if err != nil {
		panic(err)
	}
	return bytes
}
func DefaultStateSyncConfig() *StateSyncConfig {
	return &StateSyncConfig{
		TrustPeriod:   168 * time.Hour,
		DiscoveryTime: 15 * time.Second,
	}
}
func TestStateSyncConfig() *StateSyncConfig {
	return DefaultStateSyncConfig()
}
func (cfg *StateSyncConfig) ValidateBasic() error {
	if cfg.Enable {
		if len(cfg.RPCServers) == 0 {
			return errors.New("rpc_servers is required")
		}
		if len(cfg.RPCServers) < 2 {
			return errors.New("at least two rpc_servers entries is required")
		}
		for _, server := range cfg.RPCServers {
			if len(server) == 0 {
				return errors.New("found empty rpc_servers entry")
			}
		}
		if cfg.TrustPeriod <= 0 {
			return errors.New("trusted_period is required")
		}
		if cfg.TrustHeight <= 0 {
			return errors.New("trusted_height is required")
		}
		if len(cfg.TrustHash) == 0 {
			return errors.New("trusted_hash is required")
		}
		_, err := hex.DecodeString(cfg.TrustHash)
		if err != nil {
			return fmt.Errorf("invalid trusted_hash: %w", err)
		}
	}
	return nil
}
type FastSyncConfig struct {
	Version string `mapstructure:"version"`
}
func DefaultFastSyncConfig() *FastSyncConfig {
	return &FastSyncConfig{
		Version: "v0",
	}
}
func TestFastSyncConfig() *FastSyncConfig {
	return DefaultFastSyncConfig()
}
func (cfg *FastSyncConfig) ValidateBasic() error {
	switch cfg.Version {
	case "v0":
		return nil
	case "v1":
		return nil
	case "v2":
		return nil
	default:
		return fmt.Errorf("unknown fastsync version %s", cfg.Version)
	}
}
type ConsensusConfig struct {
	RootDir string `mapstructure:"home"`
	WalPath string `mapstructure:"wal_file"`
	walFile string  
	TimeoutPropose time.Duration `mapstructure:"timeout_propose"`
	TimeoutProposeDelta time.Duration `mapstructure:"timeout_propose_delta"`
	TimeoutPrevote time.Duration `mapstructure:"timeout_prevote"`
	TimeoutPrevoteDelta time.Duration `mapstructure:"timeout_prevote_delta"`
	TimeoutPrecommit time.Duration `mapstructure:"timeout_precommit"`
	TimeoutPrecommitDelta time.Duration `mapstructure:"timeout_precommit_delta"`
	TimeoutCommit time.Duration `mapstructure:"timeout_commit"`
	SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"`
	CreateEmptyBlocks         bool          `mapstructure:"create_empty_blocks"`
	CreateEmptyBlocksInterval time.Duration `mapstructure:"create_empty_blocks_interval"`
	MaxTxs int64 `mapstructure:"max_txs"`
	PeerGossipSleepDuration     time.Duration `mapstructure:"peer_gossip_sleep_duration"`
	PeerQueryMaj23SleepDuration time.Duration `mapstructure:"peer_query_maj23_sleep_duration"`
	DoubleSignCheckHeight int64 `mapstructure:"double_sign_check_height"`
}