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 <alessio@tendermint.com>
This commit is contained in:
Helder Moreira 2021-02-26 15:50:22 +00:00 committed by GitHub
parent a82a2cebaf
commit 99112e1cbd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 2 deletions

View File

@ -61,3 +61,23 @@ func ValidateChainID(baseCmd *cobra.Command) *cobra.Command {
baseCmd.RunE = validateFn baseCmd.RunE = validateFn
return baseCmd 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
}

View File

@ -65,9 +65,11 @@ func main() {
} }
// CLI commands to initialize the chain // CLI commands to initialize the chain
rootCmd.AddCommand( rootCmd.AddCommand(
client.GenerateChainID(
client.ValidateChainID( client.ValidateChainID(
genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome), genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome),
), ),
),
genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome), genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(ctx, cdc), genutilcli.MigrateGenesisCmd(ctx, cdc),
genutilcli.GenTxCmd( genutilcli.GenTxCmd(

View File

@ -7,6 +7,7 @@ import (
"strings" "strings"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
tmrand "github.com/tendermint/tendermint/libs/rand"
) )
var ( var (
@ -46,3 +47,8 @@ func ParseChainID(chainID string) (*big.Int, error) {
return chainIDInt, nil 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))
}