diff --git a/.mockery.yaml b/.mockery.yaml index 5f455e0c3..cb836e05d 100644 --- a/.mockery.yaml +++ b/.mockery.yaml @@ -3,15 +3,19 @@ mockname: "{{.InterfaceNameCamel}}" filename: "{{.InterfaceNameSnake}}.go" outpkg: "mocks" packages: - pkg.berachain.dev/polaris/cosmos/txpool: + pkg.berachain.dev/polaris/cosmos/config: config: + recursive: True + with-expecter: true all: True + pkg.berachain.dev/polaris/cosmos/txpool: + config: recursive: True with-expecter: true + all: True pkg.berachain.dev/polaris/eth/core/state: config: - all: True recursive: True with-expecter: true - + all: True \ No newline at end of file diff --git a/codecov.yml b/codecov.yml index ae65c1e9f..9a619e026 100644 --- a/codecov.yml +++ b/codecov.yml @@ -22,7 +22,7 @@ coverage: status: project: default: - target: 50% + target: 45% patch: off comment: diff --git a/cosmos/config/config.go b/cosmos/config/config.go index 7bf471377..7f672f7c6 100644 --- a/cosmos/config/config.go +++ b/cosmos/config/config.go @@ -21,18 +21,13 @@ package config import ( - "fmt" "math/big" - "time" - - "github.com/spf13/cast" "github.com/cosmos/cosmos-sdk/client/flags" servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/ethereum/go-ethereum/node" - "pkg.berachain.dev/polaris/eth/common" "pkg.berachain.dev/polaris/eth/polar" ) @@ -60,352 +55,411 @@ func MustReadConfigFromAppOpts(opts servertypes.AppOptions) *Config { return cfg } -//nolint:funlen,gocognit,gocyclo,cyclop // TODO break up later. func ReadConfigFromAppOpts(opts servertypes.AppOptions) (*Config, error) { + return readConfigFromAppOptsParser(AppOptionsParser{AppOptions: opts}) +} + +//nolint:funlen,gocognit,gocyclo,cyclop // TODO break up later. +func readConfigFromAppOptsParser(parser AppOptionsParser) (*Config, error) { var err error var val int64 conf := &Config{} - // Define little error handler. - var handleError = func(err error, flag string) error { - if err != nil { - return fmt.Errorf("error while reading configuration: %w flag: %s", err, flag) - } - return nil + // Polar settings + if conf.Polar.RPCGasCap, err = + parser.GetUint64(flagRPCGasCap); err != nil { + return nil, err } - - // Wrapping casting functions to return both value and error - getCommonAddressList := func(key string) []common.Address { - addresses := make([]common.Address, 0) - addressStrs := cast.ToStringSlice(opts.Get(key)) - for _, addressStr := range addressStrs { - address := common.HexToAddress(addressStr) - addresses = append(addresses, address) - } - return addresses - } - getString := func(key string) (string, error) { return cast.ToStringE(opts.Get(key)) } - getInt := func(key string) (int, error) { return cast.ToIntE(opts.Get(key)) } - getInt64 := func(key string) (int64, error) { return cast.ToInt64E(opts.Get(key)) } - getUint64 := func(key string) (uint64, error) { return cast.ToUint64E(opts.Get(key)) } - getUint64Ptr := func(key string) (*uint64, error) { - if num, _ := cast.ToStringE((opts.Get(key))); num == "" || num == "null" { - return nil, nil //nolint:nilnil // intentional. - } - - num, _err := cast.ToUint64E((opts.Get(key))) - if _err != nil { - return nil, _err - } - return &num, nil + if conf.Polar.RPCEVMTimeout, err = + parser.GetTimeDuration(flagRPCEvmTimeout); err != nil { + return nil, err } - getBigInt := func(key string) (*big.Int, error) { - str, _err := cast.ToStringE(opts.Get(key)) - if str == "" || str == "null" { - return nil, nil //nolint:nilnil // intentional. - } - if _err != nil { - return nil, _err - } - num, ok := new(big.Int).SetString(str, 10) //nolint:gomnd // base 10. - if !ok { - return nil, fmt.Errorf("invalid big.Int string: %s", str) - } - return num, nil + if conf.Polar.RPCTxFeeCap, err = + parser.GetFloat64(flagRPCTxFeeCap); err != nil { + return nil, err } - getFloat64 := func(key string) (float64, error) { - return cast.ToFloat64E(opts.Get(key)) + + // Polar Miner settings + if conf.Polar.Miner.Etherbase, err = + parser.GetCommonAddress(flagMinerEtherbase); err != nil { + return nil, err } - getBool := func(key string) (bool, error) { - return cast.ToBoolE(opts.Get(key)) + if conf.Polar.Miner.ExtraData, err = + parser.GetHexutilBytes(flagMinerExtraData); err != nil { + return nil, err } - getStringSlice := func(key string) ([]string, error) { - return cast.ToStringSliceE(opts.Get(key)) + if conf.Polar.Miner.GasFloor, err = + parser.GetUint64(flagMinerGasFloor); err != nil { + return nil, err } - getTimeDuration := func(key string) (time.Duration, error) { - return cast.ToDurationE(opts.Get(key)) + if conf.Polar.Miner.GasCeil, err = + parser.GetUint64(flagMinerGasCeil); err != nil { + return nil, err } - - // Polar settings - if conf.Polar.RPCGasCap, err = getUint64(flagRPCGasCap); err != nil { - return nil, handleError(err, flagRPCGasCap) + if conf.Polar.Miner.GasPrice, err = + parser.GetBigInt(flagMinerGasPrice); err != nil { + return nil, err } - if conf.Polar.RPCEVMTimeout, err = getTimeDuration(flagRPCEvmTimeout); err != nil { - return nil, handleError(err, flagRPCEvmTimeout) + if conf.Polar.Miner.Recommit, err = + parser.GetTimeDuration(flagMinerRecommit); err != nil { + return nil, err } - if conf.Polar.RPCTxFeeCap, err = getFloat64(flagRPCTxFeeCap); err != nil { - return nil, handleError(err, flagRPCTxFeeCap) + + if conf.Polar.Miner.NewPayloadTimeout, err = + parser.GetTimeDuration(flagMinerNewPayloadTimeout); err != nil { + return nil, err } // Polar Chain settings - if conf.Polar.Chain.ChainID, err = getBigInt(flagChainID); err != nil { - return nil, handleError(err, flagChainID) + if conf.Polar.Chain.ChainID, err = + parser.GetBigInt(flagChainID); err != nil { + return nil, err } - if conf.Polar.Chain.HomesteadBlock, err = getBigInt(flagHomesteadBlock); err != nil { - return nil, handleError(err, flagHomesteadBlock) + if conf.Polar.Chain.HomesteadBlock, err = + parser.GetBigInt(flagHomesteadBlock); err != nil { + return nil, err } - if conf.Polar.Chain.DAOForkBlock, err = getBigInt(flagDAOForkBlock); err != nil { - return nil, handleError(err, flagDAOForkBlock) + if conf.Polar.Chain.DAOForkBlock, err = + parser.GetBigInt(flagDAOForkBlock); err != nil { + return nil, err } - if conf.Polar.Chain.DAOForkSupport, err = getBool(flagDAOForkSupport); err != nil { - return nil, handleError(err, flagDAOForkSupport) + if conf.Polar.Chain.DAOForkSupport, err = + parser.GetBool(flagDAOForkSupport); err != nil { + return nil, err } - if conf.Polar.Chain.EIP150Block, err = getBigInt(flagEIP150Block); err != nil { - return nil, handleError(err, flagEIP150Block) + if conf.Polar.Chain.EIP150Block, err = + parser.GetBigInt(flagEIP150Block); err != nil { + return nil, err } - if conf.Polar.Chain.EIP155Block, err = getBigInt(flagEIP155Block); err != nil { - return nil, handleError(err, flagEIP155Block) + if conf.Polar.Chain.EIP155Block, err = + parser.GetBigInt(flagEIP155Block); err != nil { + return nil, err } - if conf.Polar.Chain.EIP158Block, err = getBigInt(flagEIP158Block); err != nil { - return nil, handleError(err, flagEIP158Block) + if conf.Polar.Chain.EIP158Block, err = + parser.GetBigInt(flagEIP158Block); err != nil { + return nil, err } - if conf.Polar.Chain.ByzantiumBlock, err = getBigInt(flagByzantiumBlock); err != nil { - return nil, handleError(err, flagByzantiumBlock) + if conf.Polar.Chain.ByzantiumBlock, err = + parser.GetBigInt(flagByzantiumBlock); err != nil { + return nil, err } - if conf.Polar.Chain.ConstantinopleBlock, err = getBigInt(flagConstantinopleBlock); err != nil { - return nil, handleError(err, flagConstantinopleBlock) + if conf.Polar.Chain.ConstantinopleBlock, err = + parser.GetBigInt(flagConstantinopleBlock); err != nil { + return nil, err } - if conf.Polar.Chain.PetersburgBlock, err = getBigInt(flagPetersburgBlock); err != nil { - return nil, handleError(err, flagPetersburgBlock) + if conf.Polar.Chain.PetersburgBlock, err = + parser.GetBigInt(flagPetersburgBlock); err != nil { + return nil, err } - if conf.Polar.Chain.IstanbulBlock, err = getBigInt(flagIstanbulBlock); err != nil { - return nil, handleError(err, flagIstanbulBlock) + if conf.Polar.Chain.IstanbulBlock, err = + parser.GetBigInt(flagIstanbulBlock); err != nil { + return nil, err } - if conf.Polar.Chain.MuirGlacierBlock, err = getBigInt(flagMuirGlacierBlock); err != nil { - return nil, handleError(err, flagMuirGlacierBlock) + if conf.Polar.Chain.MuirGlacierBlock, err = + parser.GetBigInt(flagMuirGlacierBlock); err != nil { + return nil, err } - if conf.Polar.Chain.BerlinBlock, err = getBigInt(flagBerlinBlock); err != nil { - return nil, handleError(err, flagBerlinBlock) + if conf.Polar.Chain.BerlinBlock, err = + parser.GetBigInt(flagBerlinBlock); err != nil { + return nil, err } - if conf.Polar.Chain.LondonBlock, err = getBigInt(flagLondonBlock); err != nil { - return nil, handleError(err, flagLondonBlock) + if conf.Polar.Chain.LondonBlock, err = + parser.GetBigInt(flagLondonBlock); err != nil { + return nil, err } - if conf.Polar.Chain.ArrowGlacierBlock, err = getBigInt(flagArrowGlacierBlock); err != nil { - return nil, handleError(err, flagArrowGlacierBlock) + if conf.Polar.Chain.ArrowGlacierBlock, err = + parser.GetBigInt(flagArrowGlacierBlock); err != nil { + return nil, err } - if conf.Polar.Chain.GrayGlacierBlock, err = getBigInt(flagGrayGlacierBlock); err != nil { - return nil, handleError(err, flagGrayGlacierBlock) + if conf.Polar.Chain.GrayGlacierBlock, err = + parser.GetBigInt(flagGrayGlacierBlock); err != nil { + return nil, err } - if conf.Polar.Chain.MergeNetsplitBlock, err = getBigInt(flagMergeNetsplitBlock); err != nil { - return nil, handleError(err, flagMergeNetsplitBlock) + if conf.Polar.Chain.MergeNetsplitBlock, err = + parser.GetBigInt(flagMergeNetsplitBlock); err != nil { + return nil, err } - if conf.Polar.Chain.ShanghaiTime, err = getUint64Ptr(flagShanghaiTime); err != nil { - return nil, handleError(err, flagShanghaiTime) + if conf.Polar.Chain.ShanghaiTime, err = + parser.GetUint64Ptr(flagShanghaiTime); err != nil { + return nil, err } - if conf.Polar.Chain.CancunTime, err = getUint64Ptr(flagCancunTime); err != nil { - return nil, handleError(err, flagCancunTime) + if conf.Polar.Chain.CancunTime, err = + parser.GetUint64Ptr(flagCancunTime); err != nil { + return nil, err } - if conf.Polar.Chain.PragueTime, err = getUint64Ptr(flagPragueTime); err != nil { - return nil, handleError(err, flagPragueTime) + if conf.Polar.Chain.PragueTime, err = + parser.GetUint64Ptr(flagPragueTime); err != nil { + return nil, err } - if conf.Polar.Chain.VerkleTime, err = getUint64Ptr(flagVerkleTime); err != nil { - return nil, handleError(err, flagVerkleTime) + if conf.Polar.Chain.VerkleTime, err = + parser.GetUint64Ptr(flagVerkleTime); err != nil { + return nil, err } - if conf.Polar.Chain.TerminalTotalDifficulty, err = getBigInt( - flagTerminalTotalDifficulty); err != nil { - return nil, handleError(err, flagTerminalTotalDifficulty) + if conf.Polar.Chain.TerminalTotalDifficulty, err = + parser.GetBigInt( + flagTerminalTotalDifficulty); err != nil { + return nil, err } - if conf.Polar.Chain.TerminalTotalDifficultyPassed, err = getBool( - flagTerminalTotalDifficultyPassed); err != nil { - return nil, handleError(err, flagTerminalTotalDifficultyPassed) + if conf.Polar.Chain.TerminalTotalDifficultyPassed, err = + parser.GetBool( + flagTerminalTotalDifficultyPassed); err != nil { + return nil, err } - if conf.Polar.Chain.IsDevMode, err = getBool(flagIsDevMode); err != nil { - return nil, handleError(err, flagIsDevMode) + if conf.Polar.Chain.IsDevMode, err = + parser.GetBool(flagIsDevMode); err != nil { + return nil, err } // Polar.GPO settings - if conf.Polar.GPO.Blocks, err = getInt(flagBlocks); err != nil { - return nil, handleError(err, flagBlocks) + if conf.Polar.GPO.Blocks, err = + parser.GetInt(flagBlocks); err != nil { + return nil, err } - if conf.Polar.GPO.Percentile, err = getInt(flagPercentile); err != nil { - return nil, handleError(err, flagPercentile) + if conf.Polar.GPO.Percentile, err = + parser.GetInt(flagPercentile); err != nil { + return nil, err } - if conf.Polar.GPO.MaxHeaderHistory, err = getUint64(flagMaxHeaderHistory); err != nil { - return nil, handleError(err, flagMaxHeaderHistory) + if conf.Polar.GPO.MaxHeaderHistory, err = + parser.GetUint64(flagMaxHeaderHistory); err != nil { + return nil, err } - if conf.Polar.GPO.MaxBlockHistory, err = getUint64(flagMaxBlockHistory); err != nil { - return nil, handleError(err, flagMaxBlockHistory) + if conf.Polar.GPO.MaxBlockHistory, err = + parser.GetUint64(flagMaxBlockHistory); err != nil { + return nil, err } - if val, err = getInt64(flagDefault); err != nil { - return nil, handleError(err, flagDefault) + if val, err = + parser.GetInt64(flagDefault); err != nil { + return nil, err } conf.Polar.GPO.Default = big.NewInt(val) - if val, err = getInt64(flagMaxPrice); err != nil { - return nil, handleError(err, flagMaxPrice) + if val, err = + parser.GetInt64(flagMaxPrice); err != nil { + return nil, err } conf.Polar.GPO.MaxPrice = big.NewInt(val) - if val, err = getInt64(flagIgnorePrice); err != nil { - return nil, handleError(err, flagIgnorePrice) + if val, err = + parser.GetInt64(flagIgnorePrice); err != nil { + return nil, err } conf.Polar.GPO.IgnorePrice = big.NewInt(val) // LegacyPool - conf.Polar.LegacyTxPool.Locals = getCommonAddressList(flagDefault) - - if conf.Polar.LegacyTxPool.NoLocals, err = getBool(flagNoLocals); err != nil { - return nil, handleError(err, flagNoLocals) + if conf.Polar.LegacyTxPool.Locals, err = + parser.GetCommonAddressList(flagLocals); err != nil { + return nil, err + } + if conf.Polar.LegacyTxPool.NoLocals, err = + parser.GetBool(flagNoLocals); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.Journal, err = getString(flagJournal); err != nil { - return nil, handleError(err, flagJournal) + if conf.Polar.LegacyTxPool.Journal, err = + parser.GetString(flagJournal); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.Rejournal, err = getTimeDuration(flagReJournal); err != nil { - return nil, handleError(err, flagReJournal) + if conf.Polar.LegacyTxPool.Rejournal, err = + parser.GetTimeDuration(flagReJournal); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.PriceLimit, err = getUint64(flagPriceLimit); err != nil { - return nil, handleError(err, flagPriceLimit) + if conf.Polar.LegacyTxPool.PriceLimit, err = + parser.GetUint64(flagPriceLimit); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.PriceBump, err = getUint64(flagPriceBump); err != nil { - return nil, handleError(err, flagPriceBump) + if conf.Polar.LegacyTxPool.PriceBump, err = + parser.GetUint64(flagPriceBump); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.AccountSlots, err = getUint64(flagAccountSlots); err != nil { - return nil, handleError(err, flagAccountSlots) + if conf.Polar.LegacyTxPool.AccountSlots, err = + parser.GetUint64(flagAccountSlots); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.GlobalSlots, err = getUint64(flagGlobalSlots); err != nil { - return nil, handleError(err, flagGlobalSlots) + if conf.Polar.LegacyTxPool.GlobalSlots, err = + parser.GetUint64(flagGlobalSlots); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.AccountQueue, err = getUint64(flagAccountQueue); err != nil { - return nil, handleError(err, flagAccountQueue) + if conf.Polar.LegacyTxPool.AccountQueue, err = + parser.GetUint64(flagAccountQueue); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.GlobalQueue, err = getUint64(flagGlobalQueue); err != nil { - return nil, handleError(err, flagGlobalQueue) + if conf.Polar.LegacyTxPool.GlobalQueue, err = + parser.GetUint64(flagGlobalQueue); err != nil { + return nil, err } - if conf.Polar.LegacyTxPool.Lifetime, err = getTimeDuration(flagLifetime); err != nil { - return nil, handleError(err, flagLifetime) + if conf.Polar.LegacyTxPool.Lifetime, err = + parser.GetTimeDuration(flagLifetime); err != nil { + return nil, err } // Node settings - if conf.Node.Name, err = getString(flagName); err != nil { - return nil, handleError(err, flagName) + if conf.Node.Name, err = + parser.GetString(flagName); err != nil { + return nil, err } - if conf.Node.UserIdent, err = getString(flagUserIdent); err != nil { - return nil, handleError(err, flagUserIdent) + if conf.Node.UserIdent, err = + parser.GetString(flagUserIdent); err != nil { + return nil, err } - if conf.Node.Version, err = getString(flagVersion); err != nil { - return nil, handleError(err, flagVersion) + if conf.Node.Version, err = + parser.GetString(flagVersion); err != nil { + return nil, err } - if conf.Node.DataDir, err = getString(flagDataDir); err != nil { - return nil, handleError(err, flagDataDir) + if conf.Node.DataDir, err = + parser.GetString(flagDataDir); err != nil { + return nil, err } if conf.Node.DataDir == "" { - conf.Node.DataDir, err = getString(flags.FlagHome) + conf.Node.DataDir, err = + parser.GetString(flags.FlagHome) if err != nil { - return nil, handleError(err, flags.FlagHome) + return nil, err } } - if conf.Node.KeyStoreDir, err = getString(flagKeyStoreDir); err != nil { - return nil, handleError(err, flagKeyStoreDir) + if conf.Node.KeyStoreDir, err = + parser.GetString(flagKeyStoreDir); err != nil { + return nil, err } - if conf.Node.ExternalSigner, err = getString(flagExternalSigner); err != nil { - return nil, handleError(err, flagExternalSigner) + if conf.Node.ExternalSigner, err = + parser.GetString(flagExternalSigner); err != nil { + return nil, err } - if conf.Node.UseLightweightKDF, err = getBool(flagUseLightweightKdf); err != nil { - return nil, handleError(err, flagUseLightweightKdf) + if conf.Node.UseLightweightKDF, err = + parser.GetBool(flagUseLightweightKdf); err != nil { + return nil, err } - if conf.Node.InsecureUnlockAllowed, err = getBool(flagInsecureUnlockAllowed); err != nil { - return nil, handleError(err, flagInsecureUnlockAllowed) + if conf.Node.InsecureUnlockAllowed, err = + parser.GetBool(flagInsecureUnlockAllowed); err != nil { + return nil, err } - if conf.Node.USB, err = getBool(flagUsb); err != nil { - return nil, handleError(err, flagUsb) + if conf.Node.USB, err = + parser.GetBool(flagUsb); err != nil { + return nil, err } - if conf.Node.SmartCardDaemonPath, err = getString(flagSmartCardDaemonPath); err != nil { - return nil, handleError(err, flagSmartCardDaemonPath) + if conf.Node.SmartCardDaemonPath, err = + parser.GetString(flagSmartCardDaemonPath); err != nil { + return nil, err } - if conf.Node.IPCPath, err = getString(flagIpcPath); err != nil { - return nil, handleError(err, flagIpcPath) + if conf.Node.IPCPath, err = + parser.GetString(flagIpcPath); err != nil { + return nil, err } - if conf.Node.HTTPHost, err = getString(flagHTTPHost); err != nil { - return nil, handleError(err, flagHTTPHost) + if conf.Node.HTTPHost, err = + parser.GetString(flagHTTPHost); err != nil { + return nil, err } - if conf.Node.HTTPPort, err = getInt(flagHTTPPort); err != nil { - return nil, handleError(err, flagHTTPPort) + if conf.Node.HTTPPort, err = + parser.GetInt(flagHTTPPort); err != nil { + return nil, err } - if conf.Node.HTTPCors, err = getStringSlice(flagHTTPCors); err != nil { - return nil, handleError(err, flagHTTPCors) + if conf.Node.HTTPCors, err = + parser.GetStringSlice(flagHTTPCors); err != nil { + return nil, err } - if conf.Node.HTTPVirtualHosts, err = getStringSlice(flagHTTPVirtualHosts); err != nil { - return nil, handleError(err, flagHTTPVirtualHosts) + if conf.Node.HTTPVirtualHosts, err = + parser.GetStringSlice(flagHTTPVirtualHosts); err != nil { + return nil, err } - if conf.Node.HTTPModules, err = getStringSlice(flagHTTPModules); err != nil { - return nil, handleError(err, flagHTTPModules) + if conf.Node.HTTPModules, err = + parser.GetStringSlice(flagHTTPModules); err != nil { + return nil, err } - if conf.Node.HTTPPathPrefix, err = getString(flagHTTPPathPrefix); err != nil { - return nil, handleError(err, flagHTTPPathPrefix) + if conf.Node.HTTPPathPrefix, err = + parser.GetString(flagHTTPPathPrefix); err != nil { + return nil, err } - if conf.Node.AuthAddr, err = getString(flagAuthAddr); err != nil { - return nil, handleError(err, flagAuthAddr) + if conf.Node.AuthAddr, err = + parser.GetString(flagAuthAddr); err != nil { + return nil, err } - if conf.Node.AuthPort, err = getInt(flagAuthPort); err != nil { - return nil, handleError(err, flagAuthPort) + if conf.Node.AuthPort, err = + parser.GetInt(flagAuthPort); err != nil { + return nil, err } - if conf.Node.AuthVirtualHosts, err = getStringSlice(flagAuthVirtualHosts); err != nil { - return nil, handleError(err, flagAuthVirtualHosts) + if conf.Node.AuthVirtualHosts, err = + parser.GetStringSlice(flagAuthVirtualHosts); err != nil { + return nil, err } - if conf.Node.WSHost, err = getString(flagWsHost); err != nil { - return nil, handleError(err, flagWsHost) + if conf.Node.WSHost, err = + parser.GetString(flagWsHost); err != nil { + return nil, err } - if conf.Node.WSPort, err = getInt(flagWsPort); err != nil { - return nil, handleError(err, flagWsPort) + if conf.Node.WSPort, err = + parser.GetInt(flagWsPort); err != nil { + return nil, err } - if conf.Node.WSPathPrefix, err = getString(flagWsPathPrefix); err != nil { - return nil, handleError(err, flagWsPathPrefix) + if conf.Node.WSPathPrefix, err = + parser.GetString(flagWsPathPrefix); err != nil { + return nil, err } - if conf.Node.WSOrigins, err = getStringSlice(flagWsOrigins); err != nil { - return nil, handleError(err, flagWsOrigins) + if conf.Node.WSOrigins, err = + parser.GetStringSlice(flagWsOrigins); err != nil { + return nil, err } - if conf.Node.WSModules, err = getStringSlice(flagWsModules); err != nil { - return nil, handleError(err, flagWsModules) + if conf.Node.WSModules, err = + parser.GetStringSlice(flagWsModules); err != nil { + return nil, err } - if conf.Node.WSExposeAll, err = getBool(flagWsExposeAll); err != nil { - return nil, handleError(err, flagWsExposeAll) + if conf.Node.WSExposeAll, err = + parser.GetBool(flagWsExposeAll); err != nil { + return nil, err } - if conf.Node.GraphQLCors, err = getStringSlice(flagGraphqlCors); err != nil { - return nil, handleError(err, flagGraphqlCors) + if conf.Node.GraphQLCors, err = + parser.GetStringSlice(flagGraphqlCors); err != nil { + return nil, err } - if conf.Node.GraphQLVirtualHosts, err = getStringSlice(flagGraphqlVirtualHosts); err != nil { - return nil, handleError(err, flagGraphqlVirtualHosts) + if conf.Node.GraphQLVirtualHosts, err = + parser.GetStringSlice(flagGraphqlVirtualHosts); err != nil { + return nil, err } - if conf.Node.AllowUnprotectedTxs, err = getBool(flagAllowUnprotectedTxs); err != nil { - return nil, handleError(err, flagAllowUnprotectedTxs) + if conf.Node.AllowUnprotectedTxs, err = + parser.GetBool(flagAllowUnprotectedTxs); err != nil { + return nil, err } - if conf.Node.BatchRequestLimit, err = getInt(flagBatchRequestLimit); err != nil { - return nil, handleError(err, flagBatchRequestLimit) + if conf.Node.BatchRequestLimit, err = + parser.GetInt(flagBatchRequestLimit); err != nil { + return nil, err } - if conf.Node.BatchResponseMaxSize, err = getInt(flagBatchResponseMaxSize); err != nil { - return nil, handleError(err, flagBatchResponseMaxSize) + if conf.Node.BatchResponseMaxSize, err = + parser.GetInt(flagBatchResponseMaxSize); err != nil { + return nil, err } - if conf.Node.JWTSecret, err = getString(flagJwtSecret); err != nil { - return nil, handleError(err, flagJwtSecret) + if conf.Node.JWTSecret, err = + parser.GetString(flagJwtSecret); err != nil { + return nil, err } - if conf.Node.DBEngine, err = getString(flagDBEngine); err != nil { - return nil, handleError(err, flagDBEngine) + if conf.Node.DBEngine, err = + parser.GetString(flagDBEngine); err != nil { + return nil, err } // Node.HTTPTimeouts settings - if conf.Node.HTTPTimeouts.ReadTimeout, err = getTimeDuration(flagReadTimeout); err != nil { - return nil, handleError(err, flagReadTimeout) - } - if conf.Node.HTTPTimeouts.ReadHeaderTimeout, err = getTimeDuration( - flagReadHeaderTimeout); err != nil { - return nil, handleError(err, flagReadHeaderTimeout) - } - if conf.Node.HTTPTimeouts.WriteTimeout, err = getTimeDuration(flagWriteTimeout); err != nil { - return nil, handleError(err, flagWriteTimeout) - } - if conf.Node.HTTPTimeouts.IdleTimeout, err = getTimeDuration(flagIdleTimeout); err != nil { - return nil, handleError(err, flagIdleTimeout) + if conf.Node.HTTPTimeouts.ReadTimeout, err = + parser.GetTimeDuration(flagReadTimeout); err != nil { + return nil, err + } + if conf.Node.HTTPTimeouts.ReadHeaderTimeout, err = + parser.GetTimeDuration( + flagReadHeaderTimeout); err != nil { + return nil, err + } + if conf.Node.HTTPTimeouts.WriteTimeout, err = + parser.GetTimeDuration(flagWriteTimeout); err != nil { + return nil, err + } + if conf.Node.HTTPTimeouts.IdleTimeout, err = + parser.GetTimeDuration(flagIdleTimeout); err != nil { + return nil, err } return conf, nil diff --git a/cosmos/config/flags.go b/cosmos/config/flags.go index 4e6ee616a..7c7ded0aa 100644 --- a/cosmos/config/flags.go +++ b/cosmos/config/flags.go @@ -21,11 +21,29 @@ package config const ( - flagGraphqlVirtualHosts = "polaris.node.graphql-virtual-hosts" - flagIpcPath = "polaris.node.ipc-path" - //#nosec: G101 // not a secret. - flagJwtSecret = "polaris.node.jwt-secret" + // Polar Root. + flagRPCEvmTimeout = "polaris.polar.rpc-evm-timeout" + flagRPCTxFeeCap = "polaris.polar.rpc-tx-fee-cap" + flagRPCGasCap = "polaris.polar.rpc-gas-cap" + + // Miner. + flagMinerEtherbase = "polaris.polar.miner.etherbase" + flagMinerExtraData = "polaris.polar.miner.extra-data" + flagMinerGasFloor = "polaris.polar.miner.gas-floor" + flagMinerGasCeil = "polaris.polar.miner.gas-ceil" + flagMinerGasPrice = "polaris.polar.miner.gas-price" + flagMinerRecommit = "polaris.polar.miner.recommit" + flagMinerNewPayloadTimeout = "polaris.polar.miner.new-payload-timeout" + + // GPO. + flagBlocks = "polaris.polar.gpo.blocks" + flagMaxBlockHistory = "polaris.polar.gpo.max-block-history" + flagPercentile = "polaris.polar.gpo.percentile" + flagMaxHeaderHistory = "polaris.polar.gpo.max-header-history" + + // Node. + flagJwtSecret = "polaris.node.jwt-secret" //#nosec: G101 // not a secret. flagWsPort = "polaris.node.ws-port" flagBatchRequestLimit = "polaris.node.batch-request-limit" flagKeyStoreDir = "polaris.node.key-store-dir" @@ -33,7 +51,6 @@ const ( flagReadTimeout = "polaris.node.http-timeouts.read-timeout" flagDataDir = "polaris.node.data-dir" flagUserIdent = "polaris.node.user-ident" - flagBlocks = "polaris.polar.gpo.blocks" flagGraphqlCors = "polaris.node.graphql-cors" flagSmartCardDaemonPath = "polaris.node.smart-card-daemon-path" flagWsModules = "polaris.node.ws-modules" @@ -44,15 +61,10 @@ const ( flagHTTPHost = "polaris.node.http-host" flagUseLightweightKdf = "polaris.node.use-lightweight-kdf" flagWsExposeAll = "polaris.node.ws-expose-all" - flagMaxBlockHistory = "polaris.polar.gpo.max-block-history" - flagPercentile = "polaris.polar.gpo.percentile" flagInsecureUnlockAllowed = "polaris.node.insecure-unlock-allowed" flagWsPathPrefix = "polaris.node.ws-path-prefix" flagWsHost = "polaris.node.ws-host" flagName = "polaris.node.name" - flagRPCEvmTimeout = "polaris.polar.rpc-evm-timeout" - flagRPCTxFeeCap = "polaris.polar.rpc-tx-fee-cap" - flagRPCGasCap = "polaris.polar.rpc-gas-cap" flagAuthVirtualHosts = "polaris.node.auth-virtual-hosts" flagAuthPort = "polaris.node.auth-port" flagUsb = "polaris.node.usb" @@ -60,7 +72,6 @@ const ( flagBatchResponseMaxSize = "polaris.node.batch-response-max-size" flagVersion = "polaris.node.version" flagHTTPVirtualHosts = "polaris.node.http-virtual-hosts" - flagMaxHeaderHistory = "polaris.polar.gpo.max-header-history" flagExternalSigner = "polaris.node.external-signer" flagHTTPPathPrefix = "polaris.node.http-path-prefix" flagWriteTimeout = "polaris.node.http-timeouts.write-timeout" @@ -70,19 +81,23 @@ const ( flagDefault = "polaris.node.http-timeouts.default" flagMaxPrice = "polaris.node.http-timeouts.max-price" flagIgnorePrice = "polaris.node.http-timeouts.ignore-price" - flagLocals = "polaris.polar.legacy-tx-pool.locals" - flagNoLocals = "polaris.polar.legacy-tx-pool.no-locals" - flagJournal = "polaris.polar.legacy-tx-pool.journal" - flagReJournal = "polaris.polar.legacy-tx-pool.rejournal" - flagPriceLimit = "polaris.polar.legacy-tx-pool.price-limit" - flagPriceBump = "polaris.polar.legacy-tx-pool.price-bump" - flagAccountSlots = "polaris.polar.legacy-tx-pool.account-slots" - flagGlobalSlots = "polaris.polar.legacy-tx-pool.global-slots" - flagAccountQueue = "polaris.polar.legacy-tx-pool.account-queue" - flagGlobalQueue = "polaris.polar.legacy-tx-pool.global-queue" - flagLifetime = "polaris.polar.legacy-tx-pool.lifetime" + flagGraphqlVirtualHosts = "polaris.node.graphql-virtual-hosts" + flagIpcPath = "polaris.node.ipc-path" + + // Legacy TxPool. + flagLocals = "polaris.polar.legacy-tx-pool.locals" + flagNoLocals = "polaris.polar.legacy-tx-pool.no-locals" + flagJournal = "polaris.polar.legacy-tx-pool.journal" + flagReJournal = "polaris.polar.legacy-tx-pool.rejournal" + flagPriceLimit = "polaris.polar.legacy-tx-pool.price-limit" + flagPriceBump = "polaris.polar.legacy-tx-pool.price-bump" + flagAccountSlots = "polaris.polar.legacy-tx-pool.account-slots" + flagGlobalSlots = "polaris.polar.legacy-tx-pool.global-slots" + flagAccountQueue = "polaris.polar.legacy-tx-pool.account-queue" + flagGlobalQueue = "polaris.polar.legacy-tx-pool.global-queue" + flagLifetime = "polaris.polar.legacy-tx-pool.lifetime" - // ethereum. + // Chain Config. flagChainID = "polaris.polar.chain.chain-id" flagHomesteadBlock = "polaris.polar.chain.homestead-block" flagDAOForkBlock = "polaris.polar.chain.dao-fork-block" diff --git a/cosmos/config/mocks/app_options.go b/cosmos/config/mocks/app_options.go new file mode 100644 index 000000000..4a23fb8ab --- /dev/null +++ b/cosmos/config/mocks/app_options.go @@ -0,0 +1,76 @@ +// Code generated by mockery v2.35.2. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// AppOptions is an autogenerated mock type for the AppOptions type +type AppOptions struct { + mock.Mock +} + +type AppOptions_Expecter struct { + mock *mock.Mock +} + +func (_m *AppOptions) EXPECT() *AppOptions_Expecter { + return &AppOptions_Expecter{mock: &_m.Mock} +} + +// Get provides a mock function with given fields: _a0 +func (_m *AppOptions) Get(_a0 string) interface{} { + ret := _m.Called(_a0) + + var r0 interface{} + if rf, ok := ret.Get(0).(func(string) interface{}); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(interface{}) + } + } + + return r0 +} + +// AppOptions_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type AppOptions_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - _a0 string +func (_e *AppOptions_Expecter) Get(_a0 interface{}) *AppOptions_Get_Call { + return &AppOptions_Get_Call{Call: _e.mock.On("Get", _a0)} +} + +func (_c *AppOptions_Get_Call) Run(run func(_a0 string)) *AppOptions_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(string)) + }) + return _c +} + +func (_c *AppOptions_Get_Call) Return(_a0 interface{}) *AppOptions_Get_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *AppOptions_Get_Call) RunAndReturn(run func(string) interface{}) *AppOptions_Get_Call { + _c.Call.Return(run) + return _c +} + +// NewAppOptions creates a new instance of AppOptions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAppOptions(t interface { + mock.TestingT + Cleanup(func()) +}) *AppOptions { + mock := &AppOptions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/cosmos/config/parser.go b/cosmos/config/parser.go new file mode 100644 index 000000000..274f46d97 --- /dev/null +++ b/cosmos/config/parser.go @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: BUSL-1.1 +// +// Copyright (C) 2023, Berachain Foundation. All rights reserved. +// Use of this software is govered by the Business Source License included +// in the LICENSE file of this repository and at www.mariadb.com/bsl11. +// +// ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY +// TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER +// VERSIONS OF THE LICENSED WORK. +// +// THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF +// LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF +// LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE). +// +// TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +// AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +// EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +// TITLE. +package config + +import ( + "fmt" + "math/big" + "time" + + "github.com/spf13/cast" + + servertypes "github.com/cosmos/cosmos-sdk/server/types" + + "pkg.berachain.dev/polaris/eth/common" + "pkg.berachain.dev/polaris/eth/common/hexutil" +) + +// baseTen is for the big.Int string conversation. +const baseTen = 10 + +// AppOptions is for generating a mock. +type AppOptions interface { + servertypes.AppOptions +} + +// AppOptionsParser is a struct that holds the application options for parsing. +type AppOptionsParser struct { + servertypes.AppOptions +} + +// NewAppOptionsParser creates a new instance of AppOptionsParser with the provided +// AppOptions. +func NewAppOptionsParser(opts servertypes.AppOptions) *AppOptionsParser { + return &AppOptionsParser{opts} +} + +// GetCommonAddress returns the common.Address for the provided key. +func (c *AppOptionsParser) GetCommonAddress(key string) (common.Address, error) { + addressStr, err := c.GetString(key) + if err != nil { + return common.Address{}, err + } + if !common.IsHexAddress(addressStr) { + return common.Address{}, fmt.Errorf("invalid address: %s", addressStr) + } + return common.HexToAddress(addressStr), nil +} + +// GetCommonAddressList retrieves a list of common.Address from a configuration key. +func (c *AppOptionsParser) GetCommonAddressList(key string) ([]common.Address, error) { + addresses := make([]common.Address, 0) + addressStrs := cast.ToStringSlice(c.Get(key)) + for _, addressStr := range addressStrs { + address := common.HexToAddress(addressStr) + if !common.IsHexAddress(addressStr) { + return nil, fmt.Errorf("invalid address: %s", addressStr) + } + addresses = append(addresses, address) + } + return addresses, nil +} + +// GetHexutilBytes returns a hexutil.Bytes from a configuration key. +func (c *AppOptionsParser) GetHexutilBytes(key string) (hexutil.Bytes, error) { + bytesStr, err := c.GetString(key) + if err != nil { + return hexutil.Bytes{}, err + } + return hexutil.Decode(bytesStr) +} + +// GetString retrieves a string value from a configuration key. +func (c *AppOptionsParser) GetString(key string) (string, error) { + return handleError(c, cast.ToStringE, key) +} + +// GetInt retrieves an integer value from a configuration key. +func (c *AppOptionsParser) GetInt(key string) (int, error) { + return handleError(c, cast.ToIntE, key) +} + +// GetInt64 retrieves a int64 value from a configuration key. +func (c *AppOptionsParser) GetInt64(key string) (int64, error) { + return handleError(c, cast.ToInt64E, key) +} + +// GetUint64 retrieves a uint64 value from a configuration key. +func (c *AppOptionsParser) GetUint64(key string) (uint64, error) { + return handleError(c, cast.ToUint64E, key) +} + +// GetUint64Ptr retrieves a pointer to a uint64 value fro m a configuration key. +func (c *AppOptionsParser) GetUint64Ptr(key string) (*uint64, error) { + return handleErrorPtr(c, cast.ToUint64E, key) +} + +// GetBigInt retrieves a big.Int value from a configuration key. +func (c *AppOptionsParser) GetBigInt(key string) (*big.Int, error) { + return handleErrorPtr(c, handleBigInt, key) +} + +// GetFloat64 retrieves a float64 value from a configuration key. +func (c *AppOptionsParser) GetFloat64(key string) (float64, error) { + return handleError(c, cast.ToFloat64E, key) +} + +// GetBool retrieves a boolean value from a configuration key. +func (c *AppOptionsParser) GetBool(key string) (bool, error) { + return handleError(c, cast.ToBoolE, key) +} + +// GetStringSlice retrieves a slice of strings from a configuration key. +func (c *AppOptionsParser) GetStringSlice(key string) ([]string, error) { + return handleError(c, cast.ToStringSliceE, key) +} + +// GetTimeDuration retrieves a time.Duration value from a configuration key. +func (c *AppOptionsParser) GetTimeDuration(key string) (time.Duration, error) { + return handleError(c, cast.ToDurationE, key) +} + +// isNilRepresentation returns true if the provided value is "", "null" or "". +// it is used to determine when we need to initialize a nil ptr for a value to +// prevent the sdk from panicking on startup due to weird value. +func (c *AppOptionsParser) isNilRepresentation(value string) bool { + return value == "" || value == "null" || value == "" +} + +// handleError handles an error for a given flag in the AppOptionsParser. +// It attempts to cast the flag's value using the provided castFn and returns the result. +// If the cast fails, it returns an error. +func handleError[T any]( + c *AppOptionsParser, castFn func(interface{}) (T, error), flag string) (T, error) { + var val T + var err error + if val, err = castFn(c.Get(flag)); err != nil { + var t T + return t, fmt.Errorf( + "error while reading configuration: %w flag: %s", err, flag) + } + return val, nil +} + +// handleErrorPtr handles an error for a given flag in the AppOptionsParser. +// It attempts to cast the flag's value using the provided castFn and returns a pointer to +// the result. If the cast fails, it returns an error. If the flag's value is empty, +// it returns a nil pointer. +func handleErrorPtr[T any]( + c *AppOptionsParser, castFn func(interface{}) (T, error), flag string) (*T, error) { + var num string + var err error + if num, err = cast.ToStringE((c.Get(flag))); err != nil { + return nil, fmt.Errorf("error while reading string: %w flag: %s", err, flag) + } else if c.isNilRepresentation(num) { + return (*T)(nil), nil + } + var val T + if val, err = castFn(num); err != nil { + return nil, fmt.Errorf("error while converting to value: %w flag: %s", err, flag) + } + return &val, nil +} + +// handleBigInt handles a big.Int value from the given numStr interface. +// It attempts to parse the numStr as a big.Int and returns the result. +// If parsing fails, it returns an error. +func handleBigInt(numStr interface{}) (big.Int, error) { + num, ok := new(big.Int).SetString(numStr.(string), baseTen) + if !ok { + return big.Int{}, fmt.Errorf("invalid big.Int string: %s", numStr.(string)) + } + return *num, nil +} diff --git a/cosmos/config/parser_test.go b/cosmos/config/parser_test.go new file mode 100644 index 000000000..120ea8dc8 --- /dev/null +++ b/cosmos/config/parser_test.go @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: BUSL-1.1 +// +// Copyright (C) 2023, Berachain Foundation. All rights reserved. +// Use of this software is govered by the Business Source License included +// in the LICENSE file of this repository and at www.mariadb.com/bsl11. +// +// ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY +// TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER +// VERSIONS OF THE LICENSED WORK. +// +// THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF +// LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF +// LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE). +// +// TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON +// AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, +// EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND +// TITLE. +package config + +import ( + "math/big" + "testing" + "time" + + "pkg.berachain.dev/polaris/cosmos/config/mocks" + "pkg.berachain.dev/polaris/eth/common" + "pkg.berachain.dev/polaris/eth/common/hexutil" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestConfig(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "cosmos/config") +} + +var _ = Describe("Parser", func() { + var parser *AppOptionsParser + var appOpts *mocks.AppOptions + + BeforeEach(func() { + appOpts = new(mocks.AppOptions) + parser = NewAppOptionsParser(appOpts) + }) + + It("should set and retrieve a string option", func() { + value := "testValue" + runTest(appOpts, parser.GetString, value) + }) + + It("should set and retrieve an integer option", func() { + value := int(42) + runTest(appOpts, parser.GetInt, value) + }) + + It("should handle an int64 option", func() { + value := int64(42) + runTest(appOpts, parser.GetInt64, value) + }) + + It("should set and retrieve a uint64 option", func() { + value := uint64(42) + runTest(appOpts, parser.GetUint64, value) + }) + + It("should set and retrieve a pointer to a uint64 option", func() { + value := uint64(42) + runTestWithOutput(appOpts, parser.GetUint64Ptr, "42", &value) + }) + + It("should set and retrieve a big.Int option", func() { + value := new(big.Int).SetInt64(42) + runTestWithOutput(appOpts, parser.GetBigInt, "42", value) + }) + + It("should set and retrieve a float64 option", func() { + value := 3.14159 + runTest(appOpts, parser.GetFloat64, value) + }) + + It("should set and retrieve a boolean option", func() { + value := true + runTest(appOpts, parser.GetBool, value) + }) + + It("should set and retrieve a string slice option", func() { + value := []string{"apple", "banana", "cherry"} + runTest(appOpts, parser.GetStringSlice, value) + }) + + It("should set and retrieve a time.Duration option", func() { + value := time.Second * 10 + runTest(appOpts, parser.GetTimeDuration, value) + }) + + It("should set and retrieve a common.Address option", func() { + addressStr := "0x18df82c7e422a42d47345ed86b0e935e9718ebda" + runTestWithOutput( + appOpts, parser.GetCommonAddress, addressStr, common.HexToAddress(addressStr)) + }) + + It("should set and retrieve a list of common.Address options", func() { + addressStrs := []string{ + "0x20f33ce90a13a4b5e7697e3544c3083b8f8a51d4", + "0x18df82c7e422a42d47345ed86b0e935e9718ebda", + } + expectedAddresses := []common.Address{ + common.HexToAddress(addressStrs[0]), + common.HexToAddress(addressStrs[1]), + } + + // Run the test using the runTest function + runTestWithOutput( + appOpts, parser.GetCommonAddressList, addressStrs, expectedAddresses) + }) + + It("should set and retrieve a hexutil.Bytes option", func() { + bytesStr := "0x1234567890abcdef" + expectedBytes := hexutil.MustDecode(bytesStr) + + // Run the test using the runTest function + runTest(appOpts, parser.GetHexutilBytes, expectedBytes) + }) +}) + +// runTest handles testing of various types. +func runTest[A any]( + appOpts *mocks.AppOptions, parser func(string) (A, error), value A) { + runTestWithOutput(appOpts, parser, value, value) +} + +// runTest handles testing of various types. +func runTestWithOutput[A, B any]( + appOpts *mocks.AppOptions, parser func(string) (B, error), value A, output B) { + // Set the value. + appOpts.On("Get", "myTestKey").Return(value).Once() + + // Retrieve the option + retrievedValue, err := parser("myTestKey") + + Expect(err).ToNot(HaveOccurred()) + Expect(retrievedValue).To(Equal(output)) +} diff --git a/cosmos/config/template.go b/cosmos/config/template.go index 0c3bccd13..138faf761 100644 --- a/cosmos/config/template.go +++ b/cosmos/config/template.go @@ -18,7 +18,7 @@ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND // TITLE. -//nolint:lll,cyclop // template file. +//nolint:lll // template file. package config const ( @@ -40,6 +40,7 @@ rpc-evm-timeout = "{{ .Polaris.Polar.RPCEVMTimeout }}" rpc-tx-fee-cap = "{{ .Polaris.Polar.RPCTxFeeCap }}" +# Chain config [polaris.polar.chain] chain-id = "{{ .Polaris.Polar.Chain.ChainID }}" @@ -113,6 +114,30 @@ terminal-total-difficulty-passed = "{{ .Polaris.Polar.Chain.TerminalTotalDifficu is-dev-mode = {{ .Polaris.Polar.Chain.IsDevMode }} +# Miner config +[polaris.polar.miner] +# The address to which mining rewards will be sent +etherbase = "{{.Polaris.Polar.Miner.Etherbase }}" + +# Extra data included in mined blocks +extra-data = "{{.Polaris.Polar.Miner.ExtraData }}" + +# Gas price for transactions included in blocks +gas-price = "{{.Polaris.Polar.Miner.GasPrice }}" + +# Minimum gas limit for transactions included in blocks +gas-floor = "{{.Polaris.Polar.Miner.GasFloor }}" + +# Maximum gas limit for transactions included in blocks +gas-ceil = "{{.Polaris.Polar.Miner.GasCeil }}" + +# Whether to enable recommit feature +recommit = "{{.Polaris.Polar.Miner.Recommit }}" + +# Timeout for creating a new payload +new-payload-timeout = "{{.Polaris.Polar.Miner.NewPayloadTimeout }}" + + # Gas price oracle settings for Polaris [polaris.polar.gpo] # Number of blocks to check for gas prices diff --git a/e2e/hive/clients/polard/config/app.toml b/e2e/hive/clients/polard/config/app.toml index a7615f28d..cc91de3f2 100644 --- a/e2e/hive/clients/polard/config/app.toml +++ b/e2e/hive/clients/polard/config/app.toml @@ -240,6 +240,7 @@ rpc-evm-timeout = "5s" rpc-tx-fee-cap = "1" +# Chain config [polaris.polar.chain] chain-id = "2061" @@ -295,37 +296,61 @@ merge-netsplit-block = "0" shanghai-time = "0" # Cancun switch time (nil == no fork, 0 = already on cancun) -cancun-time = "null" +cancun-time = "" # Prague switch time (nil == no fork, 0 = already on prague) -prague-time = "null" +prague-time = "" # Verkle switch time (nil == no fork, 0 = already on verkle) -verkle-time = "null" +verkle-time = "" # Terminal total difficulty terminal-total-difficulty = "0" # Whether terminal total difficulty has passed -terminal-total-difficulty-passed = true +terminal-total-difficulty-passed = "true" # DevMode enabled is-dev-mode = false +# Miner config +[polaris.polar.miner] +# The address to which mining rewards will be sent +etherbase = "0x0000000000000000000000000000000000000000" + +# Extra data included in mined blocks +extra-data = "0x" + +# Gas price for transactions included in blocks +gas-price = "1000000000" + +# Minimum gas limit for transactions included in blocks +gas-floor = "0" + +# Maximum gas limit for transactions included in blocks +gas-ceil = "30000000" + +# Whether to enable recommit feature +recommit = "2s" + +# Timeout for creating a new payload +new-payload-timeout = "2s" + + # Gas price oracle settings for Polaris [polaris.polar.gpo] # Number of blocks to check for gas prices -blocks = 20 +blocks = "20" # Percentile of gas price to use -percentile = 60 +percentile = "60" # Maximum header history for gas price determination -max-header-history = 1024 +max-header-history = "1024" # Maximum block history for gas price determination -max-block-history = 1024 +max-block-history = "1024" # Default gas price value default = "1000000000" @@ -352,22 +377,22 @@ journal = "transactions.rlp" rejournal = "1h0m0s" # Minimum gas price to enforce for acceptance into the pool -price-limit = 1 +price-limit = "1" # Minimum price bump percentage to replace an already existing transaction (nonce) -price-bump = 10 +price-bump = "10" # Number of executable transaction slots guaranteed per account -account-slots = 16 +account-slots = "16" # Maximum number of executable transaction slots for all accounts -account-queue = 64 +account-queue = "64" # Maximum number of non-executable transaction slots permitted per account -global-slots = 5120 +global-slots = "5120" # Maximum number of non-executable transaction slots for all accounts -global-queue = 1024 +global-queue = "1024" # Maximum amount of time non-executable transaction are queued lifetime = "3h0m0s" diff --git a/e2e/precompile/polard/config/app.toml b/e2e/precompile/polard/config/app.toml index a7615f28d..cc91de3f2 100644 --- a/e2e/precompile/polard/config/app.toml +++ b/e2e/precompile/polard/config/app.toml @@ -240,6 +240,7 @@ rpc-evm-timeout = "5s" rpc-tx-fee-cap = "1" +# Chain config [polaris.polar.chain] chain-id = "2061" @@ -295,37 +296,61 @@ merge-netsplit-block = "0" shanghai-time = "0" # Cancun switch time (nil == no fork, 0 = already on cancun) -cancun-time = "null" +cancun-time = "" # Prague switch time (nil == no fork, 0 = already on prague) -prague-time = "null" +prague-time = "" # Verkle switch time (nil == no fork, 0 = already on verkle) -verkle-time = "null" +verkle-time = "" # Terminal total difficulty terminal-total-difficulty = "0" # Whether terminal total difficulty has passed -terminal-total-difficulty-passed = true +terminal-total-difficulty-passed = "true" # DevMode enabled is-dev-mode = false +# Miner config +[polaris.polar.miner] +# The address to which mining rewards will be sent +etherbase = "0x0000000000000000000000000000000000000000" + +# Extra data included in mined blocks +extra-data = "0x" + +# Gas price for transactions included in blocks +gas-price = "1000000000" + +# Minimum gas limit for transactions included in blocks +gas-floor = "0" + +# Maximum gas limit for transactions included in blocks +gas-ceil = "30000000" + +# Whether to enable recommit feature +recommit = "2s" + +# Timeout for creating a new payload +new-payload-timeout = "2s" + + # Gas price oracle settings for Polaris [polaris.polar.gpo] # Number of blocks to check for gas prices -blocks = 20 +blocks = "20" # Percentile of gas price to use -percentile = 60 +percentile = "60" # Maximum header history for gas price determination -max-header-history = 1024 +max-header-history = "1024" # Maximum block history for gas price determination -max-block-history = 1024 +max-block-history = "1024" # Default gas price value default = "1000000000" @@ -352,22 +377,22 @@ journal = "transactions.rlp" rejournal = "1h0m0s" # Minimum gas price to enforce for acceptance into the pool -price-limit = 1 +price-limit = "1" # Minimum price bump percentage to replace an already existing transaction (nonce) -price-bump = 10 +price-bump = "10" # Number of executable transaction slots guaranteed per account -account-slots = 16 +account-slots = "16" # Maximum number of executable transaction slots for all accounts -account-queue = 64 +account-queue = "64" # Maximum number of non-executable transaction slots permitted per account -global-slots = 5120 +global-slots = "5120" # Maximum number of non-executable transaction slots for all accounts -global-queue = 1024 +global-queue = "1024" # Maximum amount of time non-executable transaction are queued lifetime = "3h0m0s" diff --git a/e2e/testapp/docker/local/config/app.toml b/e2e/testapp/docker/local/config/app.toml index a7615f28d..cc91de3f2 100644 --- a/e2e/testapp/docker/local/config/app.toml +++ b/e2e/testapp/docker/local/config/app.toml @@ -240,6 +240,7 @@ rpc-evm-timeout = "5s" rpc-tx-fee-cap = "1" +# Chain config [polaris.polar.chain] chain-id = "2061" @@ -295,37 +296,61 @@ merge-netsplit-block = "0" shanghai-time = "0" # Cancun switch time (nil == no fork, 0 = already on cancun) -cancun-time = "null" +cancun-time = "" # Prague switch time (nil == no fork, 0 = already on prague) -prague-time = "null" +prague-time = "" # Verkle switch time (nil == no fork, 0 = already on verkle) -verkle-time = "null" +verkle-time = "" # Terminal total difficulty terminal-total-difficulty = "0" # Whether terminal total difficulty has passed -terminal-total-difficulty-passed = true +terminal-total-difficulty-passed = "true" # DevMode enabled is-dev-mode = false +# Miner config +[polaris.polar.miner] +# The address to which mining rewards will be sent +etherbase = "0x0000000000000000000000000000000000000000" + +# Extra data included in mined blocks +extra-data = "0x" + +# Gas price for transactions included in blocks +gas-price = "1000000000" + +# Minimum gas limit for transactions included in blocks +gas-floor = "0" + +# Maximum gas limit for transactions included in blocks +gas-ceil = "30000000" + +# Whether to enable recommit feature +recommit = "2s" + +# Timeout for creating a new payload +new-payload-timeout = "2s" + + # Gas price oracle settings for Polaris [polaris.polar.gpo] # Number of blocks to check for gas prices -blocks = 20 +blocks = "20" # Percentile of gas price to use -percentile = 60 +percentile = "60" # Maximum header history for gas price determination -max-header-history = 1024 +max-header-history = "1024" # Maximum block history for gas price determination -max-block-history = 1024 +max-block-history = "1024" # Default gas price value default = "1000000000" @@ -352,22 +377,22 @@ journal = "transactions.rlp" rejournal = "1h0m0s" # Minimum gas price to enforce for acceptance into the pool -price-limit = 1 +price-limit = "1" # Minimum price bump percentage to replace an already existing transaction (nonce) -price-bump = 10 +price-bump = "10" # Number of executable transaction slots guaranteed per account -account-slots = 16 +account-slots = "16" # Maximum number of executable transaction slots for all accounts -account-queue = 64 +account-queue = "64" # Maximum number of non-executable transaction slots permitted per account -global-slots = 5120 +global-slots = "5120" # Maximum number of non-executable transaction slots for all accounts -global-queue = 1024 +global-queue = "1024" # Maximum amount of time non-executable transaction are queued lifetime = "3h0m0s" diff --git a/eth/common/hexutil/imported.go b/eth/common/hexutil/imported.go index 29b742112..86a99a4d8 100644 --- a/eth/common/hexutil/imported.go +++ b/eth/common/hexutil/imported.go @@ -29,4 +29,7 @@ type ( Uint = hexutil.Uint ) -var MustDecode = hexutil.MustDecode +var ( + MustDecode = hexutil.MustDecode + Decode = hexutil.Decode +) diff --git a/eth/core/types/transaction.rlpgen.go b/eth/core/types/transaction.rlpgen.go index c335ec137..5006261ca 100644 --- a/eth/core/types/transaction.rlpgen.go +++ b/eth/core/types/transaction.rlpgen.go @@ -1,8 +1,5 @@ // Code generated by rlpgen. DO NOT EDIT. -//go:build !norlpgen -// +build !norlpgen - package types import "github.com/ethereum/go-ethereum/common" diff --git a/eth/polar/config.go b/eth/polar/config.go index 66145cd7a..e1b943f53 100644 --- a/eth/polar/config.go +++ b/eth/polar/config.go @@ -27,6 +27,7 @@ import ( "github.com/ethereum/go-ethereum/core/txpool/legacypool" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/ethereum/go-ethereum/eth/gasprice" + "github.com/ethereum/go-ethereum/miner" "pkg.berachain.dev/polaris/eth/params" ) @@ -45,6 +46,7 @@ func DefaultConfig() *Config { gpoConfig.Default = big.NewInt(gpoDefault) return &Config{ Chain: *params.DefaultChainConfig, + Miner: miner.DefaultConfig, GPO: gpoConfig, LegacyTxPool: legacypool.DefaultConfig, RPCGasCap: ethconfig.Defaults.RPCGasCap, @@ -58,6 +60,9 @@ type Config struct { // The chain configuration to use. Chain params.ChainConfig + // Mining options + Miner miner.Config + // Gas Price Oracle config. GPO gasprice.Config