From a7f3639332024f354156367a0fd205f74ff3ccff Mon Sep 17 00:00:00 2001 From: rhuairahrighairigh Date: Tue, 14 Aug 2018 18:13:54 -0400 Subject: [PATCH] update to app v0.23.1 and add staking --- cmd/kvcli/main.go | 126 +++++++++--- cmd/kvd/main.go | 51 +++-- internal/app/app.go | 179 ++++++++-------- internal/app/genesis.go | 415 +++++++++++++++++++------------------- internal/types/genesis.go | 6 +- 5 files changed, 441 insertions(+), 336 deletions(-) diff --git a/cmd/kvcli/main.go b/cmd/kvcli/main.go index 48c0876b..c9ff604b 100644 --- a/cmd/kvcli/main.go +++ b/cmd/kvcli/main.go @@ -1,11 +1,9 @@ package main import ( - "os" - "github.com/spf13/cobra" - "github.com/tendermint/tmlibs/cli" + "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/keys" @@ -15,15 +13,15 @@ import ( "github.com/cosmos/cosmos-sdk/version" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + //govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" //ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" - //stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" + slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" + stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/kava-labs/kava/internal/app" - "github.com/kava-labs/kava/internal/lcd" - //"github.com/kava-labs/kava/internal/types" + //"github.com/kava-labs/kava/internal/lcd" ) -// rootCmd is the entry point for this binary var ( rootCmd = &cobra.Command{ Use: "kvcli", @@ -32,49 +30,119 @@ var ( ) func main() { - // disable sorting cobra.EnableCommandSorting = false // get the codec - cdc := app.MakeCodec() + cdc := app.CreateKavaAppCodec() - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc, and tx commands + // add standard rpc commands rpc.AddCommands(rootCmd) - rootCmd.AddCommand(client.LineBreak) - tx.AddCommands(rootCmd, cdc) - rootCmd.AddCommand(client.LineBreak) - // add query/post commands (custom to binary) + //Add state commands + tendermintCmd := &cobra.Command{ + Use: "tendermint", + Short: "Tendermint state querying subcommands", + } + tendermintCmd.AddCommand( + rpc.BlockCommand(), + rpc.ValidatorCommand(), + ) + tx.AddCommands(tendermintCmd, cdc) + + //Add IBC commands + // ibcCmd := &cobra.Command{ + // Use: "ibc", + // Short: "Inter-Blockchain Communication subcommands", + // } + // ibcCmd.AddCommand( + // client.PostCommands( + // ibccmd.IBCTransferCmd(cdc), + // ibccmd.IBCRelayCmd(cdc), + // )...) + + advancedCmd := &cobra.Command{ + Use: "advanced", + Short: "Advanced subcommands", + } + + advancedCmd.AddCommand( + tendermintCmd, + //ibcCmd, + //lcd.ServeCommand(cdc), + ) + rootCmd.AddCommand( + advancedCmd, + client.LineBreak, + ) + + //Add stake commands + stakeCmd := &cobra.Command{ + Use: "stake", + Short: "Stake and validation subcommands", + } + stakeCmd.AddCommand( + client.GetCommands( + stakecmd.GetCmdQueryValidator("stake", cdc), + stakecmd.GetCmdQueryValidators("stake", cdc), + stakecmd.GetCmdQueryDelegation("stake", cdc), + stakecmd.GetCmdQueryDelegations("stake", cdc), + slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), + )...) + stakeCmd.AddCommand( + client.PostCommands( + stakecmd.GetCmdCreateValidator(cdc), + stakecmd.GetCmdEditValidator(cdc), + stakecmd.GetCmdDelegate(cdc), + stakecmd.GetCmdUnbond("stake", cdc), + stakecmd.GetCmdRedelegate("stake", cdc), + slashingcmd.GetCmdUnrevoke(cdc), + )...) + rootCmd.AddCommand( + stakeCmd, + ) + + //Add stake commands + // govCmd := &cobra.Command{ + // Use: "gov", + // Short: "Governance and voting subcommands", + // } + // govCmd.AddCommand( + // client.GetCommands( + // govcmd.GetCmdQueryProposal("gov", cdc), + // govcmd.GetCmdQueryVote("gov", cdc), + // govcmd.GetCmdQueryVotes("gov", cdc), + // )...) + // govCmd.AddCommand( + // client.PostCommands( + // govcmd.GetCmdSubmitProposal(cdc), + // govcmd.GetCmdDeposit(cdc), + // govcmd.GetCmdVote(cdc), + // )...) + // rootCmd.AddCommand( + // govCmd, + // ) + + //Add auth and bank commands rootCmd.AddCommand( client.GetCommands( authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), )...) - rootCmd.AddCommand( client.PostCommands( bankcmd.SendTxCmd(cdc), - //ibccmd.IBCTransferCmd(cdc), - //ibccmd.IBCRelayCmd(cdc), - //stakecmd.GetCmdCreateValidator(cdc), - //stakecmd.GetCmdEditValidator(cdc), - //stakecmd.GetCmdDelegate(cdc), - //stakecmd.GetCmdUnbond(cdc), )...) // add proxy, version and key info rootCmd.AddCommand( - client.LineBreak, - lcd.ServeCommand(cdc), keys.Commands(), client.LineBreak, version.VersionCmd, ) // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "KV", os.ExpandEnv("$HOME/.kvcli")) - executor.Execute() + executor := cli.PrepareMainCmd(rootCmd, "KV", app.DefaultCLIHome) + err := executor.Execute() + if err != nil { + panic(err) + } } diff --git a/cmd/kvd/main.go b/cmd/kvd/main.go index 3231ce4d..fd291af2 100644 --- a/cmd/kvd/main.go +++ b/cmd/kvd/main.go @@ -2,45 +2,60 @@ package main import ( "encoding/json" - "os" + "io" + + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/spf13/cobra" + "github.com/spf13/viper" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/cli" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" - "github.com/tendermint/tmlibs/cli" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" "github.com/cosmos/cosmos-sdk/server" "github.com/kava-labs/kava/internal/app" ) func main() { - cdc := app.MakeCodec() + // Create an app codec + cdc := app.CreateKavaAppCodec() + + // Create a server context (a struct of a tendermint config and a logger) ctx := server.NewDefaultContext() + // Create the root kvd command + cobra.EnableCommandSorting = false rootCmd := &cobra.Command{ Use: "kvd", Short: "Kava Daemon", PersistentPreRunE: server.PersistentPreRunEFn(ctx), } - server.AddCommands(ctx, cdc, rootCmd, app.CreateAppInit(), - server.ConstructAppCreator(newApp, "kava"), - server.ConstructAppExporter(exportAppStateAndTMValidators, "kava")) + // Add server commands to kvd, passing in the app + appInit := app.KavaAppInit() + appCreator := server.ConstructAppCreator(newApp, "kava") // init db before calling newApp + appExporter := server.ConstructAppExporter(exportAppStateAndTMValidators, "kava") - // prepare and add flags - rootDir := os.ExpandEnv("$HOME/.kvd") - executor := cli.PrepareBaseCmd(rootCmd, "KV", rootDir) - executor.Execute() + server.AddCommands(ctx, cdc, rootCmd, appInit, appCreator, appExporter) + + // handle envs and add some flags and stuff + executor := cli.PrepareBaseCmd(rootCmd, "KV", app.DefaultNodeHome) + + // Run kvd + err := executor.Execute() + if err != nil { + panic(err) + } } -func newApp(logger log.Logger, db dbm.DB) abci.Application { - return app.NewKavaApp(logger, db) +func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { + return app.NewKavaApp(logger, db, traceStore, baseapp.SetPruning(viper.GetString("pruning"))) } -func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB) (json.RawMessage, []tmtypes.GenesisValidator, error) { - bapp := app.NewKavaApp(logger, db) - return bapp.ExportAppStateAndValidators() +func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB, traceStore io.Writer) (json.RawMessage, []tmtypes.GenesisValidator, error) { + tempApp := app.NewKavaApp(logger, db, traceStore) + return tempApp.ExportAppStateAndValidators() } diff --git a/internal/app/app.go b/internal/app/app.go index e62665db..ed117c28 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -2,29 +2,36 @@ package app import ( "encoding/json" + "io" + "os" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" bam "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" + //"github.com/cosmos/cosmos-sdk/x/gov" //"github.com/cosmos/cosmos-sdk/x/ibc" - //"github.com/cosmos/cosmos-sdk/x/slashing" - //"github.com/cosmos/cosmos-sdk/x/stake" - "github.com/kava-labs/kava/internal/types" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" ) const ( appName = "KavaApp" ) -// Extended ABCI application +// Set default directories for data +var ( + DefaultCLIHome = os.ExpandEnv("$HOME/.kvcli") + DefaultNodeHome = os.ExpandEnv("$HOME/.kvd") +) + type KavaApp struct { *bam.BaseApp cdc *wire.Codec @@ -32,61 +39,78 @@ type KavaApp struct { // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey - //keyIBC *sdk.KVStoreKey - //keyStake *sdk.KVStoreKey - //keySlashing *sdk.KVStoreKey + //keyIBC *sdk.KVStoreKey + keyStake *sdk.KVStoreKey + keySlashing *sdk.KVStoreKey + //keyGov *sdk.KVStoreKey + keyFeeCollection *sdk.KVStoreKey - // Manage getting and setting accounts + // keepers accountMapper auth.AccountMapper feeCollectionKeeper auth.FeeCollectionKeeper coinKeeper bank.Keeper //ibcMapper ibc.Mapper - //stakeKeeper stake.Keeper - //slashingKeeper slashing.Keeper + stakeKeeper stake.Keeper + slashingKeeper slashing.Keeper + //govKeeper gov.Keeper } -func NewKavaApp(logger log.Logger, db dbm.DB) *KavaApp { +// Creates a new KavaApp. +func NewKavaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *KavaApp { - // Create app-level codec for txs and accounts. - var cdc = MakeCodec() + // Create a codec for use across the whole app + cdc := CreateKavaAppCodec() - // Create your application object. + // Create a new base app + bApp := bam.NewBaseApp(appName, cdc, logger, db, baseAppOptions...) + bApp.SetCommitMultiStoreTracer(traceStore) + + // Create the kava app, extending baseApp var app = &KavaApp{ - BaseApp: bam.NewBaseApp(appName, cdc, logger, db), + BaseApp: bApp, cdc: cdc, keyMain: sdk.NewKVStoreKey("main"), keyAccount: sdk.NewKVStoreKey("acc"), //keyIBC: sdk.NewKVStoreKey("ibc"), - //keyStake: sdk.NewKVStoreKey("stake"), - //keySlashing: sdk.NewKVStoreKey("slashing"), + keyStake: sdk.NewKVStoreKey("stake"), + keySlashing: sdk.NewKVStoreKey("slashing"), + //keyGov: sdk.NewKVStoreKey("gov"), + keyFeeCollection: sdk.NewKVStoreKey("fee"), } - // Define the accountMapper. + // Define the accountMapper and base account app.accountMapper = auth.NewAccountMapper( cdc, - app.keyAccount, // target store - &auth.BaseAccount{}, + app.keyAccount, + auth.ProtoBaseAccount, ) - // add accountMapper/handlers + // Create the keepers app.coinKeeper = bank.NewKeeper(app.accountMapper) //app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - //app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - //app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) + app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) + app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) + //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - // register message routes + // Register the message handlers app.Router(). - AddRoute("auth", auth.NewHandler(app.accountMapper)). - AddRoute("bank", bank.NewHandler(app.coinKeeper)) + AddRoute("bank", bank.NewHandler(app.coinKeeper)). //AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - //AddRoute("stake", stake.NewHandler(app.stakeKeeper)) + AddRoute("stake", stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)) + //AddRoute("gov", gov.NewHandler(app.govKeeper)) - // Initialize BaseApp. + // Set func to initialze the chain from appState in genesis file app.SetInitChainer(app.initChainer) + + // Set functions that run before and after txs / blocks app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount) //, app.keyIBC, app.keyStake, app.keySlashing) + + // Mount stores + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyStake, app.keySlashing, app.keyFeeCollection) err := app.LoadLatestVersion(app.keyMain) if err != nil { cmn.Exit(err.Error()) @@ -94,95 +118,90 @@ func NewKavaApp(logger log.Logger, db dbm.DB) *KavaApp { return app } -// Custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - wire.RegisterCrypto(cdc) // Register crypto. - sdk.RegisterWire(cdc) // Register Msgs - bank.RegisterWire(cdc) - //stake.RegisterWire(cdc) - //slashing.RegisterWire(cdc) +// Creates a codec for use across the whole app. +func CreateKavaAppCodec() *wire.Codec { + cdc := wire.NewCodec() //ibc.RegisterWire(cdc) + bank.RegisterWire(cdc) + stake.RegisterWire(cdc) + slashing.RegisterWire(cdc) + //gov.RegisterWire(cdc) auth.RegisterWire(cdc) - - // register custom AppAccount - //cdc.RegisterInterface((*auth.Account)(nil), nil) - //cdc.RegisterConcrete(&types.BaseAccount{}, "kava/Account", nil) + sdk.RegisterWire(cdc) + wire.RegisterCrypto(cdc) return cdc } -// application updates every end block +// The function baseapp runs on receipt of a BeginBlock ABCI message func (app *KavaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - //tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - //return abci.ResponseBeginBlock{ - // Tags: tags.ToKVPairs(), - //} - return abci.ResponseBeginBlock{} + return abci.ResponseBeginBlock{ + Tags: tags.ToKVPairs(), + } } -// application updates every end block +// The function baseapp runs on receipt of a EndBlock ABCI message func (app *KavaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - //validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) + validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - //return abci.ResponseEndBlock{ - // ValidatorUpdates: validatorUpdates, - //} - return abci.ResponseEndBlock{} + //tags, _ := gov.EndBlocker(ctx, app.govKeeper) + + return abci.ResponseEndBlock{ + ValidatorUpdates: validatorUpdates, + //Tags: tags, + } } -// Custom logic for initialization +// Initialzes the app db from the appState in the genesis file. Baseapp runs this on receipt of an InitChain ABCI message func (app *KavaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { stateJSON := req.AppStateBytes - genesisState := new(types.GenesisState) - err := app.cdc.UnmarshalJSON(stateJSON, genesisState) + var genesisState GenesisState + err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") + panic(err) } + // load the accounts for _, gacc := range genesisState.Accounts { - acc, err := gacc.ToAppAccount() - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } + acc := gacc.ToAccount() acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) app.accountMapper.SetAccount(ctx, acc) } // load the initial stake information - //stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + if err != nil { + panic(err) + } + + //gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState()) return abci.ResponseInitChain{} } -// Custom logic for state export +// func (app *KavaApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { ctx := app.NewContext(true, abci.Header{}) // iterate to get the accounts - accounts := []types.GenesisAccount{} + accounts := []GenesisAccount{} appendAccount := func(acc auth.Account) (stop bool) { - account := types.GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } + account := NewGenesisAccountI(acc) accounts = append(accounts, account) return false } app.accountMapper.IterateAccounts(ctx, appendAccount) - genState := types.GenesisState{ - Accounts: accounts, + genState := GenesisState{ + Accounts: accounts, + StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), } appState, err = wire.MarshalJSONIndent(app.cdc, genState) if err != nil { return nil, nil, err } - - validators = make([]tmtypes.GenesisValidator, 0) // TODO export the actual validators - - return appState, validators, err + validators = stake.WriteValidators(ctx, app.stakeKeeper) + return appState, validators, nil } diff --git a/internal/app/genesis.go b/internal/app/genesis.go index fdb3a714..458dcaf8 100644 --- a/internal/app/genesis.go +++ b/internal/app/genesis.go @@ -4,20 +4,219 @@ import ( "encoding/json" "errors" - //"github.com/spf13/pflag" - //"github.com/spf13/viper" - crypto "github.com/tendermint/go-crypto" + "github.com/spf13/pflag" + "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" - //"github.com/cosmos/cosmos-sdk/x/stake" - - "github.com/kava-labs/kava/internal/types" + "github.com/cosmos/cosmos-sdk/x/stake" ) +var ( + // bonded tokens given to genesis validators/accounts + freeFermionVal = int64(100) + freeFermionsAcc = int64(50) +) + +// Initial app state to be written to (and read from) genesis file +type GenesisState struct { + Accounts []GenesisAccount `json:"accounts"` + StakeData stake.GenesisState `json:"stake"` +} + +// A simplified version of a normal account. It doesn't have pubkey or sequence. +type GenesisAccount struct { + Address sdk.AccAddress `json:"address"` + Coins sdk.Coins `json:"coins"` +} + +// TODO remove? +func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { + return GenesisAccount{ + Address: acc.Address, + Coins: acc.Coins, + } +} + +// TODO remove? +func NewGenesisAccountI(acc auth.Account) GenesisAccount { + return GenesisAccount{ + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + } +} + +// Converts a GenesisAccount to auth.BaseAccount TODO rename +func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { + return &auth.BaseAccount{ + Address: ga.Address, + Coins: ga.Coins.Sort(), + } +} + +// Create the appInit stuct for server init command +func KavaAppInit() server.AppInit { + fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) + fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) + + fsAppGenTx.String(server.FlagName, "", "validator moniker, required") + fsAppGenTx.String(server.FlagClientHome, DefaultCLIHome, + "home directory for the client, used for key generation") + fsAppGenTx.Bool(server.FlagOWK, false, "overwrite the accounts created") + + return server.AppInit{ + FlagsAppGenState: fsAppGenState, + FlagsAppGenTx: fsAppGenTx, + AppGenTx: KavaAppGenTx, + AppGenState: KavaAppGenStateJSON, + } +} + +// Define format for GenTx json +type KavaGenTx struct { + Name string `json:"name"` + Address sdk.AccAddress `json:"address"` + PubKey string `json:"pub_key"` +} + +// Generate a genesis transsction +func KavaAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + + // Generate address and secret key for the validator + if genTxConfig.Name == "" { + return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + } + var addr sdk.AccAddress + var secret string + addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "password", genTxConfig.Overwrite) + if err != nil { + return + } + + // Create string to print out + mm := map[string]string{"secret": secret} + var bz []byte + bz, err = cdc.MarshalJSON(mm) + if err != nil { + return + } + cliPrint = json.RawMessage(bz) + + // Create genTx and validator + appGenTx, _, validator, err = KavaAppGenTxNF(cdc, pk, addr, genTxConfig.Name) + + return +} + +// TODO combine with KavaAppGenTx +func KavaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + + // Create the gentx + var bz []byte + genTx := KavaGenTx{ + Name: name, + Address: addr, + PubKey: sdk.MustBech32ifyAccPub(pk), + } + bz, err = wire.MarshalJSONIndent(cdc, genTx) + if err != nil { + return + } + appGenTx = json.RawMessage(bz) + + // Create the validator + validator = tmtypes.GenesisValidator{ + PubKey: pk, + Power: freeFermionVal, + } + return +} + +// Create the core parameters for genesis initialization +// note that the pubkey input is this machines pubkey +func KavaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { + + if len(appGenTxs) == 0 { + err = errors.New("must provide at least 1 genesis transaction") + return + } + + // start with the default staking genesis state + stakeData := stake.DefaultGenesisState() + + // get genesis flag account information + genaccs := make([]GenesisAccount, len(appGenTxs)) + for i, appGenTx := range appGenTxs { + + var genTx KavaGenTx + err = cdc.UnmarshalJSON(appGenTx, &genTx) + if err != nil { + return + } + + // create the genesis account, give'm few steaks and a buncha token with there name + accAuth := auth.NewBaseAccountWithAddress(genTx.Address) + accAuth.Coins = sdk.Coins{ + {genTx.Name + "Token", sdk.NewInt(1000)}, + {"steak", sdk.NewInt(freeFermionsAcc)}, + } + acc := NewGenesisAccount(&accAuth) + genaccs[i] = acc + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc)) // increase the supply + + // add the validator + if len(genTx.Name) > 0 { + desc := stake.NewDescription(genTx.Name, "", "", "") + validator := stake.NewValidator(genTx.Address, + sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) + + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal)) // increase the supply + + // add some new shares to the validator + var issuedDelShares sdk.Rat + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) + stakeData.Validators = append(stakeData.Validators, validator) + + // create the self-delegation from the issuedDelShares + delegation := stake.Delegation{ + DelegatorAddr: validator.Owner, + ValidatorAddr: validator.Owner, + Shares: issuedDelShares, + Height: 0, + } + + stakeData.Bonds = append(stakeData.Bonds, delegation) + } + } + + // create the final app state + genesisState = GenesisState{ + Accounts: genaccs, + StakeData: stakeData, + } + return +} + +// Run KavaAppGenState then convert to JSON +func KavaAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + + // create the final app state + genesisState, err := KavaAppGenState(cdc, appGenTxs) + if err != nil { + return nil, err + } + appState, err = wire.MarshalJSONIndent(cdc, genesisState) + return +} + +/* + // A file, genesis.json, is created with the initial state of the kava network. // This is done by creating an AppInit object to be handed to the server when it creates commands. // When `kvd init` is run, a genesis tx is created. Then, from that, an initial app state. @@ -29,11 +228,11 @@ func CreateAppInit() server.AppInit { } } -func KavaAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( +func KavaAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { // Generate address and secret key for the validator - var addr sdk.Address + var addr sdk.AccAddress var secret string addr, secret, err = server.GenerateCoinKey() if err != nil { @@ -103,204 +302,4 @@ func KavaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState jso return } -/* - -// --------------------- default init -------------------------- - -// simple default application init -var DefaultAppInit = AppInit{ - AppGenTx: SimpleAppGenTx, - AppGenState: SimpleAppGenState, -} - -// simple genesis tx -type SimpleGenTx struct { - Addr sdk.Address `json:"addr"` -} - -// Generate a genesis transaction -func SimpleAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var addr sdk.Address - var secret string - addr, secret, err = GenerateCoinKey() - if err != nil { - return - } - - var bz []byte - simpleGenTx := SimpleGenTx{addr} - bz, err = cdc.MarshalJSON(simpleGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - mm := map[string]string{"secret": secret} - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: 10, - } - return -} - -// create the genesis app state -func SimpleAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - if len(appGenTxs) != 1 { - err = errors.New("must provide a single genesis transaction") - return - } - - var genTx SimpleGenTx - err = cdc.UnmarshalJSON(appGenTxs[0], &genTx) - if err != nil { - return - } - - appState = json.RawMessage(fmt.Sprintf(`{ - "accounts": [{ - "address": "%s", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ] - }] -}`, genTx.Addr.String())) - return -} - - -// -------------------- gaia init ---------------------- - -// simple genesis tx -type GaiaGenTx struct { - Name string `json:"name"` - Address sdk.Address `json:"address"` - PubKey crypto.PubKey `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - clientRoot := viper.GetString(flagClientHome) - overwrite := viper.GetBool(flagOWK) - name := viper.GetString(flagName) - if name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.Address - var secret string - addr, secret, err = server.GenerateSaveCoinKey(clientRoot, name, "1234567890", overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx,_,validator,err = GaiaAppGenTxNF(cdc, pk, addr, name, overwrite) - return -} - -// Generate a gaia genesis transaction without flags -func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := GaiaGenTx{ - Name: name, - Address: addr, - PubKey: pk, - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: freeFermionVal, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - // start with the default staking genesis state - stakeData := stake.DefaultGenesisState() - - // get genesis flag account information - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx GaiaGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - {genTx.Name + "Token", 1000}, - {"steak", freeFermionsAcc}, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseUnbondedTokens += freeFermionsAcc // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, genTx.PubKey, desc) - validator.PoolShares = stake.NewBondedShares(sdk.NewRat(freeFermionVal)) - stakeData.Validators = append(stakeData.Validators, validator) - - // pool logic - stakeData.Pool.BondedTokens += freeFermionVal - stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedTokens) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// GaiaAppGenState but with JSON -func GaiaAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := GaiaAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} */ diff --git a/internal/types/genesis.go b/internal/types/genesis.go index ac15e42e..9212fc0b 100644 --- a/internal/types/genesis.go +++ b/internal/types/genesis.go @@ -1,5 +1,8 @@ package types +// DEPRECATED + +/* import ( sdk "github.com/cosmos/cosmos-sdk/types" crypto "github.com/tendermint/go-crypto" @@ -41,7 +44,7 @@ func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder { } */ //___________________________________________________________________________________ - +/* type GenTx struct { Address sdk.Address `json:"address"` PubKey crypto.PubKey `json:"pub_key"` @@ -75,3 +78,4 @@ func (ga *GenesisAccount) ToAppAccount() (acc *auth.BaseAccount, err error) { Coins: ga.Coins.Sort(), }, nil } +*/