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

Commit

Permalink
init: add random chain-id generator (#797)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
3 people authored Feb 26, 2021
1 parent a82a2ce commit 99112e1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
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())
}
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))
}

0 comments on commit 99112e1

Please sign in to comment.