Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
rezbera committed Feb 3, 2025
1 parent 5fa2aa0 commit 94b8173
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 107 deletions.
10 changes: 10 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ func (c Config) GetEngine() *engineclient.Config {
return &c.Engine
}

// GetPayloadBuilder returns the block store configuration.
func (c Config) GetPayloadBuilder() *builder.Config {
return &c.PayloadBuilder
}

// GetBlockStoreService returns the block store configuration.
func (c Config) GetBlockStoreService() *blockstore.Config {
return &c.BlockStoreService
}

// GetLogger returns the logger configuration.
func (c Config) GetLogger() *log.Config {
return &c.Logger
Expand Down
176 changes: 69 additions & 107 deletions testing/injected-consensus/injected-consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,29 @@ package injectedconsensus

import (
"context"
"fmt"
"os"
"os/exec"
"testing"

"github.com/berachain/beacon-kit/beacon/blockchain"
"github.com/berachain/beacon-kit/cli/commands/genesis"
servertypes "github.com/berachain/beacon-kit/cli/commands/server/types"
"github.com/berachain/beacon-kit/cli/flags"
"github.com/berachain/beacon-kit/config"
beaconkitconfig "github.com/berachain/beacon-kit/config"
"github.com/berachain/beacon-kit/config/spec"
cometbft "github.com/berachain/beacon-kit/consensus/cometbft/service"
"github.com/berachain/beacon-kit/da/kzg"
executionconfig "github.com/berachain/beacon-kit/execution/client"
"github.com/berachain/beacon-kit/log/phuslu"
nodebuilder "github.com/berachain/beacon-kit/node-core/builder"
"github.com/berachain/beacon-kit/node-core/components"
"github.com/berachain/beacon-kit/node-core/components/signer"
nodetypes "github.com/berachain/beacon-kit/node-core/types"
payloadbuilder "github.com/berachain/beacon-kit/payload/builder"
"github.com/berachain/beacon-kit/primitives/common"
"github.com/berachain/beacon-kit/primitives/math"
"github.com/berachain/beacon-kit/storage/db"
cmtcfg "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/crypto/bls12381"
"github.com/cometbft/cometbft/types"
dbm "github.com/cosmos/cosmos-db"
cosmosutil "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/ethereum/go-ethereum/params"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -116,127 +111,93 @@ type TestNode struct {
CancelFunc context.CancelFunc
}

// func copyFile(t *testing.T, src, dst string) error {
// t.Helper()
// // Open the source file
// srcFile, err := os.Open(src)
// if err != nil {
// return fmt.Errorf("failed to open source file %s: %w", src, err)
// }
// defer srcFile.Close()
//
// // Create the destination file
// dstFile, err := os.Create(dst)
// if err != nil {
// return fmt.Errorf("failed to create destination file %s: %w", dst, err)
// }
// defer dstFile.Close()
//
// // Copy the file contents
// _, err = io.Copy(dstFile, srcFile)
// if err != nil {
// return fmt.Errorf("failed to copy from %s to %s: %w", src, dst, err)
// }
//
// return nil
//}

func runCommand(command string, args ...string) error {
cmd := exec.Command(command, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

err := cmd.Run()
if err != nil {
return fmt.Errorf("failed to run command %s %v: %w", command, args, err)
}
return nil
}

func initializeBeaconState(t *testing.T, homedir string) {
ethGenesis := "./eth-genesis.json"

commands := [][]string{
{"./build/bin/beacond", "genesis", "add-premined-deposit", "--home", homedir, "32000000000", "0x20f33ce90a13a4b5e7697e3544c3083b8f8a51d4"},
{"./build/bin/beacond", "genesis", "collect-premined-deposits", "--home", homedir},
{"./build/bin/beacond", "genesis", "set-deposit-storage", ethGenesis, "--home", homedir},
{"./build/bin/beacond", "genesis", "execution-payload", ethGenesis, "--home", homedir},
}

for _, cmdArgs := range commands {
err := runCommand(cmdArgs[0], cmdArgs[1:]...)
require.NoError(t, err)
}
}

// Uses the mainnet chainspec.
func NewTestNode(t *testing.T) *TestNode {
// createConfiguration creates the BeaconKit configuration and the CometBFT configuration.
func createConfiguration(t *testing.T, tempHomeDir string) (
*beaconkitconfig.Config,
*cmtcfg.Config,
) {
t.Helper()

// Create a test node that
ctx, cancelFunc := context.WithCancel(context.Background())
// 1. Build a node builder with your default or custom test components.
nb := nodebuilder.New(
nodebuilder.WithComponents[nodetypes.Node](DefaultComponents(t)),
)

tempHomeDir := t.TempDir()

// initializeBeaconState(t, tempHomeDir)

logger := phuslu.NewLogger(os.Stdout, nil)

cmtCfg := cometbft.DefaultConfig()
cmtCfg.RootDir = tempHomeDir
// Forces Comet to Create it
cmtCfg.NodeKey = "node_key.json"
beaconCfg := beaconkitconfig.DefaultConfig()
return beaconCfg, cmtCfg
}

beaconCfg := config.DefaultConfig()
executionClientConfig := executionconfig.DefaultConfig()
payloadBuilderCfg := payloadbuilder.DefaultConfig()

chainSpec, err := spec.MainnetChainSpec()
require.NoError(t, err)

// Ideally we can avoid having to set the flags like this and just directly modify a config type
// getAppOptions returns the Application Options we need to set for the Node Builder.
// Ideally we can avoid having to set the flags like this and just directly modify a config type.
func getAppOptions(t *testing.T, beaconKitConfig *beaconkitconfig.Config, tempHomeDir string) servertypes.AppOptions {
t.Helper()
appOpts := viper.New()
// Execution Client Config
appOpts.Set(flags.JWTSecretPath, "../files/jwt.hex")
appOpts.Set(flags.RPCJWTRefreshInterval, executionClientConfig.RPCJWTRefreshInterval)
appOpts.Set(flags.RPCStartupCheckInterval, executionClientConfig.RPCStartupCheckInterval)
appOpts.Set(flags.RPCDialURL, executionClientConfig.RPCDialURL)
appOpts.Set(flags.RPCTimeout, executionClientConfig.RPCTimeout)
appOpts.Set(flags.RPCJWTRefreshInterval, beaconKitConfig.GetEngine().RPCJWTRefreshInterval)
appOpts.Set(flags.RPCStartupCheckInterval, beaconKitConfig.GetEngine().RPCStartupCheckInterval)
appOpts.Set(flags.RPCDialURL, beaconKitConfig.GetEngine().RPCDialURL)
appOpts.Set(flags.RPCTimeout, beaconKitConfig.GetEngine().RPCTimeout)

// BLS Config
appOpts.Set(flags.PrivValidatorKeyFile, "./config/priv_validator_key.json")
appOpts.Set(flags.PrivValidatorStateFile, "./data/priv_validator_state.json")

// Beacon Config
appOpts.Set(flags.BlockStoreServiceAvailabilityWindow, beaconCfg.BlockStoreService.AvailabilityWindow)
appOpts.Set(flags.BlockStoreServiceEnabled, beaconCfg.BlockStoreService.Enabled)
appOpts.Set(flags.BlockStoreServiceAvailabilityWindow, beaconKitConfig.GetBlockStoreService().AvailabilityWindow)
appOpts.Set(flags.BlockStoreServiceEnabled, beaconKitConfig.GetBlockStoreService().Enabled)
appOpts.Set(flags.KZGTrustedSetupPath, "../files/kzg-trusted-setup.json")
appOpts.Set(flags.KZGImplementation, kzg.DefaultConfig().Implementation)

// Payload Builder Config
payloadBuilderCfg.SuggestedFeeRecipient = common.NewExecutionAddressFromHex("0x981114102592310C347E61368342DDA67017bf84")
appOpts.Set(flags.BuilderEnabled, payloadBuilderCfg.Enabled)
appOpts.Set(flags.BuildPayloadTimeout, payloadBuilderCfg.PayloadTimeout)
appOpts.Set(flags.SuggestedFeeRecipient, payloadBuilderCfg.SuggestedFeeRecipient)
beaconKitConfig.GetPayloadBuilder().SuggestedFeeRecipient = common.NewExecutionAddressFromHex("0x981114102592310C347E61368342DDA67017bf84")
appOpts.Set(flags.BuilderEnabled, beaconKitConfig.GetPayloadBuilder().Enabled)
appOpts.Set(flags.BuildPayloadTimeout, beaconKitConfig.GetPayloadBuilder().PayloadTimeout)
appOpts.Set(flags.SuggestedFeeRecipient, beaconKitConfig.GetPayloadBuilder().SuggestedFeeRecipient)

// TODO: Cleanup this Set
appOpts.Set("pruning", "default")
appOpts.Set("home", tempHomeDir)
return appOpts
}

// NewTestNode Uses the mainnet chainspec.
func NewTestNode(t *testing.T) *TestNode {
t.Helper()

ctx, cancelFunc := context.WithCancel(context.Background())
logger := phuslu.NewLogger(os.Stdout, nil)

tempHomeDir := t.TempDir()
beaconKitConfig, cometConfig := createConfiguration(t, tempHomeDir)

chainSpec, err := spec.MainnetChainSpec()
require.NoError(t, err)

appOpts := getAppOptions(t, beaconKitConfig, tempHomeDir)

// Chain Spec
t.Setenv(components.ChainSpecTypeEnvVar, components.MainnetChainSpecType)

// Create the genesis deposit
blsSigner := signer.BLSSigner{PrivValidator: types.NewMockPVWithKeyType(bls12381.KeyType)}
depositAmount := math.Gwei(250_000 * params.GWei)

// Make the deposit amount the Max effective balance - set arbitrarily higher than 250K BERA required for mainnet
depositAmount := math.Gwei(chainSpec.MaxEffectiveBalance())
withdrawalAddress := common.NewExecutionAddressFromHex("0x6Eb9C23e4c187452504Ef8c5fD8fA1a4b15BE162")
err = genesis.AddGenesisDeposit(chainSpec, cometConfig, blsSigner, depositAmount, withdrawalAddress, "")
require.NoError(t, err)

err = genesis.AddGenesisDeposit(chainSpec, cmtCfg, blsSigner, depositAmount, withdrawalAddress, "")
// Collect the genesis deposit
err = genesis.CollectGenesisValidators(cometConfig)
require.NoError(t, err)

// TODO: Cleanup this Set
appOpts.Set("pruning", "default")
appOpts.Set("home", tempHomeDir)
// Update the EL Deposit Storage
err = genesis.SetDepositStorage(chainSpec, cometConfig, "TBD", false)
require.NoError(t, err)

// 1. Build a node builder with your default or custom test components.
nb := nodebuilder.New(
nodebuilder.WithComponents[nodetypes.Node](DefaultComponents(t)),
)

database, err := db.OpenDB(tempHomeDir, dbm.PebbleDBBackend)
require.NoError(t, err)
Expand All @@ -245,10 +206,11 @@ func NewTestNode(t *testing.T) *TestNode {
logger,
database,
os.Stdout, // or some other writer
cmtCfg,
cometConfig,
appOpts,
)

// Fetch services we will want to query and interact with so they are easily accessible in testing
var cometService *cometbft.Service
err = node.FetchService(&cometService)
require.NoError(t, err)
Expand All @@ -263,16 +225,16 @@ func NewTestNode(t *testing.T) *TestNode {
Node: node,
CometService: cometService,
BlockchainService: blockchainService,
CometConfig: cmtCfg,
CometConfig: cometConfig,
Homedir: tempHomeDir,
Context: ctx,
CancelFunc: cancelFunc,
}
}

func genesisFromFile(t *testing.T, file string) *cosmosutil.AppGenesis {
t.Helper()
appGenesis, err := cosmosutil.AppGenesisFromFile(file)
require.NoError(t, err)
return appGenesis
}
// func genesisFromFile(t *testing.T, file string) *cosmosutil.AppGenesis {
// t.Helper()
// appGenesis, err := cosmosutil.AppGenesisFromFile(file)
// require.NoError(t, err)
// return appGenesis
//}
1 change: 1 addition & 0 deletions testing/injected-consensus/invalid_block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,6 @@ func (s *InjectedConsensus) TestProcessProposalRequestInvalidBlock() {
}

func TestInjectedConsensus(t *testing.T) {
t.Parallel()
suite.Run(t, new(InjectedConsensus))
}

0 comments on commit 94b8173

Please sign in to comment.