Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(init-cli): Refactor the Init CLI command to be callable from runtime #2468

Closed
wants to merge 5 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 79 additions & 63 deletions cli/commands/initialize/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"github.com/berachain/beacon-kit/errors"
"github.com/berachain/beacon-kit/primitives/crypto"
"github.com/berachain/beacon-kit/primitives/encoding/json"
cfg "github.com/cometbft/cometbft/config"
cmtconfig "github.com/cometbft/cometbft/config"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
Expand Down Expand Up @@ -92,7 +92,7 @@
return err
}

//nolint:funlen,gocognit,mnd // based on cosmossdk implementation

Check failure on line 95 in cli/commands/initialize/initialize.go

View workflow job for this annotation

GitHub Actions / lint

directive `//nolint:funlen,gocognit,mnd // based on cosmossdk implementation` is unused for linter "funlen" (nolintlint)
func InitCmd(mm interface {
DefaultGenesis() map[string]json.RawMessage
ValidateGenesis(genesisData map[string]json.RawMessage) error
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We run ValidateGenesis in initChain and hence we don't use it here (i.e. this was unused)

Expand All @@ -114,7 +114,6 @@
if err != nil {
return errors.New("failed to parse FlagChainID")
}

switch {
case chainID != "":
case clientCtx.ChainID != "":
Expand All @@ -125,7 +124,7 @@
if config.RootDir == "" {
config.RootDir = clientCtx.HomeDir
}

config.Moniker = args[0]
Copy link
Contributor Author

@rezbera rezbera Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reordered setting the moniker so its closer to where other config updates are done

// Get bip39 mnemonic
var mnemonic string
shouldRecover, err := cmd.Flags().GetBool(FlagRecover)
Expand All @@ -145,7 +144,6 @@
return errors.New("invalid mnemonic")
}
}

// Get initial height
initHeight, err := cmd.Flags().GetInt64(flags.FlagInitHeight)
if err != nil {
Expand All @@ -155,14 +153,6 @@
initHeight = 1
}

nodeID, _, err := genutil.InitializeNodeValidatorFilesFromMnemonic(config, mnemonic, consensusKeyAlgo)
if err != nil {
return err
}
Comment on lines -158 to -161
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved this core logic to Init


config.Moniker = args[0]

genFile := config.GenesisFile()
overwrite, err := cmd.Flags().GetBool(FlagOverwrite)
if err != nil {
return errors.New("failed to parse FlagOverwrite")
Expand All @@ -171,65 +161,91 @@
if err != nil {
return errors.New("failed to parse FlagDefaultBondDenom")
}
return Init(
chainID,
config,
mnemonic,
initHeight,
overwrite,
defaultDenom,
mm.DefaultGenesis(),
cmd.ErrOrStderr(),
)
},
}

// use os.Stat to check if the file exists
_, err = os.Stat(genFile)
if !overwrite && !os.IsNotExist(err) {
return fmt.Errorf("genesis.json file already exists: %v", genFile)
}
cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file")
cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating")
cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created")
cmd.Flags().String(FlagDefaultBondDenom, "", "genesis file default denomination, if left blank default value is 'stake'")
cmd.Flags().Int64(flags.FlagInitHeight, 1, "specify the initial block height at genesis")
return cmd
}

// Overwrites the SDK default denom for side-effects
if defaultDenom != "" {
sdk.DefaultBondDenom = defaultDenom
}
appGenState := mm.DefaultGenesis()
func Init(
chainID string,
config *cmtconfig.Config,
mnemonic string,
initHeight int64,
overwrite bool,
defaultDenom string,
appGenesisState map[string]json.RawMessage,
printDestination io.Writer,
) error {
nodeID, _, err := genutil.InitializeNodeValidatorFilesFromMnemonic(config, mnemonic, consensusKeyAlgo)
if err != nil {
return err
}

appState, err := json.MarshalIndent(appGenState, "", " ")
if err != nil {
return errorsmod.Wrap(err, "Failed to marshal default genesis state")
}
genFile := config.GenesisFile()
// use os.Stat to check if the file exists
_, err = os.Stat(genFile)
if !overwrite && !os.IsNotExist(err) {
return fmt.Errorf("genesis.json file already exists: %v", genFile)
}

appGenesis := &types.AppGenesis{}
if _, err = os.Stat(genFile); err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
appGenesis, err = types.AppGenesisFromFile(genFile)
if err != nil {
return errorsmod.Wrap(err, "Failed to read genesis doc from file")
}
}
// Overwrites the SDK default denom for side-effects
if defaultDenom != "" {
sdk.DefaultBondDenom = defaultDenom
}

appGenesis.AppName = version.AppName
appGenesis.AppVersion = version.Version
appGenesis.ChainID = chainID
appGenesis.AppState = appState
appGenesis.InitialHeight = initHeight
appGenesis.Consensus = &types.ConsensusGenesis{
Validators: nil,
Params: cometbft.DefaultConsensusParams(consensusKeyAlgo),
}
appState, err := json.MarshalIndent(appGenesisState, "", " ")
if err != nil {
return errorsmod.Wrap(err, "Failed to marshal default genesis state")
}

if err = genutil.ExportGenesisFile(appGenesis, genFile); err != nil {
return errorsmod.Wrap(err, "Failed to export genesis file")
}
appGenesis := &types.AppGenesis{}
if _, err = os.Stat(genFile); err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
appGenesis, err = types.AppGenesisFromFile(genFile)
if err != nil {
return errorsmod.Wrap(err, "Failed to read genesis doc from file")
}
}

toPrint := newPrintInfo(config.Moniker, chainID, nodeID, "", appState)
appGenesis.AppName = version.AppName
appGenesis.AppVersion = version.Version
appGenesis.ChainID = chainID
appGenesis.AppState = appState
appGenesis.InitialHeight = initHeight
appGenesis.Consensus = &types.ConsensusGenesis{
Validators: nil,
Params: cometbft.DefaultConsensusParams(consensusKeyAlgo),
}

// Note: the config file was already creating before execution this command
// by [SetupCommand], and it is being overwritten here. The only difference,
// post default values cleanups, should be in the moniker, which is only setup
// correctly here
cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config)
return displayInfo(cmd.ErrOrStderr(), toPrint)
},
if err = genutil.ExportGenesisFile(appGenesis, genFile); err != nil {
return errorsmod.Wrap(err, "Failed to export genesis file")
}

cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file")
cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating")
cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created")
cmd.Flags().String(FlagDefaultBondDenom, "", "genesis file default denomination, if left blank default value is 'stake'")
cmd.Flags().Int64(flags.FlagInitHeight, 1, "specify the initial block height at genesis")
return cmd
toPrint := newPrintInfo(config.Moniker, chainID, nodeID, "", appState)

// Note: the config file was already creating before execution this command
// by [SetupCommand], and it is being overwritten here. The only difference,
// post default values cleanups, should be in the moniker, which is only setup
// correctly here
cmtconfig.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config)
return displayInfo(printDestination, toPrint)
}
Loading