From 99112e1cbd817dd7f7c5066e023129e521fd2a8b Mon Sep 17 00:00:00 2001 From: Helder Moreira Date: Fri, 26 Feb 2021 15:50:22 +0000 Subject: [PATCH] init: add random chain-id generator (#797) * init: add random chain-id generator * Update types/chain_id.go Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Co-authored-by: Alessio Treglia --- client/config.go | 20 ++++++++++++++++++++ cmd/ethermintd/main.go | 6 ++++-- types/chain_id.go | 6 ++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/client/config.go b/client/config.go index 1069e5c0..b374b0a0 100644 --- a/client/config.go +++ b/client/config.go @@ -61,3 +61,23 @@ func ValidateChainID(baseCmd *cobra.Command) *cobra.Command { baseCmd.RunE = validateFn return baseCmd } + +// GenerateChainID wraps a cobra command with a RunE function with base 10 integer chain-id random generation +// when a chain-id is not provided. +func GenerateChainID(baseCmd *cobra.Command) *cobra.Command { + // Copy base run command to be used after chain verification + baseRunE := baseCmd.RunE + + // Function to replace command's RunE function + generateFn := func(cmd *cobra.Command, args []string) error { + chainID := viper.GetString(flags.FlagChainID) + + if chainID == "" { + viper.Set(flags.FlagChainID, ethermint.GenerateRandomChainID()) + } + return baseRunE(cmd, args) + } + + baseCmd.RunE = generateFn + return baseCmd +} diff --git a/cmd/ethermintd/main.go b/cmd/ethermintd/main.go index 506c22f8..e6715122 100644 --- a/cmd/ethermintd/main.go +++ b/cmd/ethermintd/main.go @@ -65,8 +65,10 @@ func main() { } // CLI commands to initialize the chain rootCmd.AddCommand( - client.ValidateChainID( - genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome), + client.GenerateChainID( + client.ValidateChainID( + genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome), + ), ), genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome), genutilcli.MigrateGenesisCmd(ctx, cdc), diff --git a/types/chain_id.go b/types/chain_id.go index 7bc316b1..1c54fbe2 100644 --- a/types/chain_id.go +++ b/types/chain_id.go @@ -7,6 +7,7 @@ import ( "strings" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + tmrand "github.com/tendermint/tendermint/libs/rand" ) var ( @@ -46,3 +47,8 @@ func ParseChainID(chainID string) (*big.Int, error) { return chainIDInt, nil } + +// GenerateRandomChainID returns a random chain-id in the valid format. +func GenerateRandomChainID() string { + return fmt.Sprintf("ethermint-%d", 10+tmrand.Intn(10000)) +}