From 9bc02f607f1150cfb60f6561ee741ff229aa50fa Mon Sep 17 00:00:00 2001 From: wonjoon Date: Thu, 23 Jan 2025 16:27:17 +0900 Subject: [PATCH 1/3] chore: refactoring by comment --- cmd/babylond/cmd/init.go | 4 +- .../cmd/{migrate.go => migrate_bls.go} | 16 ++++---- .../{migrate_test.go => migrate_bls_test.go} | 8 ++-- privval/file.go | 3 ++ testutil/signer/private.go | 3 +- x/checkpointing/keeper/bls_signer.go | 2 +- x/checkpointing/vote_ext_test.go | 41 ------------------- 7 files changed, 20 insertions(+), 57 deletions(-) rename cmd/babylond/cmd/{migrate.go => migrate_bls.go} (86%) rename cmd/babylond/cmd/{migrate_test.go => migrate_bls_test.go} (95%) diff --git a/cmd/babylond/cmd/init.go b/cmd/babylond/cmd/init.go index 3eedb9ebf..fb3b5fc08 100644 --- a/cmd/babylond/cmd/init.go +++ b/cmd/babylond/cmd/init.go @@ -13,7 +13,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: cosmosInitCmd.Use, Short: cosmosInitCmd.Short, - Long: cosmosInitCmd.Long, + Long: `Initialize validators's and node's configuration files, including the generation and setup of BLS keys for validators.`, Args: cosmosInitCmd.Args, RunE: func(cmd *cobra.Command, args []string) error { if err := cosmosInitCmd.RunE(cmd, args); err != nil { @@ -27,6 +27,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { }, } cmd.Flags().AddFlagSet(cosmosInitCmd.Flags()) - cmd.Flags().String(flagBlsPassword, "", "The password for the BLS key. If a flag is set, the non-empty password should be provided. If a flag is not set, the password will be read from the prompt.") + cmd.Flags().String(flagBlsPassword, "", "The password for the BLS key. If a flag is not set, the password will be read from the prompt.") return cmd } diff --git a/cmd/babylond/cmd/migrate.go b/cmd/babylond/cmd/migrate_bls.go similarity index 86% rename from cmd/babylond/cmd/migrate.go rename to cmd/babylond/cmd/migrate_bls.go index d5620a8a3..5d5c0eb2f 100644 --- a/cmd/babylond/cmd/migrate.go +++ b/cmd/babylond/cmd/migrate_bls.go @@ -28,10 +28,10 @@ func MigrateBlsKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "migrate-bls-key", Short: "Migrate the contents of the priv_validator_key.json file into separate files of bls and comet", - Long: strings.TrimSpace(`migrate splits the contents of the priv_validator_key.json file, + Long: strings.TrimSpace(`Migration splits the contents of the priv_validator_key.json file, which contained both the bls and comet keys used in previous versions, into separate files. -BLS keys are stored along with other validator keys in priv_validator_key.json in previous version, +BLS keys are stored along with the ed25519 validator key in priv_validator_key.json in the previous version, which should exist before running the command (via babylond init or babylond testnet). NOTE: Before proceeding with the migration, ensure you back up the priv_validator_key.json file to a secure location. @@ -63,12 +63,12 @@ func migrate(homeDir, password string) error { filepath := cmtcfg.PrivValidatorKeyFile() if !cmtos.FileExists(filepath) { - return fmt.Errorf("priv_validator_key.json of previous version not found") + return fmt.Errorf("priv_validator_key.json of previous version not found in %s", filepath) } pv, err := loadPrevWrappedFilePV(filepath) if err != nil { - return err + return fmt.Errorf("Error loading priv_validator_key.json from %v: %v\n", filepath, err) } prevCmtPrivKey := pv.PrivKey @@ -86,13 +86,13 @@ func migrate(homeDir, password string) error { blsPv := privval.NewBlsPV(prevBlsPrivKey, privval.DefaultBlsKeyFile(homeDir), privval.DefaultBlsPasswordFile(homeDir)) // before saving keys to files, verify that the migrated keys match - if err := verifyAfterMigration( + if err := verifyBeforeMigration( prevCmtPrivKey, cmtPv.Key.PrivKey, prevBlsPrivKey, blsPv.Key.PrivKey, ); err != nil { - return fmt.Errorf("failed to verify after migration: %w", err) + return fmt.Errorf("failed to verify before migration: %w", err) } // save key to files after verification @@ -115,8 +115,8 @@ func loadPrevWrappedFilePV(filePath string) (*PrevWrappedFilePV, error) { return &pvKey, nil } -// verifyAfterMigration checks if the migrated keys match -func verifyAfterMigration(prevCmtPrivKey, newCmtPrivKey cmtcrypto.PrivKey, prevBlsPrivKey, newBlsPrivKey bls12381.PrivateKey) error { +// verifyBeforeMigration checks if the migrated keys match +func verifyBeforeMigration(prevCmtPrivKey, newCmtPrivKey cmtcrypto.PrivKey, prevBlsPrivKey, newBlsPrivKey bls12381.PrivateKey) error { if bytes.Equal(prevCmtPrivKey.Bytes(), newCmtPrivKey.Bytes()) && bytes.Equal(prevBlsPrivKey, newBlsPrivKey) { return nil } diff --git a/cmd/babylond/cmd/migrate_test.go b/cmd/babylond/cmd/migrate_bls_test.go similarity index 95% rename from cmd/babylond/cmd/migrate_test.go rename to cmd/babylond/cmd/migrate_bls_test.go index 79cbbe6c6..11900f1af 100644 --- a/cmd/babylond/cmd/migrate_test.go +++ b/cmd/babylond/cmd/migrate_bls_test.go @@ -95,7 +95,7 @@ func TestMigrate(t *testing.T) { t.Run("verify after migration", func(t *testing.T) { newCmtPv := cmtprivval.LoadFilePV(newPvKeyFile, newPvStateFile) newBlsPv := privval.LoadBlsPV(newBlsKeyFile, newBlsPasswordFile) - err := verifyAfterMigration( + err := verifyBeforeMigration( pvKey.PrivKey, newCmtPv.Key.PrivKey, pvKey.BlsPrivKey, @@ -146,7 +146,7 @@ func TestVerifyAfterMigration(t *testing.T) { cmtKey := ed25519.GenPrivKey() blsKey := bls12381.GenPrivKey() - err := verifyAfterMigration(cmtKey, cmtKey, blsKey, blsKey) + err := verifyBeforeMigration(cmtKey, cmtKey, blsKey, blsKey) require.NoError(t, err) }) @@ -155,7 +155,7 @@ func TestVerifyAfterMigration(t *testing.T) { cmtKey2 := ed25519.GenPrivKey() blsKey := bls12381.GenPrivKey() - err := verifyAfterMigration(cmtKey1, cmtKey2, blsKey, blsKey) + err := verifyBeforeMigration(cmtKey1, cmtKey2, blsKey, blsKey) require.Error(t, err) require.Contains(t, err.Error(), "migrated keys do not match") }) @@ -165,7 +165,7 @@ func TestVerifyAfterMigration(t *testing.T) { blsKey1 := bls12381.GenPrivKey() blsKey2 := bls12381.GenPrivKey() - err := verifyAfterMigration(cmtKey, cmtKey, blsKey1, blsKey2) + err := verifyBeforeMigration(cmtKey, cmtKey, blsKey1, blsKey2) require.Error(t, err) require.Contains(t, err.Error(), "migrated keys do not match") }) diff --git a/privval/file.go b/privval/file.go index 7cb11bb8f..089e0db00 100644 --- a/privval/file.go +++ b/privval/file.go @@ -4,11 +4,14 @@ import ( "fmt" "github.com/babylonlabs-io/babylon/crypto/bls12381" + "github.com/babylonlabs-io/babylon/x/checkpointing/keeper" checkpointingtypes "github.com/babylonlabs-io/babylon/x/checkpointing/types" cmtcrypto "github.com/cometbft/cometbft/crypto" cmtprivval "github.com/cometbft/cometbft/privval" ) +var _ keeper.BlsSigner = &WrappedFilePV{} + // WrappedFilePV is a wrapper around cmtprivval.FilePV type WrappedFilePV struct { Comet cmtprivval.FilePVKey diff --git a/testutil/signer/private.go b/testutil/signer/private.go index 92f6e1d9b..40f5ae1a8 100644 --- a/testutil/signer/private.go +++ b/testutil/signer/private.go @@ -35,7 +35,7 @@ func SetupTestPrivSigner() (*signer.PrivSigner, error) { return privSigner, nil } -// func GenesisKeyFromPrivSigner(ps *signer.PrivSigner, delegatorAddress sdk.ValAddress) (*checkpointingtypes.GenesisKey, error) { +// GenesisKeyFromPrivSigner returns a GenesisKey from a PrivSigner func GenesisKeyFromPrivSigner(ps *signer.PrivSigner, delegatorAddress sdk.ValAddress) (*checkpointingtypes.GenesisKey, error) { valKeys, err := privval.NewValidatorKeys( ps.PV.Comet.PrivKey, @@ -56,6 +56,7 @@ func GenesisKeyFromPrivSigner(ps *signer.PrivSigner, delegatorAddress sdk.ValAdd ) } +// GeneratePrivSigner generates a PrivSigner for testing func GeneratePrivSigner(nodeDir string) error { nodeCfg := cmtconfig.DefaultConfig() nodeCfg.SetRoot(nodeDir) diff --git a/x/checkpointing/keeper/bls_signer.go b/x/checkpointing/keeper/bls_signer.go index a887b14fb..156d96387 100644 --- a/x/checkpointing/keeper/bls_signer.go +++ b/x/checkpointing/keeper/bls_signer.go @@ -8,8 +8,8 @@ import ( "github.com/babylonlabs-io/babylon/x/checkpointing/types" ) +// BlsSigner is an interface for signing BLS messages type BlsSigner interface { - // GetAddress() sdk.ValAddress SignMsgWithBls(msg []byte) (bls12381.Signature, error) GetBlsPubkey() (bls12381.PublicKey, error) GetValidatorPubkey() crypto.PubKey diff --git a/x/checkpointing/vote_ext_test.go b/x/checkpointing/vote_ext_test.go index 3793365b8..0a4dcc9d0 100644 --- a/x/checkpointing/vote_ext_test.go +++ b/x/checkpointing/vote_ext_test.go @@ -212,44 +212,3 @@ func FuzzExtendVote_EmptyBLSPrivKey(f *testing.F) { require.Error(t, err) }) } - -// WARN -// This test code became untestable after deleting the DelegatorAddress field. -// -// // FuzzExtendVote_NotInValidatorSet tests the case where the -// // private signer is not in the validator set -// func FuzzExtendVote_NotInValidatorSet(f *testing.F) { -// datagen.AddRandomSeedsToFuzzer(f, 10) - -// f.Fuzz(func(t *testing.T, seed int64) { -// r := rand.New(rand.NewSource(seed)) -// // generate the validator set with 10 validators as genesis -// genesisValSet, ps, err := datagen.GenesisValidatorSetWithPrivSigner(10) -// require.NoError(t, err) - -// // the private signer is not included in the validator set -// helper := testhelper.NewHelperWithValSetNoSigner(t, genesisValSet, ps) - -// ek := helper.App.EpochingKeeper - -// epoch := ek.GetEpoch(helper.Ctx) -// require.Equal(t, uint64(1), epoch.EpochNumber) - -// // go to block 10, reaching epoch boundary -// interval := ek.GetParams(helper.Ctx).EpochInterval -// for i := uint64(0); i < interval-2; i++ { -// _, err := helper.ApplyEmptyBlockWithSomeInvalidVoteExtensions(r) -// require.NoError(t, err) -// } - -// req := &abci.RequestExtendVote{ -// Hash: datagen.GenRandomByteArray(r, types.HashSize), -// Height: 10, -// } - -// // error is expected because the BLS signer in not -// // in the validator set -// _, err = helper.App.ExtendVote(helper.Ctx, req) -// require.Error(t, err) -// }) -// } From 83d908869061b1883958f877378838f7bd3df9ea Mon Sep 17 00:00:00 2001 From: wonjoon Date: Thu, 23 Jan 2025 20:34:11 +0900 Subject: [PATCH 2/3] feat: set blspv to blssigner and reduce the dependency with cometpv --- app/keepers/keepers.go | 2 +- privval/bls.go | 19 +++++ privval/file.go | 29 +------- x/checkpointing/keeper/bls_signer.go | 23 +++--- x/checkpointing/keeper/keeper.go | 12 ++++ x/checkpointing/keeper/registration_state.go | 13 ++++ x/checkpointing/types/errors.go | 1 + x/checkpointing/vote_ext.go | 19 ++--- x/checkpointing/vote_ext_test.go | 76 ++++++++++---------- 9 files changed, 102 insertions(+), 92 deletions(-) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index 4e40ec10b..ff0586899 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -252,7 +252,7 @@ func (ak *AppKeepers) InitKeepers( checkpointingKeeper := checkpointingkeeper.NewKeeper( appCodec, runtime.NewKVStoreService(keys[checkpointingtypes.StoreKey]), - privSigner.PV, + &privSigner.PV.Bls, epochingKeeper, ) diff --git a/privval/bls.go b/privval/bls.go index a8f43e1ce..be919e440 100644 --- a/privval/bls.go +++ b/privval/bls.go @@ -9,6 +9,7 @@ import ( "github.com/babylonlabs-io/babylon/crypto/bls12381" "github.com/babylonlabs-io/babylon/crypto/erc2335" + "github.com/babylonlabs-io/babylon/x/checkpointing/keeper" checkpointingtypes "github.com/babylonlabs-io/babylon/x/checkpointing/types" cmtcfg "github.com/cometbft/cometbft/config" cmtcrypto "github.com/cometbft/cometbft/crypto" @@ -20,6 +21,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +var _ keeper.BlsSigner = &BlsPVKey{} + const ( DefaultBlsKeyName = "bls_key.json" // Default file name for BLS key DefaultBlsPasswordName = "bls_password.txt" // Default file name for BLS password @@ -181,3 +184,19 @@ func DefaultBlsKeyFile(home string) string { func DefaultBlsPasswordFile(home string) string { return filepath.Join(home, defaultBlsPasswordPath) } + +// SignMsgWithBls signs a message with BLS, implementing the BlsSigner interface +func (k *BlsPVKey) SignMsgWithBls(msg []byte) (bls12381.Signature, error) { + if k.PrivKey == nil { + return nil, fmt.Errorf("BLS private key does not exist: %w", checkpointingtypes.ErrBlsPrivKeyDoesNotExist) + } + return bls12381.Sign(k.PrivKey, msg), nil +} + +// GetBlsPubkey returns the public key of the BLS, implementing the BlsSigner interface +func (k *BlsPVKey) GetBlsPubkey() (bls12381.PublicKey, error) { + if k.PrivKey == nil { + return nil, checkpointingtypes.ErrBlsPrivKeyDoesNotExist + } + return k.PrivKey.PubKey(), nil +} diff --git a/privval/file.go b/privval/file.go index 089e0db00..98ae4362d 100644 --- a/privval/file.go +++ b/privval/file.go @@ -1,16 +1,10 @@ package privval import ( - "fmt" - - "github.com/babylonlabs-io/babylon/crypto/bls12381" - "github.com/babylonlabs-io/babylon/x/checkpointing/keeper" - checkpointingtypes "github.com/babylonlabs-io/babylon/x/checkpointing/types" - cmtcrypto "github.com/cometbft/cometbft/crypto" cmtprivval "github.com/cometbft/cometbft/privval" ) -var _ keeper.BlsSigner = &WrappedFilePV{} +// var _ keeper.BlsSigner = &WrappedFilePV{} // WrappedFilePV is a wrapper around cmtprivval.FilePV type WrappedFilePV struct { @@ -25,24 +19,3 @@ func NewWrappedFilePV(comet cmtprivval.FilePVKey, bls BlsPVKey) *WrappedFilePV { Bls: bls, } } - -// SignMsgWithBls signs a message with BLS, implementing the BlsSigner interface -func (pv *WrappedFilePV) SignMsgWithBls(msg []byte) (bls12381.Signature, error) { - if pv.Bls.PrivKey == nil { - return nil, fmt.Errorf("BLS private key does not exist: %w", checkpointingtypes.ErrBlsPrivKeyDoesNotExist) - } - return bls12381.Sign(pv.Bls.PrivKey, msg), nil -} - -// GetBlsPubkey returns the public key of the BLS, implementing the BlsSigner interface -func (pv *WrappedFilePV) GetBlsPubkey() (bls12381.PublicKey, error) { - if pv.Bls.PrivKey == nil { - return nil, checkpointingtypes.ErrBlsPrivKeyDoesNotExist - } - return pv.Bls.PrivKey.PubKey(), nil -} - -// GetValidatorPubkey returns the public key of the validator, implementing the BlsSigner interface -func (pv *WrappedFilePV) GetValidatorPubkey() cmtcrypto.PubKey { - return pv.Comet.PrivKey.PubKey() -} diff --git a/x/checkpointing/keeper/bls_signer.go b/x/checkpointing/keeper/bls_signer.go index 156d96387..869e9bdf8 100644 --- a/x/checkpointing/keeper/bls_signer.go +++ b/x/checkpointing/keeper/bls_signer.go @@ -1,18 +1,18 @@ package keeper import ( - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" + "context" + "fmt" "github.com/babylonlabs-io/babylon/crypto/bls12381" "github.com/babylonlabs-io/babylon/x/checkpointing/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) // BlsSigner is an interface for signing BLS messages type BlsSigner interface { SignMsgWithBls(msg []byte) (bls12381.Signature, error) GetBlsPubkey() (bls12381.PublicKey, error) - GetValidatorPubkey() crypto.PubKey } // SignBLS signs a BLS signature over the given information @@ -22,14 +22,11 @@ func (k Keeper) SignBLS(epochNum uint64, blockHash types.BlockHash) (bls12381.Si return k.blsSigner.SignMsgWithBls(signBytes) } -// GetConAddressFromPubkey returns the consensus address -func (k Keeper) GetConAddressFromPubkey() sdk.ConsAddress { - pk := k.blsSigner.GetValidatorPubkey() - return sdk.ConsAddress(pk.Address()) -} - -// GetValAddressFromPubkey returns the validator address -func (k Keeper) GetValAddressFromPubkey() sdk.ValAddress { - pk := k.blsSigner.GetValidatorPubkey() - return sdk.ValAddress(pk.Address()) +// GetValidatorAddress returns the validator address of the signer +func (k Keeper) GetValidatorAddress(ctx context.Context) (sdk.ValAddress, error) { + blsPubKey, err := k.blsSigner.GetBlsPubkey() + if err != nil { + return nil, fmt.Errorf("failed to get BLS public key: %w", err) + } + return k.GetValAddr(ctx, blsPubKey) } diff --git a/x/checkpointing/keeper/keeper.go b/x/checkpointing/keeper/keeper.go index ab0d8b853..bae8c0328 100644 --- a/x/checkpointing/keeper/keeper.go +++ b/x/checkpointing/keeper/keeper.go @@ -402,26 +402,37 @@ func (k Keeper) GetBLSPubKeySet(ctx context.Context, epochNumber uint64) ([]*typ return valWithblsKeys, nil } +// GetBlsPubKey returns the BLS public key of the validator func (k Keeper) GetBlsPubKey(ctx context.Context, address sdk.ValAddress) (bls12381.PublicKey, error) { return k.RegistrationState(ctx).GetBlsPubKey(address) } +// GetValAddr returns the validator address of the BLS public key +func (k Keeper) GetValAddr(ctx context.Context, key bls12381.PublicKey) (sdk.ValAddress, error) { + return k.RegistrationState(ctx).GetValAddr(key) +} + +// GetEpoch returns the current epoch func (k Keeper) GetEpoch(ctx context.Context) *epochingtypes.Epoch { return k.epochingKeeper.GetEpoch(ctx) } +// GetValidatorSet returns the validator set for a given epoch func (k Keeper) GetValidatorSet(ctx context.Context, epochNumber uint64) epochingtypes.ValidatorSet { return k.epochingKeeper.GetValidatorSet(ctx, epochNumber) } +// GetTotalVotingPower returns the total voting power for a given epoch func (k Keeper) GetTotalVotingPower(ctx context.Context, epochNumber uint64) int64 { return k.epochingKeeper.GetTotalVotingPower(ctx, epochNumber) } +// GetPubKeyByConsAddr returns the public key of a validator by consensus address func (k Keeper) GetPubKeyByConsAddr(ctx context.Context, consAddr sdk.ConsAddress) (cmtprotocrypto.PublicKey, error) { return k.epochingKeeper.GetPubKeyByConsAddr(ctx, consAddr) } +// GetValidatorByConsAddr returns the validator by consensus address func (k Keeper) GetValidatorByConsAddr(ctx context.Context, consAddr sdk.ConsAddress) (stakingtypes.Validator, error) { return k.epochingKeeper.GetValidatorByConsAddr(ctx, consAddr) } @@ -438,6 +449,7 @@ func (k Keeper) GetLastFinalizedEpoch(ctx context.Context) uint64 { return sdk.BigEndianToUint64(epochNumberBytes) } +// GetEpochByHeight returns the epoch number for a given height func (k Keeper) GetEpochByHeight(ctx context.Context, height uint64) uint64 { return k.epochingKeeper.GetEpochNumByHeight(ctx, height) } diff --git a/x/checkpointing/keeper/registration_state.go b/x/checkpointing/keeper/registration_state.go index 968a4d185..3d3168c9c 100644 --- a/x/checkpointing/keeper/registration_state.go +++ b/x/checkpointing/keeper/registration_state.go @@ -72,6 +72,19 @@ func (rs RegistrationState) GetBlsPubKey(addr sdk.ValAddress) (bls12381.PublicKe return *pk, err } +// GetBlsPubKey retrieves BLS public key by validator's address +func (rs RegistrationState) GetValAddr(key bls12381.PublicKey) (sdk.ValAddress, error) { + pkKey := types.BlsKeyToAddrKey(key) + rawBytes := rs.blsKeysToAddr.Get(pkKey) + if rawBytes == nil { + return nil, types.ErrValAddrDoesNotExist.Wrapf("validator address does not exist with BLS public key %s", key) + } + addr := new(sdk.ValAddress) + err := addr.Unmarshal(rawBytes) + + return *addr, err +} + // Exists checks whether a BLS key exists func (rs RegistrationState) Exists(addr sdk.ValAddress) bool { pkKey := types.AddrToBlsKeyKey(addr) diff --git a/x/checkpointing/types/errors.go b/x/checkpointing/types/errors.go index f212924c6..12112d6e5 100644 --- a/x/checkpointing/types/errors.go +++ b/x/checkpointing/types/errors.go @@ -19,4 +19,5 @@ var ( ErrConflictingCheckpoint = errorsmod.Register(ModuleName, 1213, "Conflicting checkpoint is found") ErrInvalidAppHash = errorsmod.Register(ModuleName, 1214, "Provided app hash is Invalid") ErrInsufficientVotingPower = errorsmod.Register(ModuleName, 1215, "Accumulated voting power is not greater than 2/3 of total power") + ErrValAddrDoesNotExist = errorsmod.Register(ModuleName, 1216, "validator address does not exist") ) diff --git a/x/checkpointing/vote_ext.go b/x/checkpointing/vote_ext.go index 85f75140a..d1b110c6e 100644 --- a/x/checkpointing/vote_ext.go +++ b/x/checkpointing/vote_ext.go @@ -51,19 +51,10 @@ func (h *VoteExtensionHandler) ExtendVote() sdk.ExtendVoteHandler { return emptyRes, nil } - // 1. check if itself is the validator as the BLS sig is only signed - // when the node itself is a validator - - valConsAddr := k.GetConAddressFromPubkey() - val, err := k.GetValidatorByConsAddr(ctx, valConsAddr) - if err != nil { - panic(fmt.Errorf("the BLS signer's consensus address %s is not in the validator set", valConsAddr.String())) - } - - // get signer (delegator address) - signer, err := sdk.ValAddressFromBech32(val.GetOperator()) + // 1. get validator address for VoteExtension structure + valAddr, err := k.GetValidatorAddress(ctx) if err != nil { - panic(fmt.Errorf("the BLS signer's operator %s is not in the validator set", val.GetOperator())) + panic(fmt.Errorf("failed to get validator address: %w", err)) } // 2. sign BLS signature @@ -82,8 +73,8 @@ func (h *VoteExtensionHandler) ExtendVote() sdk.ExtendVoteHandler { // 3. build vote extension ve := &ckpttypes.VoteExtension{ - Signer: signer.String(), - ValidatorAddress: k.GetValAddressFromPubkey().String(), + Signer: valAddr.String(), + ValidatorAddress: valAddr.String(), BlockHash: &bhash, EpochNum: epoch.EpochNumber, Height: uint64(req.Height), diff --git a/x/checkpointing/vote_ext_test.go b/x/checkpointing/vote_ext_test.go index 0a4dcc9d0..0012db73f 100644 --- a/x/checkpointing/vote_ext_test.go +++ b/x/checkpointing/vote_ext_test.go @@ -176,39 +176,43 @@ func FuzzExtendVote_InvalidBlockHash(f *testing.F) { }) } -// FuzzExtendVote_EmptyBLSPrivKey tests the case where the -// BLS private key of the private signer is missing -func FuzzExtendVote_EmptyBLSPrivKey(f *testing.F) { - datagen.AddRandomSeedsToFuzzer(f, 10) - - f.Fuzz(func(t *testing.T, seed int64) { - r := rand.New(rand.NewSource(seed)) - // generate the validator set with 10 validators as genesis - genesisValSet, ps, err := datagen.GenesisValidatorSetWithPrivSigner(10) - require.NoError(t, err) - - // set the BLS private key to be nil to trigger panic - ps.PV.Bls.PrivKey = nil - helper := testhelper.NewHelperWithValSet(t, genesisValSet, ps) - ek := helper.App.EpochingKeeper - - epoch := ek.GetEpoch(helper.Ctx) - require.Equal(t, uint64(1), epoch.EpochNumber) - - // go to block 10, reaching epoch boundary - interval := ek.GetParams(helper.Ctx).EpochInterval - for i := uint64(0); i < interval-2; i++ { - _, err := helper.ApplyEmptyBlockWithVoteExtension(r) - require.NoError(t, err) - } - - req := &abci.RequestExtendVote{ - Hash: datagen.GenRandomByteArray(r, types.HashSize), - Height: 10, - } - - // error is expected due to nil BLS private key - _, err = helper.App.ExtendVote(helper.Ctx, req) - require.Error(t, err) - }) -} +// Since validator address is available to obtain +// from kvstore in the x/checkpointing module, +// This test case is inappropriate. +// +// // FuzzExtendVote_EmptyBLSPrivKey tests the case where the +// // BLS private key of the private signer is missing +// func FuzzExtendVote_EmptyBLSPrivKey(f *testing.F) { +// datagen.AddRandomSeedsToFuzzer(f, 10) + +// f.Fuzz(func(t *testing.T, seed int64) { +// r := rand.New(rand.NewSource(seed)) +// // generate the validator set with 10 validators as genesis +// genesisValSet, ps, err := datagen.GenesisValidatorSetWithPrivSigner(10) +// require.NoError(t, err) + +// // set the BLS private key to be nil to trigger panic +// ps.PV.Bls.PrivKey = nil +// helper := testhelper.NewHelperWithValSet(t, genesisValSet, ps) +// ek := helper.App.EpochingKeeper + +// epoch := ek.GetEpoch(helper.Ctx) +// require.Equal(t, uint64(1), epoch.EpochNumber) + +// // go to block 10, reaching epoch boundary +// interval := ek.GetParams(helper.Ctx).EpochInterval +// for i := uint64(0); i < interval-2; i++ { +// _, err := helper.ApplyEmptyBlockWithVoteExtension(r) +// require.NoError(t, err) +// } + +// req := &abci.RequestExtendVote{ +// Hash: datagen.GenRandomByteArray(r, types.HashSize), +// Height: 10, +// } + +// // error is expected due to nil BLS private key +// _, err = helper.App.ExtendVote(helper.Ctx, req) +// require.Error(t, err) +// }) +// } From f63c3ae7ccd159a06b8d60518c2afbf8afe157e9 Mon Sep 17 00:00:00 2001 From: wonjoon Date: Thu, 23 Jan 2025 21:35:29 +0900 Subject: [PATCH 3/3] feat: mockgen --- privval/file.go | 2 -- testutil/mocks/bls_signer.go | 31 ------------------------------- 2 files changed, 33 deletions(-) diff --git a/privval/file.go b/privval/file.go index 98ae4362d..8b14513e3 100644 --- a/privval/file.go +++ b/privval/file.go @@ -4,8 +4,6 @@ import ( cmtprivval "github.com/cometbft/cometbft/privval" ) -// var _ keeper.BlsSigner = &WrappedFilePV{} - // WrappedFilePV is a wrapper around cmtprivval.FilePV type WrappedFilePV struct { Comet cmtprivval.FilePVKey diff --git a/testutil/mocks/bls_signer.go b/testutil/mocks/bls_signer.go index c59a2fcd7..9112cc5fa 100644 --- a/testutil/mocks/bls_signer.go +++ b/testutil/mocks/bls_signer.go @@ -8,8 +8,6 @@ import ( reflect "reflect" bls12381 "github.com/babylonlabs-io/babylon/crypto/bls12381" - crypto "github.com/cometbft/cometbft/crypto" - types "github.com/cosmos/cosmos-sdk/types" gomock "github.com/golang/mock/gomock" ) @@ -36,20 +34,6 @@ func (m *MockBlsSigner) EXPECT() *MockBlsSignerMockRecorder { return m.recorder } -// GetAddress mocks base method. -func (m *MockBlsSigner) GetAddress() types.ValAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAddress") - ret0, _ := ret[0].(types.ValAddress) - return ret0 -} - -// GetAddress indicates an expected call of GetAddress. -func (mr *MockBlsSignerMockRecorder) GetAddress() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAddress", reflect.TypeOf((*MockBlsSigner)(nil).GetAddress)) -} - // GetBlsPubkey mocks base method. func (m *MockBlsSigner) GetBlsPubkey() (bls12381.PublicKey, error) { m.ctrl.T.Helper() @@ -65,21 +49,6 @@ func (mr *MockBlsSignerMockRecorder) GetBlsPubkey() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlsPubkey", reflect.TypeOf((*MockBlsSigner)(nil).GetBlsPubkey)) } -// GetValidatorPubkey mocks base method. -func (m *MockBlsSigner) GetValidatorPubkey() (crypto.PubKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetValidatorPubkey") - ret0, _ := ret[0].(crypto.PubKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetValidatorPubkey indicates an expected call of GetValidatorPubkey. -func (mr *MockBlsSignerMockRecorder) GetValidatorPubkey() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorPubkey", reflect.TypeOf((*MockBlsSigner)(nil).GetValidatorPubkey)) -} - // SignMsgWithBls mocks base method. func (m *MockBlsSigner) SignMsgWithBls(msg []byte) (bls12381.Signature, error) { m.ctrl.T.Helper()