diff --git a/beacond/cmd/defaults.go b/beacond/cmd/defaults.go index 695d0dc215..e4ede16b88 100644 --- a/beacond/cmd/defaults.go +++ b/beacond/cmd/defaults.go @@ -21,7 +21,6 @@ package main import ( - cometbft "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" "github.com/berachain/beacon-kit/mod/node-core/pkg/components" ) @@ -106,7 +105,7 @@ func DefaultComponents() []any { *ExecutionPayload, *ExecutionPayloadHeader, *KVStore, *Logger, ], components.ProvideReportingService[*Logger], - components.ProvideCometBFTService, + components.ProvideCometBFTService[*Logger], components.ProvideServiceRegistry[ *AvailabilityStore, *BeaconBlock, *BeaconBlockBody, *BeaconBlockHeader, *BlockStore, *BeaconState, @@ -149,7 +148,7 @@ func DefaultComponents() []any { *AvailabilityStore, *BeaconBlock, *BeaconBlockBody, *BeaconBlockHeader, *BlockStore, *BeaconState, *BeaconStateMarshallable, *BlobSidecars, *Deposit, *DepositStore, - *ExecutionPayloadHeader, *KVStore, *cometbft.Service, *StorageBackend, + *ExecutionPayloadHeader, *KVStore, *CometBFTService, *StorageBackend, ], ) @@ -159,7 +158,7 @@ func DefaultComponents() []any { *ExecutionPayloadHeader, *KVStore, NodeAPIContext, ], components.ProvideNodeAPIBeaconHandler[ - *BeaconBlockHeader, *BeaconState, *cometbft.Service, NodeAPIContext, + *BeaconBlockHeader, *BeaconState, *CometBFTService, NodeAPIContext, ], components.ProvideNodeAPIBuilderHandler[NodeAPIContext], components.ProvideNodeAPIConfigHandler[NodeAPIContext], @@ -168,7 +167,7 @@ func DefaultComponents() []any { components.ProvideNodeAPINodeHandler[NodeAPIContext], components.ProvideNodeAPIProofHandler[ *BeaconBlockHeader, *BeaconState, *BeaconStateMarshallable, - *ExecutionPayloadHeader, *KVStore, *cometbft.Service, NodeAPIContext, + *ExecutionPayloadHeader, *KVStore, *CometBFTService, NodeAPIContext, ], ) diff --git a/beacond/cmd/main.go b/beacond/cmd/main.go index a318b92eef..d30d80302a 100644 --- a/beacond/cmd/main.go +++ b/beacond/cmd/main.go @@ -65,7 +65,6 @@ func run() error { clicomponents.DefaultClientComponents(), // TODO: remove these, and eventually pull cfg and chainspec // from built node - nodecomponents.ProvideConfig, nodecomponents.ProvideChainSpec, ), ), diff --git a/beacond/cmd/types.go b/beacond/cmd/types.go index 14ffa27cfa..32f851a73e 100644 --- a/beacond/cmd/types.go +++ b/beacond/cmd/types.go @@ -111,6 +111,9 @@ type ( *PayloadAttributes, ] + // CometBFTService is a type alias for the CometBFT service. + CometBFTService = cometbft.Service[*Logger] + // ConsensusMiddleware is a type alias for the consensus middleware. ConsensusMiddleware = cometbft.MiddlewareI @@ -348,7 +351,7 @@ type ( *Eth1Data, *ExecutionPayloadHeader, *Fork, - *cometbft.Service, + *CometBFTService, *KVStore, *StorageBackend, *Validator, diff --git a/mod/cli/go.mod b/mod/cli/go.mod index df38df11f5..72f1532495 100644 --- a/mod/cli/go.mod +++ b/mod/cli/go.mod @@ -21,9 +21,7 @@ replace ( ) require ( - cosmossdk.io/core v1.0.0 cosmossdk.io/depinject v1.0.0 - cosmossdk.io/log v1.4.1 github.com/berachain/beacon-kit/mod/config v0.0.0-20240705193247-d464364483df github.com/berachain/beacon-kit/mod/consensus v0.0.0-20240821053614-036c5d2945f0 github.com/berachain/beacon-kit/mod/consensus-types v0.0.0-20240821182712-08bbb9c7d685 @@ -43,7 +41,9 @@ require ( ) require ( + cosmossdk.io/core v1.0.0 // indirect cosmossdk.io/errors/v2 v2.0.0-20240731132947-df72853b3ca5 // indirect + cosmossdk.io/log v1.4.1 // indirect cosmossdk.io/schema v0.1.1 // indirect github.com/berachain/beacon-kit/mod/beacon v0.0.0-20240821052951-c15422305b4e // indirect github.com/berachain/beacon-kit/mod/chain-spec v0.0.0-20240705193247-d464364483df // indirect diff --git a/mod/cli/pkg/builder/builder.go b/mod/cli/pkg/builder/builder.go index e27c4b5101..7f0491b7b9 100644 --- a/mod/cli/pkg/builder/builder.go +++ b/mod/cli/pkg/builder/builder.go @@ -52,7 +52,7 @@ type CLIBuilder[ // nodeBuilderFunc is a function that builds the Node, // eventually called by the cosmos-sdk. // TODO: CLI should not know about the AppCreator - nodeBuilderFunc servertypes.AppCreator[T] + nodeBuilderFunc servertypes.AppCreator[T, LoggerT] } // New returns a new CLIBuilder with the given options. @@ -111,7 +111,7 @@ func (cb *CLIBuilder[ // apply default root command setup cmdlib.DefaultRootCommandSetup[T, ExecutionPayloadT]( rootCmd, - &cometbft.Service{}, + &cometbft.Service[LoggerT]{}, cb.nodeBuilderFunc, chainSpec, ) diff --git a/mod/cli/pkg/builder/options.go b/mod/cli/pkg/builder/options.go index 54dcd70f1e..b9aa488ece 100644 --- a/mod/cli/pkg/builder/options.go +++ b/mod/cli/pkg/builder/options.go @@ -73,7 +73,7 @@ func WithNodeBuilderFunc[ ExecutionPayloadT constraints.EngineType[ExecutionPayloadT], LoggerT log.AdvancedLogger[LoggerT], ]( - nodeBuilderFunc servertypes.AppCreator[T], + nodeBuilderFunc servertypes.AppCreator[T, LoggerT], ) Opt[T, ExecutionPayloadT, LoggerT] { return func(cb *CLIBuilder[T, ExecutionPayloadT, LoggerT]) { cb.nodeBuilderFunc = nodeBuilderFunc diff --git a/mod/cli/pkg/commands/genesis/collect.go b/mod/cli/pkg/commands/genesis/collect.go index e7b9b62841..d11b4b13ae 100644 --- a/mod/cli/pkg/commands/genesis/collect.go +++ b/mod/cli/pkg/commands/genesis/collect.go @@ -25,10 +25,10 @@ import ( "path/filepath" "strings" + "github.com/berachain/beacon-kit/mod/cli/pkg/context" "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" "github.com/berachain/beacon-kit/mod/errors" "github.com/berachain/beacon-kit/mod/primitives/pkg/encoding/json" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/spf13/afero" @@ -42,7 +42,7 @@ func CollectGenesisDepositsCmd() *cobra.Command { Use: "collect-premined-deposits", Short: "adds a validator to the genesis file", RunE: func(cmd *cobra.Command, _ []string) error { - config := client.GetConfigFromCmd(cmd) + config := context.GetConfigFromCmd(cmd) appGenesis, err := genutiltypes.AppGenesisFromFile( config.GenesisFile(), diff --git a/mod/cli/pkg/commands/genesis/deposit.go b/mod/cli/pkg/commands/genesis/deposit.go index 0373fc6ff6..bef7984ca7 100644 --- a/mod/cli/pkg/commands/genesis/deposit.go +++ b/mod/cli/pkg/commands/genesis/deposit.go @@ -25,6 +25,7 @@ import ( "os" "path/filepath" + "github.com/berachain/beacon-kit/mod/cli/pkg/context" "github.com/berachain/beacon-kit/mod/cli/pkg/utils/parser" "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" "github.com/berachain/beacon-kit/mod/errors" @@ -35,7 +36,6 @@ import ( "github.com/berachain/beacon-kit/mod/primitives/pkg/encoding/json" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" "github.com/berachain/beacon-kit/mod/primitives/pkg/version" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/spf13/afero" @@ -49,7 +49,7 @@ func AddGenesisDepositCmd(cs common.ChainSpec) *cobra.Command { Use: "add-premined-deposit", Short: "adds a validator to the genesis file", RunE: func(cmd *cobra.Command, _ []string) error { - config := client.GetConfigFromCmd(cmd) + config := context.GetConfigFromCmd(cmd) _, valPubKey, err := genutil.InitializeNodeValidatorFiles( config, crypto.CometBLSType, @@ -69,7 +69,7 @@ func AddGenesisDepositCmd(cs common.ChainSpec) *cobra.Command { // Get the BLS signer. blsSigner, err := components.ProvideBlsSigner( components.BlsSignerInput{ - AppOpts: client.GetViperFromCmd(cmd), + AppOpts: context.GetViperFromCmd(cmd), }, ) if err != nil { diff --git a/mod/cli/pkg/commands/genesis/payload.go b/mod/cli/pkg/commands/genesis/payload.go index 2e2fb5d7ac..deccc019ad 100644 --- a/mod/cli/pkg/commands/genesis/payload.go +++ b/mod/cli/pkg/commands/genesis/payload.go @@ -23,6 +23,7 @@ package genesis import ( "unsafe" + "github.com/berachain/beacon-kit/mod/cli/pkg/context" "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" engineprimitives "github.com/berachain/beacon-kit/mod/engine-primitives/pkg/engine-primitives" "github.com/berachain/beacon-kit/mod/errors" @@ -32,7 +33,6 @@ import ( "github.com/berachain/beacon-kit/mod/primitives/pkg/encoding/json" "github.com/berachain/beacon-kit/mod/primitives/pkg/math" "github.com/berachain/beacon-kit/mod/primitives/pkg/version" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/spf13/afero" @@ -65,7 +65,7 @@ func AddExecutionPayloadCmd(chainSpec common.ChainSpec) *cobra.Command { nil, ).ExecutionPayload - config := client.GetConfigFromCmd(cmd) + config := context.GetConfigFromCmd(cmd) appGenesis, err := genutiltypes.AppGenesisFromFile( config.GenesisFile(), diff --git a/mod/cli/pkg/commands/server/rollback.go b/mod/cli/pkg/commands/server/rollback.go index 9f188f15a0..d79cc31d57 100644 --- a/mod/cli/pkg/commands/server/rollback.go +++ b/mod/cli/pkg/commands/server/rollback.go @@ -26,20 +26,24 @@ import ( "cosmossdk.io/store" types "github.com/berachain/beacon-kit/mod/cli/pkg/commands/server/types" + clicontext "github.com/berachain/beacon-kit/mod/cli/pkg/context" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/storage/pkg/db" cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" ) // NewRollbackCmd creates a command to rollback CometBFT and multistore state by // one height. -func NewRollbackCmd[T interface { - Start(context.Context) error - CommitMultiStore() store.CommitMultiStore -}]( - appCreator types.AppCreator[T], +func NewRollbackCmd[ + T interface { + Start(context.Context) error + CommitMultiStore() store.CommitMultiStore + }, + LoggerT log.AdvancedLogger[LoggerT], +]( + appCreator types.AppCreator[T, LoggerT], ) *cobra.Command { var removeBlock bool @@ -56,9 +60,9 @@ restarting CometBFT the transactions in block n will be re-executed against the application. `, RunE: func(cmd *cobra.Command, _ []string) error { - v := client.GetViperFromCmd(cmd) - logger := client.GetLoggerFromCmd(cmd) - cfg := client.GetConfigFromCmd(cmd) + v := clicontext.GetViperFromCmd(cmd) + logger := clicontext.GetLoggerFromCmd[LoggerT](cmd) + cfg := clicontext.GetConfigFromCmd(cmd) db, err := db.OpenDB(cfg.RootDir, dbm.PebbleDBBackend) if err != nil { diff --git a/mod/cli/pkg/commands/server/start.go b/mod/cli/pkg/commands/server/start.go index b2764cc3c5..134d7f246f 100644 --- a/mod/cli/pkg/commands/server/start.go +++ b/mod/cli/pkg/commands/server/start.go @@ -26,10 +26,11 @@ import ( pruningtypes "cosmossdk.io/store/pruning/types" types "github.com/berachain/beacon-kit/mod/cli/pkg/commands/server/types" + clicontext "github.com/berachain/beacon-kit/mod/cli/pkg/context" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/storage/pkg/db" cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" ) @@ -51,30 +52,38 @@ const ( // StartCmdOptions defines options that can be customized in // `StartCmdWithOptions`,. -type StartCmdOptions[T interface { - Start(context.Context) error -}] struct { +type StartCmdOptions[ + T interface { + Start(context.Context) error + }, +] struct { // AddFlags allows adding custom flags to the start command. AddFlags func(cmd *cobra.Command) } // StartCmd runs the service passed in, either stand-alone or in-process with // CometBFT. -func StartCmd[T interface { - Start(context.Context) error -}]( - appCreator types.AppCreator[T], +func StartCmd[ + T interface { + Start(context.Context) error + }, + LoggerT log.AdvancedLogger[LoggerT], +]( + appCreator types.AppCreator[T, LoggerT], ) *cobra.Command { - return StartCmdWithOptions(appCreator, StartCmdOptions[T]{}) + return StartCmdWithOptions[T, LoggerT](appCreator, StartCmdOptions[T]{}) } // StartCmdWithOptions runs the service passed in, either stand-alone or // in-process with // CometBFT. -func StartCmdWithOptions[T interface { - Start(context.Context) error -}]( - appCreator types.AppCreator[T], +func StartCmdWithOptions[ + T interface { + Start(context.Context) error + }, + LoggerT log.AdvancedLogger[LoggerT], +]( + appCreator types.AppCreator[T, LoggerT], opts StartCmdOptions[T], ) *cobra.Command { //nolint:lll // its okay. @@ -96,9 +105,9 @@ custom: allow pruning options to be manually specified through 'pruning-keep-rec `, RunE: func(cmd *cobra.Command, _ []string) error { - logger := client.GetLoggerFromCmd(cmd) - cfg := client.GetConfigFromCmd(cmd) - v := client.GetViperFromCmd(cmd) + logger := clicontext.GetLoggerFromCmd[LoggerT](cmd) + cfg := clicontext.GetConfigFromCmd(cmd) + v := clicontext.GetViperFromCmd(cmd) _, err := GetPruningOptionsFromFlags(v) if err != nil { return err @@ -123,9 +132,11 @@ custom: allow pruning options to be manually specified through 'pruning-keep-rec // addStartNodeFlags should be added to any CLI commands that start the network. // //nolint:lll // todo fix. -func addStartNodeFlags[T interface { - Start(context.Context) error -}]( +func addStartNodeFlags[ + T interface { + Start(context.Context) error + }, +]( cmd *cobra.Command, opts StartCmdOptions[T], ) { diff --git a/mod/cli/pkg/commands/server/types/app.go b/mod/cli/pkg/commands/server/types/app.go index 9f1e99a6f7..385571ae5b 100644 --- a/mod/cli/pkg/commands/server/types/app.go +++ b/mod/cli/pkg/commands/server/types/app.go @@ -24,7 +24,7 @@ import ( "context" "io" - "cosmossdk.io/log" + "github.com/berachain/beacon-kit/mod/log" cmtcfg "github.com/cometbft/cometbft/config" dbm "github.com/cosmos/cosmos-db" ) @@ -45,9 +45,14 @@ type ( // AppCreator is a function that allows us to lazily initialize an // application using various configurations. - AppCreator[T interface { - Start(ctx context.Context) error - }] func( - log.Logger, dbm.DB, io.Writer, *cmtcfg.Config, AppOptions, - ) T + AppCreator[ + AppT interface { + Start(ctx context.Context) error + }, + LoggerT interface { + log.AdvancedLogger[LoggerT] + }, + ] func( + LoggerT, dbm.DB, io.Writer, *cmtcfg.Config, AppOptions, + ) AppT ) diff --git a/mod/cli/pkg/commands/setup.go b/mod/cli/pkg/commands/setup.go index 983b6b3302..140b153673 100644 --- a/mod/cli/pkg/commands/setup.go +++ b/mod/cli/pkg/commands/setup.go @@ -29,6 +29,7 @@ import ( "github.com/berachain/beacon-kit/mod/cli/pkg/flags" cmtcli "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/cli" cometbft "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/node-core/pkg/types" "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/constraints" @@ -40,10 +41,11 @@ import ( func DefaultRootCommandSetup[ T types.Node, ExecutionPayloadT constraints.EngineType[ExecutionPayloadT], + LoggerT log.AdvancedLogger[LoggerT], ]( root *Root, - mm *cometbft.Service, - appCreator servertypes.AppCreator[T], + mm *cometbft.Service[LoggerT], + appCreator servertypes.AppCreator[T, LoggerT], chainSpec common.ChainSpec, ) { // Add all the commands to the root command. diff --git a/mod/cli/pkg/components/logger.go b/mod/cli/pkg/components/logger.go index 9ce2fef438..29ffc2196e 100644 --- a/mod/cli/pkg/components/logger.go +++ b/mod/cli/pkg/components/logger.go @@ -30,7 +30,6 @@ import ( type LoggerInput struct { depinject.In - Out io.Writer } @@ -39,6 +38,8 @@ type LoggerInput struct { func ProvideLogger( in LoggerInput, ) *phuslu.Logger { + // the logger config should be passed in here, but it is not yet populated + // so we pass in nil for now to get the default logger. logger := phuslu.NewLogger(in.Out, nil) logger.AddKeyColor("error", log.Red) logger.AddKeyColor("err", log.Red) diff --git a/mod/cli/pkg/config/server.go b/mod/cli/pkg/config/server.go index ad516fc4f7..4df591a9f3 100644 --- a/mod/cli/pkg/config/server.go +++ b/mod/cli/pkg/config/server.go @@ -28,12 +28,10 @@ import ( "path/filepath" "strings" - corectx "cosmossdk.io/core/context" - sdklog "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/log" + clicontext "github.com/berachain/beacon-kit/mod/cli/pkg/context" "github.com/berachain/beacon-kit/mod/errors" "github.com/berachain/beacon-kit/mod/log" cmtcfg "github.com/cometbft/cometbft/config" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -60,7 +58,7 @@ func SetupCommand[ } if err := handleConfigs( - client.GetViperFromCmd(cmd), + clicontext.GetViperFromCmd(cmd), appTemplate, appConfig, cmtConfig, ); err != nil { return err @@ -93,9 +91,9 @@ func InitializeCmd[ } ctx := cmd.Context() - ctx = context.WithValue(ctx, corectx.ViperContextKey, viper) + ctx = context.WithValue(ctx, clicontext.ViperContextKey, viper) ctx = context.WithValue( - ctx, corectx.LoggerContextKey, sdklog.WrapSDKLogger(logger), + ctx, clicontext.LoggerContextKey, logger, ) cmd.SetContext(ctx) diff --git a/mod/cli/pkg/context/cmd.go b/mod/cli/pkg/context/cmd.go new file mode 100644 index 0000000000..c002e8e808 --- /dev/null +++ b/mod/cli/pkg/context/cmd.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: BUSL-1.1 +// +// Copyright (C) 2024, Berachain Foundation. All rights reserved. +// Use of this software is governed 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 context + +import ( + "github.com/berachain/beacon-kit/mod/log" + "github.com/berachain/beacon-kit/mod/log/pkg/phuslu" + cmtcfg "github.com/cometbft/cometbft/config" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func GetViperFromCmd(cmd *cobra.Command) *viper.Viper { + value := cmd.Context().Value(ViperContextKey) + v, ok := value.(*viper.Viper) + if !ok { + return viper.New() + } + return v +} + +func GetLoggerFromCmd[ + LoggerT log.AdvancedLogger[LoggerT], +](cmd *cobra.Command) LoggerT { + v := cmd.Context().Value(LoggerContextKey) + logger, ok := v.(LoggerT) + if !ok { + return any(phuslu.NewLogger(cmd.OutOrStdout(), nil)).(LoggerT) + } + return logger +} + +func GetConfigFromCmd(cmd *cobra.Command) *cmtcfg.Config { + v := cmd.Context().Value(ViperContextKey) + viper, ok := v.(*viper.Viper) + if !ok { + return cmtcfg.DefaultConfig() + } + return GetConfigFromViper(viper) +} + +func GetConfigFromViper(v *viper.Viper) *cmtcfg.Config { + conf := cmtcfg.DefaultConfig() + err := v.Unmarshal(conf) + rootDir := v.GetString(flags.FlagHome) + if err != nil { + return cmtcfg.DefaultConfig().SetRoot(rootDir) + } + return conf.SetRoot(rootDir) +} diff --git a/mod/node-core/pkg/builder/invokers.go b/mod/cli/pkg/context/keys.go similarity index 67% rename from mod/node-core/pkg/builder/invokers.go rename to mod/cli/pkg/context/keys.go index f8cb2d1a49..c43460be27 100644 --- a/mod/node-core/pkg/builder/invokers.go +++ b/mod/cli/pkg/context/keys.go @@ -18,26 +18,15 @@ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND // TITLE. -package builder +package context -import ( - "github.com/berachain/beacon-kit/mod/config" - "github.com/berachain/beacon-kit/mod/log" +type ( + loggerContextKey struct{} + viperContextKey struct{} ) -// SetLoggerConfig sets the logger configuration. It acts as an invoker -// for the depinject framework. -func SetLoggerConfig[ - LoggerT interface { - log.AdvancedLogger[LoggerT] - log.Configurable[LoggerT, LoggerConfigT] - }, - LoggerConfigT any, -]( - config *config.Config, - logger LoggerT, -) { - logger.WithConfig( - any(config.GetLogger()).(LoggerConfigT), - ) -} +//nolint:gochecknoglobals // context keys +var ( + LoggerContextKey loggerContextKey + ViperContextKey viperContextKey +) diff --git a/mod/consensus/go.mod b/mod/consensus/go.mod index 2e73e80766..bbe9e30617 100644 --- a/mod/consensus/go.mod +++ b/mod/consensus/go.mod @@ -166,6 +166,7 @@ require ( github.com/opencontainers/image-spec v1.1.0 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/petermattis/goid v0.0.0-20240607163614-bb94eb51e7a7 // indirect + github.com/phuslu/log v1.0.110 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.20.1 // indirect diff --git a/mod/consensus/go.sum b/mod/consensus/go.sum index ae9d253953..88950479c4 100644 --- a/mod/consensus/go.sum +++ b/mod/consensus/go.sum @@ -481,6 +481,8 @@ github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/petermattis/goid v0.0.0-20240607163614-bb94eb51e7a7 h1:CtBLeckhC0zAXgp5V8uR30CNYH0JgCJoxCg5+6i2zQk= github.com/petermattis/goid v0.0.0-20240607163614-bb94eb51e7a7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/phuslu/log v1.0.110 h1:9WQnpL1/CBi3IwZaVadYnI/i0bgobTvit2ayXIgSg4c= +github.com/phuslu/log v1.0.110/go.mod h1:F8osGJADo5qLK/0F88djWwdyoZZ9xDJQL1HYRHFEkS0= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= diff --git a/mod/consensus/pkg/cometbft/cli/commands.go b/mod/consensus/pkg/cometbft/cli/commands.go index c3f541801d..2173b08df2 100644 --- a/mod/consensus/pkg/cometbft/cli/commands.go +++ b/mod/consensus/pkg/cometbft/cli/commands.go @@ -23,11 +23,11 @@ package server import ( "context" - "cosmossdk.io/log" "cosmossdk.io/store" types "github.com/berachain/beacon-kit/mod/cli/pkg/commands/server/types" - + clicontext "github.com/berachain/beacon-kit/mod/cli/pkg/context" service "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/storage/pkg/db" cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" cmtcfg "github.com/cometbft/cometbft/config" @@ -47,11 +47,13 @@ import ( ) // Commands add server commands. -func Commands[T interface { - Start(context.Context) error - CommitMultiStore() store.CommitMultiStore -}]( - appCreator types.AppCreator[T], +func Commands[ + T interface { + Start(context.Context) error + CommitMultiStore() store.CommitMultiStore + }, LoggerT log.AdvancedLogger[LoggerT], +]( + appCreator types.AppCreator[T, LoggerT], ) *cobra.Command { cometCmd := &cobra.Command{ Use: "comet", @@ -122,7 +124,7 @@ func ShowNodeIDCmd() *cobra.Command { Use: "show-node-id", Short: "Show this node's ID", RunE: func(cmd *cobra.Command, args []string) error { - cfg := client.GetConfigFromCmd(cmd) + cfg := clicontext.GetConfigFromCmd(cmd) nodeKey, err := p2p.LoadNodeKey(cfg.NodeKeyFile()) if err != nil { return err @@ -140,7 +142,7 @@ func ShowValidatorCmd() *cobra.Command { Use: "show-validator", Short: "Show this node's CometBFT validator info", RunE: func(cmd *cobra.Command, args []string) error { - cfg := client.GetConfigFromCmd(cmd) + cfg := clicontext.GetConfigFromCmd(cmd) privValidator := pvm.LoadFilePV( cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile(), @@ -175,7 +177,7 @@ func ShowAddressCmd() *cobra.Command { Use: "show-address", Short: "Shows this node's CometBFT validator consensus address", RunE: func(cmd *cobra.Command, args []string) error { - cfg := client.GetConfigFromCmd(cmd) + cfg := clicontext.GetConfigFromCmd(cmd) privValidator := pvm.LoadFilePV( cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile(), @@ -222,17 +224,17 @@ func VersionCmd() *cobra.Command { func BootstrapStateCmd[T interface { Start(context.Context) error CommitMultiStore() store.CommitMultiStore -}]( - appCreator types.AppCreator[T], +}, LoggerT log.AdvancedLogger[LoggerT]]( + appCreator types.AppCreator[T, LoggerT], ) *cobra.Command { cmd := &cobra.Command{ Use: "bootstrap-state", Short: "Bootstrap CometBFT state at an arbitrary block height using a light client", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - logger := log.NewLogger(cmd.OutOrStdout()) - cfg := client.GetConfigFromCmd(cmd) - v := client.GetViperFromCmd(cmd) + logger := clicontext.GetLoggerFromCmd[LoggerT](cmd) + cfg := clicontext.GetConfigFromCmd(cmd) + v := clicontext.GetViperFromCmd(cmd) height, err := cmd.Flags().GetInt64("height") if err != nil { diff --git a/mod/consensus/pkg/cometbft/service/abci.go b/mod/consensus/pkg/cometbft/service/abci.go index b4174a9813..e1b6a27dc4 100644 --- a/mod/consensus/pkg/cometbft/service/abci.go +++ b/mod/consensus/pkg/cometbft/service/abci.go @@ -30,6 +30,7 @@ import ( "cosmossdk.io/store/rootmulti" ctypes "github.com/berachain/beacon-kit/mod/consensus-types/pkg/types" + servercmtlog "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/log" "github.com/berachain/beacon-kit/mod/consensus/pkg/types" errorsmod "github.com/berachain/beacon-kit/mod/errors" "github.com/berachain/beacon-kit/mod/primitives/pkg/encoding/json" @@ -42,7 +43,7 @@ import ( ) //nolint:gocognit // todo fix. -func (s *Service) InitChain( +func (s *Service[LoggerT]) InitChain( _ context.Context, req *cmtabci.InitChainRequest, ) (*cmtabci.InitChainResponse, error) { @@ -156,7 +157,7 @@ func (s *Service) InitChain( } // InitChainer initializes the chain. -func (s *Service) initChainer( +func (s *Service[LoggerT]) initChainer( ctx sdk.Context, req *cmtabci.InitChainRequest, ) (*cmtabci.InitChainResponse, error) { @@ -185,7 +186,7 @@ func (s *Service) initChainer( }, nil } -func (s *Service) Info( +func (s *Service[LoggerT]) Info( context.Context, *cmtabci.InfoRequest, ) (*cmtabci.InfoResponse, error) { @@ -213,7 +214,7 @@ func (s *Service) Info( // PrepareProposal implements the PrepareProposal ABCI method and returns a // ResponsePrepareProposal object to the client. -func (s *Service) PrepareProposal( +func (s *Service[LoggerT]) PrepareProposal( _ context.Context, req *cmtabci.PrepareProposalRequest, ) (*cmtabci.PrepareProposalResponse, error) { @@ -261,7 +262,7 @@ func (s *Service) PrepareProposal( // ProcessProposal implements the ProcessProposal ABCI method and returns a // ResponseProcessProposal object to the client. -func (s *Service) ProcessProposal( +func (s *Service[LoggerT]) ProcessProposal( _ context.Context, req *cmtabci.ProcessProposalRequest, ) (*cmtabci.ProcessProposalResponse, error) { @@ -314,7 +315,7 @@ func (s *Service) ProcessProposal( return resp, nil } -func (s *Service) internalFinalizeBlock( +func (s *Service[LoggerT]) internalFinalizeBlock( ctx context.Context, req *cmtabci.FinalizeBlockRequest, ) (*cmtabci.FinalizeBlockResponse, error) { @@ -401,7 +402,7 @@ func (s *Service) internalFinalizeBlock( }, nil } -func (s *Service) FinalizeBlock( +func (s *Service[_]) FinalizeBlock( _ context.Context, req *cmtabci.FinalizeBlockRequest, ) (*cmtabci.FinalizeBlockResponse, error) { @@ -420,7 +421,7 @@ func (s *Service) FinalizeBlock( // defined in config, Commit will execute a deferred function call to check // against that height and gracefully halt if it matches the latest committed // height. -func (s *Service) Commit( +func (s *Service[LoggerT]) Commit( context.Context, *cmtabci.CommitRequest, ) (*cmtabci.CommitResponse, error) { if s.finalizeBlockState == nil { @@ -451,7 +452,7 @@ func (s *Service) Commit( // Commit(), the application state transitions will be flushed to disk and as a // result, but we already have // an application Merkle root. -func (s *Service) workingHash() []byte { +func (s *Service[LoggerT]) workingHash() []byte { // Write the FinalizeBlock state into branched storage and commit the // MultiStore. The write to the FinalizeBlock state writes all state // transitions to the root @@ -476,7 +477,7 @@ func (s *Service) workingHash() []byte { // getContextForProposal returns the correct Context for PrepareProposal and // ProcessProposal. We use finalizeBlockState on the first block to be able to // access any state changes made in InitChain. -func (s *Service) getContextForProposal( +func (s *Service[LoggerT]) getContextForProposal( ctx sdk.Context, height int64, ) sdk.Context { @@ -493,7 +494,7 @@ func (s *Service) getContextForProposal( // CreateQueryContext creates a new sdk.Context for a query, taking as args // the block height and whether the query needs a proof or not. -func (s *Service) CreateQueryContext( +func (s *Service[LoggerT]) CreateQueryContext( height int64, prove bool, ) (sdk.Context, error) { @@ -540,7 +541,7 @@ func (s *Service) CreateQueryContext( ) } - return sdk.NewContext(cacheMS, true, s.logger), nil + return sdk.NewContext(cacheMS, true, servercmtlog.WrapSDKLogger(s.logger)), nil } // GetBlockRetentionHeight returns the height for which all blocks below this @@ -567,7 +568,7 @@ func (s *Service) CreateQueryContext( // all blocks, e.g. via a local config option min-retain-blocks. There may also // be a need to vary retention for other nodes, e.g. sentry nodes which do not // need historical blocks. -func (s *Service) GetBlockRetentionHeight(commitHeight int64) int64 { +func (s *Service[_]) GetBlockRetentionHeight(commitHeight int64) int64 { // pruning is disabled if minRetainBlocks is zero if s.minRetainBlocks == 0 { return 0 diff --git a/mod/consensus/pkg/cometbft/service/genesis.go b/mod/consensus/pkg/cometbft/service/genesis.go index 70ffbf590e..ec72d848d4 100644 --- a/mod/consensus/pkg/cometbft/service/genesis.go +++ b/mod/consensus/pkg/cometbft/service/genesis.go @@ -31,12 +31,12 @@ import ( ) // LoadHeight loads a particular height. -func (s *Service) LoadHeight(height int64) error { +func (s *Service[_]) LoadHeight(height int64) error { return s.LoadVersion(height) } // DefaultGenesis returns the default genesis state for the application. -func (s *Service) DefaultGenesis() map[string]json.RawMessage { +func (s *Service[_]) DefaultGenesis() map[string]json.RawMessage { // Implement the default genesis state for the application. // This should return a map of module names to their respective default // genesis states. @@ -50,7 +50,7 @@ func (s *Service) DefaultGenesis() map[string]json.RawMessage { } // ValidateGenesis validates the provided genesis state. -func (s *Service) ValidateGenesis( +func (s *Service[_]) ValidateGenesis( _ map[string]json.RawMessage, ) error { // Implement the validation logic for the provided genesis state. diff --git a/mod/consensus/pkg/cometbft/service/log/cmt_logger.go b/mod/consensus/pkg/cometbft/service/log/cmt_logger.go index e98ca52519..8b8a94ebda 100644 --- a/mod/consensus/pkg/cometbft/service/log/cmt_logger.go +++ b/mod/consensus/pkg/cometbft/service/log/cmt_logger.go @@ -21,22 +21,28 @@ package log import ( - "cosmossdk.io/log" + "github.com/berachain/beacon-kit/mod/log" cmtlog "github.com/cometbft/cometbft/libs/log" ) -var _ cmtlog.Logger = (*CometLoggerWrapper)(nil) +type CometLogger[LoggerT log.AdvancedLogger[LoggerT]] struct { + log.AdvancedLogger[LoggerT] +} + +func WrapCometLogger[LoggerT log.AdvancedLogger[LoggerT]]( + logger LoggerT, +) *CometLogger[LoggerT] { + return &CometLogger[LoggerT]{ + AdvancedLogger: logger, + } +} -// CometLoggerWrapper provides a wrapper around a cosmossdk.io/log instance. -// It implements CometBFT's Logger interface. -type CometLoggerWrapper struct { - log.Logger +func (l *CometLogger[LoggerT]) With(keyVals ...any) cmtlog.Logger { + return &CometLogger[LoggerT]{ + AdvancedLogger: l.AdvancedLogger.With(keyVals...), + } } -// With returns a new wrapped logger with additional context provided by a set -// of key/value tuples. The number of tuples must be even and the key of the -// tuple must be a string. -func (cmt CometLoggerWrapper) With(keyVals ...interface{}) cmtlog.Logger { - logger := cmt.Logger.With(keyVals...) - return CometLoggerWrapper{logger} +func (l *CometLogger[LoggerT]) Impl() any { + return l.AdvancedLogger } diff --git a/mod/consensus/pkg/cometbft/service/log/sdk_logger.go b/mod/consensus/pkg/cometbft/service/log/sdk_logger.go index 3c136be0af..c7658d2dc7 100644 --- a/mod/consensus/pkg/cometbft/service/log/sdk_logger.go +++ b/mod/consensus/pkg/cometbft/service/log/sdk_logger.go @@ -26,37 +26,23 @@ import ( ) type SDKLogger[LoggerT log.AdvancedLogger[LoggerT]] struct { - Logger LoggerT + log.AdvancedLogger[LoggerT] } func WrapSDKLogger[LoggerT log.AdvancedLogger[LoggerT]]( logger LoggerT, ) *SDKLogger[LoggerT] { return &SDKLogger[LoggerT]{ - Logger: logger, + AdvancedLogger: logger, } } -func (l *SDKLogger[LoggerT]) Info(msg string, keyVals ...any) { - l.Logger.Info(msg, keyVals...) -} - -func (l *SDKLogger[LoggerT]) Warn(msg string, keyVals ...any) { - l.Logger.Warn(msg, keyVals...) -} - -func (l *SDKLogger[LoggerT]) Error(msg string, keyVals ...any) { - l.Logger.Error(msg, keyVals...) -} - -func (l *SDKLogger[LoggerT]) Debug(msg string, keyVals ...any) { - l.Logger.Debug(msg, keyVals...) -} - func (l *SDKLogger[LoggerT]) With(keyVals ...any) sdklog.Logger { - return &SDKLogger[LoggerT]{Logger: l.Logger.With(keyVals...)} + return &SDKLogger[LoggerT]{ + AdvancedLogger: l.AdvancedLogger.With(keyVals...), + } } func (l *SDKLogger[LoggerT]) Impl() any { - return l.Logger + return l.AdvancedLogger } diff --git a/mod/consensus/pkg/cometbft/service/noops.go b/mod/consensus/pkg/cometbft/service/noops.go index b28fcf3bb2..c58d0bed93 100644 --- a/mod/consensus/pkg/cometbft/service/noops.go +++ b/mod/consensus/pkg/cometbft/service/noops.go @@ -26,56 +26,56 @@ import ( abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" ) -func (Service) Query( +func (Service[_]) Query( context.Context, *abci.QueryRequest, ) (*abci.QueryResponse, error) { return &abci.QueryResponse{}, nil } -func (Service) ListSnapshots( +func (Service[_]) ListSnapshots( context.Context, *abci.ListSnapshotsRequest, ) (*abci.ListSnapshotsResponse, error) { return &abci.ListSnapshotsResponse{}, nil } -func (Service) LoadSnapshotChunk( +func (Service[_]) LoadSnapshotChunk( context.Context, *abci.LoadSnapshotChunkRequest, ) (*abci.LoadSnapshotChunkResponse, error) { return &abci.LoadSnapshotChunkResponse{}, nil } -func (Service) OfferSnapshot( +func (Service[_]) OfferSnapshot( context.Context, *abci.OfferSnapshotRequest, ) (*abci.OfferSnapshotResponse, error) { return &abci.OfferSnapshotResponse{}, nil } -func (Service) ApplySnapshotChunk( +func (Service[_]) ApplySnapshotChunk( context.Context, *abci.ApplySnapshotChunkRequest, ) (*abci.ApplySnapshotChunkResponse, error) { return &abci.ApplySnapshotChunkResponse{}, nil } -func (Service) ExtendVote( +func (Service[_]) ExtendVote( context.Context, *abci.ExtendVoteRequest, ) (*abci.ExtendVoteResponse, error) { return &abci.ExtendVoteResponse{}, nil } -func (Service) VerifyVoteExtension( +func (Service[_]) VerifyVoteExtension( context.Context, *abci.VerifyVoteExtensionRequest, ) (*abci.VerifyVoteExtensionResponse, error) { return &abci.VerifyVoteExtensionResponse{}, nil } -func (*Service) CheckTx( +func (*Service[_]) CheckTx( context.Context, *abci.CheckTxRequest, ) (*abci.CheckTxResponse, error) { diff --git a/mod/consensus/pkg/cometbft/service/options.go b/mod/consensus/pkg/cometbft/service/options.go index 8e448ecff1..ad9a6116b3 100644 --- a/mod/consensus/pkg/cometbft/service/options.go +++ b/mod/consensus/pkg/cometbft/service/options.go @@ -27,58 +27,69 @@ import ( pruningtypes "cosmossdk.io/store/pruning/types" storetypes "cosmossdk.io/store/types" + "github.com/berachain/beacon-kit/mod/log" ) // File for storing in-package cometbft optional functions, // for options that need access to non-exported fields of the Service // SetPruning sets a pruning option on the multistore associated with the s. -func SetPruning(opts pruningtypes.PruningOptions) func(*Service) { - return func(bs *Service) { bs.cms.SetPruning(opts) } +func SetPruning[ + LoggerT log.AdvancedLogger[LoggerT], +](opts pruningtypes.PruningOptions) func(*Service[LoggerT]) { + return func(bs *Service[LoggerT]) { bs.cms.SetPruning(opts) } } // SetMinRetainBlocks returns a Service option function that sets the minimum // block retention height value when determining which heights to prune during // ABCI Commit. -func SetMinRetainBlocks(minRetainBlocks uint64) func(*Service) { - return func(bs *Service) { bs.setMinRetainBlocks(minRetainBlocks) } +func SetMinRetainBlocks[ + LoggerT log.AdvancedLogger[LoggerT], +](minRetainBlocks uint64) func(*Service[LoggerT]) { + return func(bs *Service[LoggerT]) { bs.setMinRetainBlocks(minRetainBlocks) } } // SetIAVLCacheSize provides a Service option function that sets the size of // IAVL cache. -func SetIAVLCacheSize(size int) func(*Service) { - return func(bs *Service) { bs.cms.SetIAVLCacheSize(size) } +func SetIAVLCacheSize[ + LoggerT log.AdvancedLogger[LoggerT], +](size int) func(*Service[LoggerT]) { + return func(bs *Service[LoggerT]) { bs.cms.SetIAVLCacheSize(size) } } // SetIAVLDisableFastNode enables(false)/disables(true) fast node usage from the // IAVL store. -func SetIAVLDisableFastNode(disable bool) func(*Service) { - return func(bs *Service) { bs.cms.SetIAVLDisableFastNode(disable) } +func SetIAVLDisableFastNode[ + LoggerT log.AdvancedLogger[LoggerT], +](disable bool) func(*Service[LoggerT]) { + return func(bs *Service[LoggerT]) { bs.cms.SetIAVLDisableFastNode(disable) } } // SetInterBlockCache provides a Service option function that sets the // inter-block cache. -func SetInterBlockCache( - cache storetypes.MultiStorePersistentCache, -) func(*Service) { - return func(s *Service) { s.setInterBlockCache(cache) } +func SetInterBlockCache[ + LoggerT log.AdvancedLogger[LoggerT], +](cache storetypes.MultiStorePersistentCache) func(*Service[LoggerT]) { + return func(s *Service[LoggerT]) { s.setInterBlockCache(cache) } } // SetChainID sets the chain ID in cometbft. -func SetChainID(chainID string) func(*Service) { - return func(s *Service) { s.chainID = chainID } +func SetChainID[ + LoggerT log.AdvancedLogger[LoggerT], +](chainID string) func(*Service[LoggerT]) { + return func(s *Service[LoggerT]) { s.chainID = chainID } } -func (s *Service) SetName(name string) { +func (s *Service[_]) SetName(name string) { s.name = name } // SetVersion sets the application's version string. -func (s *Service) SetVersion(v string) { +func (s *Service[_]) SetVersion(v string) { s.version = v } -func (s *Service) SetAppVersion(ctx context.Context, v uint64) error { +func (s *Service[_]) SetAppVersion(ctx context.Context, v uint64) error { if s.paramStore == nil { return errors. New("param store must be set to set app version") diff --git a/mod/consensus/pkg/cometbft/service/service.go b/mod/consensus/pkg/cometbft/service/service.go index 534c65d0dd..22d649ff51 100644 --- a/mod/consensus/pkg/cometbft/service/service.go +++ b/mod/consensus/pkg/cometbft/service/service.go @@ -25,12 +25,12 @@ import ( "errors" "fmt" - "cosmossdk.io/log" "cosmossdk.io/store" storemetrics "cosmossdk.io/store/metrics" storetypes "cosmossdk.io/store/types" servercmtlog "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/log" "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/params" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/primitives/pkg/common" "github.com/berachain/beacon-kit/mod/primitives/pkg/crypto" "github.com/berachain/beacon-kit/mod/primitives/pkg/transition" @@ -58,11 +58,13 @@ const ( const InitialAppVersion uint64 = 0 -type Service struct { +type Service[ + LoggerT log.AdvancedLogger[LoggerT], +] struct { node *node.Node cmtCfg *cmtcfg.Config // initialized on creation - logger log.Logger + logger LoggerT name string db dbm.DB cms storetypes.CommitMultiStore @@ -80,23 +82,25 @@ type Service struct { chainID string } -func NewService( +func NewService[ + LoggerT log.AdvancedLogger[LoggerT], +]( storeKey *storetypes.KVStoreKey, - logger log.Logger, + logger LoggerT, db dbm.DB, middleware MiddlewareI, loadLatest bool, cmtCfg *cmtcfg.Config, cs common.ChainSpec, - options ...func(*Service), -) *Service { - s := &Service{ - logger: logger.With(log.ModuleKey, "cometbft"), + options ...func(*Service[LoggerT]), +) *Service[LoggerT] { + s := &Service[LoggerT]{ + logger: logger, name: "beacond", db: db, cms: store.NewCommitMultiStore( db, - logger, + servercmtlog.WrapSDKLogger(logger), storemetrics.NewNoOpMetrics(), ), Middleware: middleware, @@ -126,7 +130,7 @@ func NewService( } // TODO: Move nodeKey into being created within the function. -func (s *Service) Start( +func (s *Service[_]) Start( ctx context.Context, ) error { cfg := s.cmtCfg @@ -147,7 +151,7 @@ func (s *Service) Start( GetGenDocProvider(cfg), cmtcfg.DefaultDBProvider, node.DefaultMetricsProvider(cfg.Instrumentation), - servercmtlog.CometLoggerWrapper{Logger: s.logger}, + servercmtlog.WrapCometLogger(s.logger), ) if err != nil { return err @@ -157,7 +161,7 @@ func (s *Service) Start( } // Close is called in start cmd to gracefully cleanup resources. -func (s *Service) Close() error { +func (s *Service[_]) Close() error { var errs []error if s.node != nil && s.node.IsRunning() { @@ -178,17 +182,17 @@ func (s *Service) Close() error { } // Name returns the name of the cometbft. -func (s *Service) Name() string { +func (s *Service[_]) Name() string { return s.name } // CommitMultiStore returns the CommitMultiStore of the cometbft. -func (s *Service) CommitMultiStore() storetypes.CommitMultiStore { +func (s *Service[_]) CommitMultiStore() storetypes.CommitMultiStore { return s.cms } // AppVersion returns the application's protocol version. -func (s *Service) AppVersion(ctx context.Context) (uint64, error) { +func (s *Service[_]) AppVersion(ctx context.Context) (uint64, error) { cp, err := s.paramStore.Get(ctx) if err != nil { return 0, fmt.Errorf("failed to get consensus params: %w", err) @@ -201,14 +205,14 @@ func (s *Service) AppVersion(ctx context.Context) (uint64, error) { // MountStore mounts a store to the provided key in the Service multistore, // using the default DB. -func (s *Service) MountStore( +func (s *Service[_]) MountStore( key storetypes.StoreKey, typ storetypes.StoreType, ) { s.cms.MountStoreWithDB(key, typ, nil) } -func (s *Service) LoadLatestVersion() error { +func (s *Service[_]) LoadLatestVersion() error { if err := s.cms.LoadLatestVersion(); err != nil { return fmt.Errorf("failed to load latest version: %w", err) } @@ -217,7 +221,7 @@ func (s *Service) LoadLatestVersion() error { return s.cms.GetPruning().Validate() } -func (s *Service) LoadVersion(version int64) error { +func (s *Service[_]) LoadVersion(version int64) error { err := s.cms.LoadVersion(version) if err != nil { return fmt.Errorf("failed to load version %d: %w", version, err) @@ -228,30 +232,30 @@ func (s *Service) LoadVersion(version int64) error { } // LastCommitID returns the last CommitID of the multistore. -func (s *Service) LastCommitID() storetypes.CommitID { +func (s *Service[_]) LastCommitID() storetypes.CommitID { return s.cms.LastCommitID() } // LastBlockHeight returns the last committed block height. -func (s *Service) LastBlockHeight() int64 { +func (s *Service[_]) LastBlockHeight() int64 { return s.cms.LastCommitID().Version } -func (s *Service) setMinRetainBlocks(minRetainBlocks uint64) { +func (s *Service[_]) setMinRetainBlocks(minRetainBlocks uint64) { s.minRetainBlocks = minRetainBlocks } -func (s *Service) setInterBlockCache( +func (s *Service[_]) setInterBlockCache( cache storetypes.MultiStorePersistentCache, ) { s.interBlockCache = cache } -func (s *Service) setState(mode execMode) { +func (s *Service[LoggerT]) setState(mode execMode) { ms := s.cms.CacheMultiStore() baseState := &state{ ms: ms, - ctx: sdk.NewContext(ms, false, s.logger), + ctx: sdk.NewContext(ms, false, servercmtlog.WrapSDKLogger(s.logger)), } switch mode { @@ -272,7 +276,7 @@ func (s *Service) setState(mode execMode) { // GetConsensusParams returns the current consensus parameters from the // Service's // ParamStore. If the Service has no ParamStore defined, nil is returned. -func (s *Service) GetConsensusParams( +func (s *Service[_]) GetConsensusParams( ctx context.Context, ) cmtproto.ConsensusParams { //#nosec:G703 // bet. @@ -280,7 +284,7 @@ func (s *Service) GetConsensusParams( return cp } -func (s *Service) validateFinalizeBlockHeight( +func (s *Service[_]) validateFinalizeBlockHeight( req *abci.FinalizeBlockRequest, ) error { if req.Height < 1 { diff --git a/mod/node-core/go.mod b/mod/node-core/go.mod index 5ee5ac7ac9..ae8b007ddb 100644 --- a/mod/node-core/go.mod +++ b/mod/node-core/go.mod @@ -20,7 +20,6 @@ replace ( require ( cosmossdk.io/core v1.0.0 cosmossdk.io/depinject v1.0.0 - cosmossdk.io/log v1.4.1 cosmossdk.io/store/v2 v2.0.0-20240821144902-e88c138760a3 github.com/berachain/beacon-kit/mod/beacon v0.0.0-20240821052951-c15422305b4e github.com/berachain/beacon-kit/mod/cli v0.0.0-20240822173558-4e2a8018ae21 @@ -52,6 +51,7 @@ require ( require ( cosmossdk.io/api v0.7.5 // indirect cosmossdk.io/errors/v2 v2.0.0-20240731132947-df72853b3ca5 // indirect + cosmossdk.io/log v1.4.1 // indirect cosmossdk.io/x/tx v0.13.4-0.20240623110059-dec2d5583e39 // indirect github.com/VictoriaMetrics/fastcache v1.12.2 // indirect github.com/berachain/beacon-kit/mod/chain-spec v0.0.0-20240705193247-d464364483df // indirect diff --git a/mod/node-core/pkg/builder/baseapp_options.go b/mod/node-core/pkg/builder/baseapp_options.go index b878d7da59..c01ac3b40d 100644 --- a/mod/node-core/pkg/builder/baseapp_options.go +++ b/mod/node-core/pkg/builder/baseapp_options.go @@ -30,6 +30,7 @@ import ( server "github.com/berachain/beacon-kit/mod/cli/pkg/commands/server" "github.com/berachain/beacon-kit/mod/config" cometbft "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" + "github.com/berachain/beacon-kit/mod/log" "github.com/cosmos/cosmos-sdk/client/flags" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/spf13/cast" @@ -41,9 +42,11 @@ import ( // DefaultServiceOptions returns the default Service options provided by the // Cosmos SDK. -func DefaultServiceOptions( +func DefaultServiceOptions[ + LoggerT log.AdvancedLogger[LoggerT], +]( appOpts config.AppOptions, -) []func(*cometbft.Service) { +) []func(*cometbft.Service[LoggerT]) { var cache storetypes.MultiStorePersistentCache if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { @@ -79,19 +82,19 @@ func DefaultServiceOptions( } } - return []func(*cometbft.Service){ - cometbft.SetPruning(pruningOpts), - cometbft.SetMinRetainBlocks( + return []func(*cometbft.Service[LoggerT]){ + cometbft.SetPruning[LoggerT](pruningOpts), + cometbft.SetMinRetainBlocks[LoggerT]( cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks)), ), - cometbft.SetInterBlockCache(cache), - cometbft.SetIAVLCacheSize( + cometbft.SetInterBlockCache[LoggerT](cache), + cometbft.SetIAVLCacheSize[LoggerT]( cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize)), ), - cometbft.SetIAVLDisableFastNode( + cometbft.SetIAVLDisableFastNode[LoggerT]( // default to true true, ), - cometbft.SetChainID(chainID), + cometbft.SetChainID[LoggerT](chainID), } } diff --git a/mod/node-core/pkg/builder/builder.go b/mod/node-core/pkg/builder/builder.go index 311d62304d..a867fe9d13 100644 --- a/mod/node-core/pkg/builder/builder.go +++ b/mod/node-core/pkg/builder/builder.go @@ -24,8 +24,8 @@ import ( "io" "cosmossdk.io/depinject" - sdklog "cosmossdk.io/log" servertypes "github.com/berachain/beacon-kit/mod/cli/pkg/commands/server/types" + "github.com/berachain/beacon-kit/mod/config" cometbft "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/node-core/pkg/types" @@ -72,7 +72,7 @@ func New[ // build a new instance of the node. // It is necessary to adhere to the types.AppCreator[T] interface. func (nb *NodeBuilder[NodeT, LoggerT, LoggerConfigT]) Build( - logger sdklog.Logger, + logger LoggerT, db dbm.DB, _ io.Writer, cmtCfg *cmtcfg.Config, @@ -81,10 +81,11 @@ func (nb *NodeBuilder[NodeT, LoggerT, LoggerConfigT]) Build( // variables to hold the components needed to set up BeaconApp var ( apiBackend interface { - AttachQueryBackend(*cometbft.Service) + AttachQueryBackend(*cometbft.Service[LoggerT]) } beaconNode NodeT - cmtService *cometbft.Service + cmtService *cometbft.Service[LoggerT] + config *config.Config ) // build all node components using depinject @@ -95,27 +96,27 @@ func (nb *NodeBuilder[NodeT, LoggerT, LoggerConfigT]) Build( ), depinject.Supply( appOpts, - logger.Impl().(LoggerT), + logger, db, cmtCfg, ), - // TODO: cosmos depinject bad project, fixed with dig. - // depinject.Invoke( - // SetLoggerConfig[LoggerT, LoggerConfigT], - // ), ), - &beaconNode, &apiBackend, + &beaconNode, &cmtService, + &config, ); err != nil { panic(err) } - + if config == nil { + panic("config is nil") + } if apiBackend == nil { panic("node or api backend is nil") } // TODO: so hood + logger.WithConfig(any(config.GetLogger()).(LoggerConfigT)) apiBackend.AttachQueryBackend(cmtService) return beaconNode } diff --git a/mod/node-core/pkg/components/cometbft_service.go b/mod/node-core/pkg/components/cometbft_service.go index fe474d405e..edc91f8a90 100644 --- a/mod/node-core/pkg/components/cometbft_service.go +++ b/mod/node-core/pkg/components/cometbft_service.go @@ -24,8 +24,7 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/berachain/beacon-kit/mod/config" cometbft "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service" - "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/log" - "github.com/berachain/beacon-kit/mod/log/pkg/phuslu" + "github.com/berachain/beacon-kit/mod/log" "github.com/berachain/beacon-kit/mod/node-core/pkg/builder" "github.com/berachain/beacon-kit/mod/primitives/pkg/common" cmtcfg "github.com/cometbft/cometbft/config" @@ -33,23 +32,25 @@ import ( ) // ProvideCometBFTService provides the CometBFT service component. -func ProvideCometBFTService( - logger *phuslu.Logger, +func ProvideCometBFTService[ + LoggerT log.AdvancedLogger[LoggerT], +]( + logger LoggerT, storeKey **storetypes.KVStoreKey, abciMiddleware cometbft.MiddlewareI, db dbm.DB, cmtCfg *cmtcfg.Config, appOpts config.AppOptions, chainSpec common.ChainSpec, -) *cometbft.Service { +) *cometbft.Service[LoggerT] { return cometbft.NewService( *storeKey, - log.WrapSDKLogger(logger), + logger, db, abciMiddleware, true, cmtCfg, chainSpec, - builder.DefaultServiceOptions(appOpts)..., + builder.DefaultServiceOptions[LoggerT](appOpts)..., ) } diff --git a/mod/node-core/pkg/components/node.go b/mod/node-core/pkg/components/node.go index 6ee914bb49..4cb82c8ee1 100644 --- a/mod/node-core/pkg/components/node.go +++ b/mod/node-core/pkg/components/node.go @@ -21,7 +21,6 @@ package components import ( - "github.com/berachain/beacon-kit/mod/consensus/pkg/cometbft/service/log" "github.com/berachain/beacon-kit/mod/log/pkg/phuslu" "github.com/berachain/beacon-kit/mod/node-core/pkg/node" service "github.com/berachain/beacon-kit/mod/node-core/pkg/services/registry" @@ -33,5 +32,5 @@ func ProvideNode( registry *service.Registry, logger *phuslu.Logger, ) types.Node { - return node.New[types.Node](registry, log.WrapSDKLogger(logger)) + return node.New[types.Node](registry, logger) } diff --git a/mod/node-core/pkg/components/service_registry.go b/mod/node-core/pkg/components/service_registry.go index 157f9fc35d..db930d4193 100644 --- a/mod/node-core/pkg/components/service_registry.go +++ b/mod/node-core/pkg/components/service_registry.go @@ -64,7 +64,7 @@ type ServiceRegistryInput[ ExecutionPayloadHeaderT ExecutionPayloadHeader[ExecutionPayloadHeaderT], GenesisT Genesis[DepositT, ExecutionPayloadHeaderT], KVStoreT any, - LoggerT any, + LoggerT log.AdvancedLogger[LoggerT], NodeAPIContextT NodeAPIContext, WithdrawalT Withdrawal[WithdrawalT], WithdrawalsT Withdrawals[WithdrawalT], @@ -104,7 +104,7 @@ type ServiceRegistryInput[ *Eth1Data, ExecutionPayloadT, ExecutionPayloadHeaderT, *ForkData, *SlashingInfo, *SlotData, ] - CometBFTService *cometbft.Service + CometBFTService *cometbft.Service[LoggerT] } // ProvideServiceRegistry is the depinject provider for the service registry. diff --git a/mod/node-core/pkg/node/node.go b/mod/node-core/pkg/node/node.go index 2ae51cf1cc..7cbe7ead07 100644 --- a/mod/node-core/pkg/node/node.go +++ b/mod/node-core/pkg/node/node.go @@ -26,7 +26,7 @@ import ( "os/signal" "syscall" - "cosmossdk.io/log" + "github.com/berachain/beacon-kit/mod/log" service "github.com/berachain/beacon-kit/mod/node-core/pkg/services/registry" "github.com/berachain/beacon-kit/mod/node-core/pkg/types" "golang.org/x/sync/errgroup"