Skip to content

Commit

Permalink
feat(staking): create-validator and gentx with SEDA keys
Browse files Browse the repository at this point in the history
  • Loading branch information
hacheigriega committed Dec 4, 2024
1 parent 8de6b43 commit f8f57da
Show file tree
Hide file tree
Showing 21 changed files with 959 additions and 317 deletions.
7 changes: 4 additions & 3 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ import (

// Used in cosmos-sdk when registering the route for swagger docs.
_ "github.com/sedaprotocol/seda-chain/client/docs/statik"
"github.com/sedaprotocol/seda-chain/cmd/sedad/gentx"
"github.com/sedaprotocol/seda-chain/x/batching"
batchingkeeper "github.com/sedaprotocol/seda-chain/x/batching/keeper"
batchingtypes "github.com/sedaprotocol/seda-chain/x/batching/types"
Expand Down Expand Up @@ -171,7 +172,7 @@ var (
// non-dependant module elements, such as codec registration
// and genesis verification.
ModuleBasics = module.NewBasicManager(
genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
genutil.NewAppModuleBasic(gentx.GenTxValidator),
auth.AppModuleBasic{},
authzmodule.AppModuleBasic{},
vesting.AppModuleBasic{},
Expand Down Expand Up @@ -780,7 +781,7 @@ func NewApp(
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, nil),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, nil, app.interfaceRegistry),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, nil),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, nil),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.PubKeyKeeper),
upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.AddressCodec()),
evidence.NewAppModule(app.EvidenceKeeper),
consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper),
Expand Down Expand Up @@ -808,7 +809,7 @@ func NewApp(
app.bmm = module.NewBasicManagerFromManager(
app.mm,
map[string]module.AppModuleBasic{
genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
genutiltypes.ModuleName: genutil.NewAppModuleBasic(gentx.GenTxValidator),
govtypes.ModuleName: gov.NewAppModuleBasic(
[]govclient.ProposalHandler{
// paramsclient.ProposalHandler,
Expand Down
5 changes: 3 additions & 2 deletions cmd/sedad/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import (
"github.com/sedaprotocol/seda-chain/app"
appparams "github.com/sedaprotocol/seda-chain/app/params"
_ "github.com/sedaprotocol/seda-chain/client/docs/statik" // for swagger docs
"github.com/sedaprotocol/seda-chain/cmd/sedad/gentx"
)

// NewRootCmd creates a new root command for a Cosmos SDK application
Expand Down Expand Up @@ -187,13 +188,13 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig, basi
rootCmd.AddCommand(
genutilcli.InitCmd(basicManager, app.DefaultNodeHome),
JoinNetworkCommand(basicManager, app.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(
gentx.CollectGenTxsCmd(
banktypes.GenesisBalancesIterator{},
app.DefaultNodeHome,
gentxModule.GenTxValidator,
encodingConfig.InterfaceRegistry.SigningContext().ValidatorAddressCodec(),
),
genutilcli.GenTxCmd(
gentx.GenTxCmd(
basicManager,
encodingConfig.TxConfig,
banktypes.GenesisBalancesIterator{},
Expand Down
4 changes: 2 additions & 2 deletions cmd/sedad/gentx/collect_gentxs.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func GenAppStateFromConfig(cdc codec.JSONCodec, txEncodingConfig client.TxEncodi
}

// CollectTxs processes and validates application's genesis Txs of type
// MsgCreateValidatorWithVRF and returns the list of appGenTxs and
// MsgCreateSEDAValidator and returns the list of appGenTxs and
// persistent peers required to generate genesis.json.
func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTxsDir string,
genesis *types.AppGenesis, genBalIterator types.GenesisBalancesIterator,
Expand Down Expand Up @@ -188,7 +188,7 @@ func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTx

// genesis transactions must be single-message
msgs := genTx.GetMsgs()
msg := msgs[0].(*stakingtypes.MsgCreateValidatorWithVRF)
msg := msgs[0].(*stakingtypes.MsgCreateSEDAValidator)

// validate validator addresses and funds against the accounts in the state
valAddr, err := valAddrCodec.StringToBytes(msg.ValidatorAddress)
Expand Down
305 changes: 305 additions & 0 deletions cmd/sedad/gentx/gentx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,305 @@
package gentx

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"

"github.com/spf13/cobra"

address "cosmossdk.io/core/address"
"cosmossdk.io/errors"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"

"github.com/sedaprotocol/seda-chain/app/utils"
customcli "github.com/sedaprotocol/seda-chain/x/staking/client/cli"
stakingtypes "github.com/sedaprotocol/seda-chain/x/staking/types"
)

//nolint:revive
func GenTxValidator(msgs []sdk.Msg) error {
if len(msgs) != 1 {
return fmt.Errorf("unexpected number of GenTx messages; got: %d, expected: 1", len(msgs))
}
if _, ok := msgs[0].(*stakingtypes.MsgCreateSEDAValidator); !ok {
return fmt.Errorf("unexpected GenTx message type; expected: MsgCreateSEDAValidator, got: %T", msgs[0])
}

if m, ok := msgs[0].(sdk.HasValidateBasic); ok {
if err := m.ValidateBasic(); err != nil {
return fmt.Errorf("invalid GenTx '%s': %w", msgs[0], err)
}
}

return nil
}

// GenTxCmd builds the application's gentx command.
//
//nolint:revive
func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string, valAdddressCodec address.Codec) *cobra.Command {
ipDefault, _ := server.ExternalIP()
fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault)

cmd := &cobra.Command{
Use: "gentx [key_name] [amount]",
Short: "Generate a genesis tx carrying a self delegation and VRF public key",
Args: cobra.ExactArgs(2),
Long: fmt.Sprintf(`Generate a genesis transaction that creates a validator with a self-delegation and
VRF public key. The transaction is signed by the key in the Keyring referenced by a given name. A VRF key pair
is generated and stored in the configuration directory during the process. A node ID and consensus pubkey may
optionally be provided. If they are omitted, they will be retrieved from the priv_validator.json file.
The following default parameters are included:
%s
Example:
$ %s gentx my-key-name 1000000seda --home=/path/to/home/dir --keyring-backend=os --chain-id=sedachain \
--moniker="myvalidator" \
--commission-max-change-rate=0.01 \
--commission-max-rate=1.0 \
--commission-rate=0.07 \
--details="..." \
--security-contact="..." \
--website="..."
`, defaultsDesc, version.AppName,
),
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := server.GetServerContextFromCmd(cmd)
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
cdc := clientCtx.Codec

config := serverCtx.Config
config.SetRoot(clientCtx.HomeDir)

nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(serverCtx.Config)
if err != nil {
return errors.Wrap(err, "failed to initialize node validator files")
}
// vrfPubKey, err := utils.LoadOrGenVRFKey(serverCtx.Config, "") // TODO (#314)
// if err != nil {
// return errors.Wrap(err, "failed to initialize VRF key")
// }

// read --nodeID, if empty take it from priv_validator.json
if nodeIDString, _ := cmd.Flags().GetString(cli.FlagNodeID); nodeIDString != "" {
nodeID = nodeIDString
}

// read --pubkey, if empty take it from priv_validator.json
if pkStr, _ := cmd.Flags().GetString(cli.FlagPubKey); pkStr != "" {
if err := clientCtx.Codec.UnmarshalInterfaceJSON([]byte(pkStr), &valPubKey); err != nil {
return errors.Wrap(err, "failed to unmarshal validator public key")
}
}

appGenesis, err := types.AppGenesisFromFile(config.GenesisFile())
if err != nil {
return errors.Wrapf(err, "failed to read genesis doc file %s", config.GenesisFile())
}

var genesisState map[string]json.RawMessage
if err = json.Unmarshal(appGenesis.AppState, &genesisState); err != nil {
return errors.Wrap(err, "failed to unmarshal genesis state")
}

if err = mbm.ValidateGenesis(cdc, txEncCfg, genesisState); err != nil {
return errors.Wrap(err, "failed to validate genesis state")
}

inBuf := bufio.NewReader(cmd.InOrStdin())

name := args[0]
key, err := clientCtx.Keyring.Key(name)
if err != nil {
return errors.Wrapf(err, "failed to fetch '%s' from the keyring", name)
}

moniker := config.Moniker
if m, _ := cmd.Flags().GetString(cli.FlagMoniker); m != "" {
moniker = m
}

// Generate SEDA keys.
pub, err := key.GetAddress()
if err != nil {
return err
}
clientCtx = clientCtx.WithInput(inBuf).WithFromAddress(pub)

valAddr := sdk.ValAddress(clientCtx.GetFromAddress())
if valAddr.Empty() {
return fmt.Errorf("set the from address using --from flag")
}
pks, err := utils.GenerateSEDAKeys(valAddr, filepath.Dir(config.PrivValidatorKeyFile()))
if err != nil {
return err
}

// set flags for creating a gentx
sdkCfg, err := cli.PrepareConfigForTxCreateValidator(cmd.Flags(), moniker, nodeID, appGenesis.ChainID, valPubKey)
if err != nil {
return errors.Wrap(err, "error creating configuration to create validator msg")
}
createValCfg := customcli.TxCreateValidatorConfig{
TxCreateValidatorConfig: sdkCfg,
SEDAPubKeys: pks,
}

amount := args[1]
coins, err := sdk.ParseCoinsNormalized(amount)
if err != nil {
return errors.Wrap(err, "failed to parse coins")
}
addr, err := key.GetAddress()
if err != nil {
return err
}
err = genutil.ValidateAccountInGenesis(genesisState, genBalIterator, addr, coins, cdc)
if err != nil {
return errors.Wrap(err, "failed to validate account in genesis")
}

txFactory, err := tx.NewFactoryCLI(clientCtx, cmd.Flags())
if err != nil {
return err
}

// The following line comes from a discrepancy between the `gentx`
// and `create-validator` commands:
// - `gentx` expects amount as an arg,
// - `create-validator` expects amount as a required flag.
// ref: https://github.com/cosmos/cosmos-sdk/issues/8251
// Since gentx doesn't set the amount flag (which `create-validator`
// reads from), we copy the amount arg into the valCfg directly.
//
// Ideally, the `create-validator` command should take a validator
// config file instead of so many flags.
// ref: https://github.com/cosmos/cosmos-sdk/issues/8177
createValCfg.Amount = amount

// create a 'create-validator' message
txf, msg, err := customcli.BuildCreateSEDAValidatorMsg(clientCtx, createValCfg, txFactory, true, valAdddressCodec)
if err != nil {
return errors.Wrap(err, "failed to build create-validator-with-vrf message")
}

if key.GetType() == keyring.TypeOffline || key.GetType() == keyring.TypeMulti {
cmd.PrintErrln("Offline key passed in. Use `tx sign` command to sign.")
return txf.PrintUnsignedTx(clientCtx, msg)
}

// write the unsigned transaction to the buffer
w := bytes.NewBuffer([]byte{})
clientCtx = clientCtx.WithOutput(w)

if m, ok := msg.(sdk.HasValidateBasic); ok {
if err := m.ValidateBasic(); err != nil {
return err
}
}

if err = txf.PrintUnsignedTx(clientCtx, msg); err != nil {
return errors.Wrap(err, "failed to print unsigned std tx")
}

// read the transaction
stdTx, err := readUnsignedGenTxFile(clientCtx, w)
if err != nil {
return errors.Wrap(err, "failed to read unsigned gen tx file")
}

// sign the transaction and write it to the output file
txBuilder, err := clientCtx.TxConfig.WrapTxBuilder(stdTx)
if err != nil {
return fmt.Errorf("error creating tx builder: %w", err)
}

err = authclient.SignTx(txFactory, clientCtx, name, txBuilder, true, true)
if err != nil {
return errors.Wrap(err, "failed to sign std tx")
}

outputDocument, _ := cmd.Flags().GetString(flags.FlagOutputDocument)
if outputDocument == "" {
outputDocument, err = makeOutputFilepath(config.RootDir, nodeID)
if err != nil {
return errors.Wrap(err, "failed to create output file path")
}
}

if err := writeSignedGenTx(clientCtx, outputDocument, stdTx); err != nil {
return errors.Wrap(err, "failed to write signed gen tx")
}

cmd.PrintErrf("Genesis transaction written to %q\n", outputDocument)
return nil
},
}

cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flags.FlagOutputDocument, "", "Write the genesis transaction JSON document to the given file instead of the default location")
cmd.Flags().AddFlagSet(fsCreateValidator)
flags.AddTxFlagsToCmd(cmd)
_ = cmd.Flags().MarkHidden(flags.FlagOutput) // signing makes sense to output only json

return cmd
}

func makeOutputFilepath(rootDir, nodeID string) (string, error) {
writePath := filepath.Join(rootDir, "config", "gentx")
if err := os.MkdirAll(writePath, 0o700); err != nil {
return "", fmt.Errorf("could not create directory %q: %w", writePath, err)
}

return filepath.Join(writePath, fmt.Sprintf("gentx-%v.json", nodeID)), nil
}

func readUnsignedGenTxFile(clientCtx client.Context, r io.Reader) (sdk.Tx, error) {
bz, err := io.ReadAll(r)
if err != nil {
return nil, err
}

aTx, err := clientCtx.TxConfig.TxJSONDecoder()(bz)
if err != nil {
return nil, err
}

return aTx, err
}

func writeSignedGenTx(clientCtx client.Context, outputDocument string, tx sdk.Tx) error {
outputFile, err := os.OpenFile(outputDocument, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer outputFile.Close()

json, err := clientCtx.TxConfig.TxJSONEncoder()(tx)
if err != nil {
return err
}

_, err = fmt.Fprintf(outputFile, "%s\n", json)

return err
}
Loading

0 comments on commit f8f57da

Please sign in to comment.