-
Notifications
You must be signed in to change notification settings - Fork 170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add validate-genesis cmd #187
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
package cmd | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
|
||
"github.com/spf13/cobra" | ||
|
||
"github.com/cosmos/cosmos-sdk/client" | ||
"github.com/cosmos/cosmos-sdk/server" | ||
"github.com/cosmos/cosmos-sdk/types/module" | ||
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" | ||
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" | ||
tmtypes "github.com/tendermint/tendermint/types" | ||
|
||
"github.com/babylonchain/babylon/x/checkpointing/types" | ||
) | ||
|
||
const chainUpgradeGuide = "https://github.com/cosmos/cosmos-sdk/blob/a51aa517c46c70df04a06f586c67fb765e45322a/UPGRADING.md" | ||
|
||
// ValidateGenesisCmd takes a genesis file, and makes sure that it is valid. | ||
// 1. genesis state of each module should be valid according to each module's | ||
// validation rule | ||
// 2. each genesis BLS key or gentx should have a corresponding gentx or genesis | ||
// BLS key | ||
// modified based on "https://github.com/cosmos/cosmos-sdk/blob/6d32debf1aca4b7f1ed1429d87be1d02c315f02d/x/genutil/client/cli/validate_genesis.go" | ||
func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { | ||
return &cobra.Command{ | ||
Use: "validate-genesis [file]", | ||
Args: cobra.RangeArgs(0, 1), | ||
Short: "validates the genesis file at the default location or at the location passed as an arg", | ||
RunE: func(cmd *cobra.Command, args []string) (err error) { | ||
serverCtx := server.GetServerContextFromCmd(cmd) | ||
clientCtx := client.GetClientContextFromCmd(cmd) | ||
|
||
cdc := clientCtx.Codec | ||
|
||
// Load default if passed no args, otherwise load passed file | ||
var genesis string | ||
if len(args) == 0 { | ||
genesis = serverCtx.Config.GenesisFile() | ||
} else { | ||
genesis = args[0] | ||
} | ||
|
||
genDoc, err := validateGenDoc(genesis) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
var genState map[string]json.RawMessage | ||
if err = json.Unmarshal(genDoc.AppState, &genState); err != nil { | ||
return fmt.Errorf("error unmarshalling genesis doc %s: %s", genesis, err.Error()) | ||
} | ||
|
||
if err = mbm.ValidateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { | ||
return fmt.Errorf("error validating genesis file %s: %s", genesis, err.Error()) | ||
} | ||
|
||
if err = CheckCorrespondence(clientCtx, genState); err != nil { | ||
return fmt.Errorf("error validating genesis file correspondence %s: %s", genesis, err.Error()) | ||
} | ||
|
||
fmt.Printf("File at %s is a valid genesis file\n", genesis) | ||
return nil | ||
}, | ||
} | ||
} | ||
|
||
// validateGenDoc reads a genesis file and validates that it is a correct | ||
// Tendermint GenesisDoc. This function does not do any cosmos-related | ||
// validation. | ||
func validateGenDoc(importGenesisFile string) (*tmtypes.GenesisDoc, error) { | ||
genDoc, err := tmtypes.GenesisDocFromFile(importGenesisFile) | ||
if err != nil { | ||
return nil, fmt.Errorf("%s. Make sure that"+ | ||
" you have correctly migrated all Tendermint consensus params, please see the"+ | ||
" chain migration guide at %s for more info", | ||
err.Error(), chainUpgradeGuide, | ||
) | ||
} | ||
|
||
return genDoc, nil | ||
} | ||
|
||
// CheckCorrespondence checks that each genesis tx/BLS key should have one | ||
// corresponding BLS key/genesis tx | ||
func CheckCorrespondence(ctx client.Context, genesis map[string]json.RawMessage) error { | ||
checkpointingGenState := types.GetGenesisStateFromAppState(ctx.Codec, genesis) | ||
gks := checkpointingGenState.GetGenesisKeys() | ||
genTxState := genutiltypes.GetGenesisStateFromAppState(ctx.Codec, genesis) | ||
addresses := make(map[string]struct{}, 0) | ||
// ensure no duplicate BLS keys | ||
for _, gk := range gks { | ||
addresses[gk.ValidatorAddress] = struct{}{} | ||
} | ||
if len(addresses) != len(gks) { | ||
return errors.New("duplicate genesis BLS keys") | ||
} | ||
// ensure the number of BLS keys and gentxs are the same so that we | ||
// don't need to do reverse checking | ||
if len(addresses) != len(genTxState.GenTxs) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This check means that you don't have to do a reverse loop later to check whether all BLS sigs have a matching gentx, right? Maybe worth adding a comment about your checking algorithm. |
||
return errors.New("genesis txs and genesis BLS keys do not match") | ||
} | ||
// ensure every gentx has a match with BLS key by address | ||
for _, genTx := range genTxState.GenTxs { | ||
tx, err := genutiltypes.ValidateAndGetGenTx(genTx, ctx.TxConfig.TxJSONDecoder()) | ||
if err != nil { | ||
return err | ||
} | ||
msgs := tx.GetMsgs() | ||
if len(msgs) == 0 { | ||
return errors.New("invalid genesis transaction") | ||
} | ||
msgCreateValidator := msgs[0].(*stakingtypes.MsgCreateValidator) | ||
if _, exists := addresses[msgCreateValidator.ValidatorAddress]; !exists { | ||
return errors.New("cannot find a corresponding BLS key for a genesis tx") | ||
} | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
package cmd_test | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/spf13/viper" | ||
"github.com/stretchr/testify/require" | ||
|
||
"github.com/babylonchain/babylon/app" | ||
"github.com/babylonchain/babylon/cmd/babylond/cmd" | ||
"github.com/babylonchain/babylon/x/checkpointing/types" | ||
|
||
"github.com/cosmos/cosmos-sdk/client" | ||
"github.com/cosmos/cosmos-sdk/client/flags" | ||
"github.com/cosmos/cosmos-sdk/server" | ||
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" | ||
genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil" | ||
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" | ||
tmjson "github.com/tendermint/tendermint/libs/json" | ||
"github.com/tendermint/tendermint/libs/log" | ||
tmtypes "github.com/tendermint/tendermint/types" | ||
) | ||
|
||
func TestCheckCorrespondence(t *testing.T) { | ||
homePath := t.TempDir() | ||
encodingCft := app.MakeTestEncodingConfig() | ||
clientCtx := client.Context{}.WithCodec(encodingCft.Marshaler).WithTxConfig(encodingCft.TxConfig) | ||
|
||
// generate valid genesis doc | ||
validGenState, genDoc := generateTestGenesisState(homePath, 2) | ||
validGenDocJSON, err := tmjson.MarshalIndent(genDoc, "", " ") | ||
require.NoError(t, err) | ||
|
||
// generate mismatched genesis doc by deleting one item from gentx and genKeys in different positions | ||
gentxs := genutiltypes.GetGenesisStateFromAppState(clientCtx.Codec, validGenState) | ||
genKeys := types.GetGenesisStateFromAppState(clientCtx.Codec, validGenState) | ||
gentxs.GenTxs = gentxs.GenTxs[:1] | ||
genKeys.GenesisKeys = genKeys.GenesisKeys[1:] | ||
genTxsBz, err := clientCtx.Codec.MarshalJSON(gentxs) | ||
require.NoError(t, err) | ||
genKeysBz, err := clientCtx.Codec.MarshalJSON(&genKeys) | ||
require.NoError(t, err) | ||
validGenState[genutiltypes.ModuleName] = genTxsBz | ||
validGenState[types.ModuleName] = genKeysBz | ||
misMatchedGenStateBz, err := json.Marshal(validGenState) | ||
require.NoError(t, err) | ||
genDoc.AppState = misMatchedGenStateBz | ||
misMatchedGenDocJSON, err := tmjson.MarshalIndent(genDoc, "", " ") | ||
require.NoError(t, err) | ||
|
||
testCases := []struct { | ||
name string | ||
genesis []byte | ||
expErr bool | ||
}{ | ||
{ | ||
"valid genesis gentx and BLS key pair", | ||
validGenDocJSON, | ||
false, | ||
}, | ||
{ | ||
"mismatched genesis state", | ||
misMatchedGenDocJSON, | ||
true, | ||
}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
genDoc, err := tmtypes.GenesisDocFromJSON(tc.genesis) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, genDoc) | ||
genesisState, err := genutiltypes.GenesisStateFromGenDoc(*genDoc) | ||
require.NoError(t, err) | ||
require.NotEmpty(t, genesisState) | ||
err = cmd.CheckCorrespondence(clientCtx, genesisState) | ||
if tc.expErr { | ||
require.Error(t, err) | ||
} else { | ||
require.NoError(t, err) | ||
} | ||
} | ||
} | ||
|
||
func generateTestGenesisState(home string, n int) (map[string]json.RawMessage, *tmtypes.GenesisDoc) { | ||
encodingConfig := app.MakeTestEncodingConfig() | ||
logger := log.NewNopLogger() | ||
cfg, _ := genutiltest.CreateDefaultTendermintConfig(home) | ||
|
||
_ = genutiltest.ExecInitCmd(app.ModuleBasics, home, encodingConfig.Marshaler) | ||
|
||
serverCtx := server.NewContext(viper.New(), cfg, logger) | ||
clientCtx := client.Context{}. | ||
WithCodec(encodingConfig.Marshaler). | ||
WithHomeDir(home). | ||
WithTxConfig(encodingConfig.TxConfig) | ||
|
||
ctx := context.Background() | ||
ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) | ||
ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) | ||
testnetCmd := cmd.TestnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}) | ||
testnetCmd.SetArgs([]string{ | ||
fmt.Sprintf("--%s=test", flags.FlagKeyringBackend), | ||
fmt.Sprintf("--v=%v", n), | ||
fmt.Sprintf("--output-dir=%s", home), | ||
}) | ||
_ = testnetCmd.ExecuteContext(ctx) | ||
|
||
genFile := cfg.GenesisFile() | ||
appState, gendoc, _ := genutiltypes.GenesisStateFromGenFile(genFile) | ||
return appState, gendoc | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since you check that on the
Validate
function of thecheckpointing
module, you don't need to do it again here as theValidateFunction
already gets called.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is true, but I just thought
CheckCorrespondence
is rather independent. It does not hurt if we do the length checking here again. What if some day we accidentally moveCheckCorrespondence
before the module validation?