Skip to content
This repository has been archived by the owner on Nov 30, 2021. It is now read-only.

init: add random chain-id generator #797

Merged
merged 3 commits into from
Feb 26, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions client/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Comment on lines +75 to +77
Copy link
Contributor

Choose a reason for hiding this comment

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

I'd prefer to add this logic to the ValidateChainID function

Copy link
Contributor

Choose a reason for hiding this comment

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

But then ValidateChainID would not just validate

return baseRunE(cmd, args)
}

baseCmd.RunE = generateFn
return baseCmd
}
6 changes: 4 additions & 2 deletions cmd/ethermintd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
6 changes: 6 additions & 0 deletions types/chain_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"

sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
tmrand "github.com/tendermint/tendermint/libs/rand"
)

var (
Expand Down Expand Up @@ -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))
}