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

Commit 99112e1

Browse files
helder-moreirafedekunzeAlessio Treglia
authored
init: add random chain-id generator (#797)
* init: add random chain-id generator * Update types/chain_id.go Co-authored-by: Federico Kunze <[email protected]> Co-authored-by: Alessio Treglia <[email protected]>
1 parent a82a2ce commit 99112e1

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

client/config.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,23 @@ func ValidateChainID(baseCmd *cobra.Command) *cobra.Command {
6161
baseCmd.RunE = validateFn
6262
return baseCmd
6363
}
64+
65+
// GenerateChainID wraps a cobra command with a RunE function with base 10 integer chain-id random generation
66+
// when a chain-id is not provided.
67+
func GenerateChainID(baseCmd *cobra.Command) *cobra.Command {
68+
// Copy base run command to be used after chain verification
69+
baseRunE := baseCmd.RunE
70+
71+
// Function to replace command's RunE function
72+
generateFn := func(cmd *cobra.Command, args []string) error {
73+
chainID := viper.GetString(flags.FlagChainID)
74+
75+
if chainID == "" {
76+
viper.Set(flags.FlagChainID, ethermint.GenerateRandomChainID())
77+
}
78+
return baseRunE(cmd, args)
79+
}
80+
81+
baseCmd.RunE = generateFn
82+
return baseCmd
83+
}

cmd/ethermintd/main.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,10 @@ func main() {
6565
}
6666
// CLI commands to initialize the chain
6767
rootCmd.AddCommand(
68-
client.ValidateChainID(
69-
genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome),
68+
client.GenerateChainID(
69+
client.ValidateChainID(
70+
genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome),
71+
),
7072
),
7173
genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome),
7274
genutilcli.MigrateGenesisCmd(ctx, cdc),

types/chain_id.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"strings"
88

99
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
10+
tmrand "github.com/tendermint/tendermint/libs/rand"
1011
)
1112

1213
var (
@@ -46,3 +47,8 @@ func ParseChainID(chainID string) (*big.Int, error) {
4647

4748
return chainIDInt, nil
4849
}
50+
51+
// GenerateRandomChainID returns a random chain-id in the valid format.
52+
func GenerateRandomChainID() string {
53+
return fmt.Sprintf("ethermint-%d", 10+tmrand.Intn(10000))
54+
}

0 commit comments

Comments
 (0)