reduce module interdependancy, /client refactor (#4415)

* abstract staking BuildCreateValidatorMsg, genutil defines its own flags

* client/ refactor

* staking move keys from keeper to types
This commit is contained in:
frog power 4000 2019-05-28 04:44:04 -04:00 committed by Alessio Treglia
parent 91e75cb74a
commit 73e5ef7c13
72 changed files with 854 additions and 659 deletions

View File

@ -0,0 +1 @@
#4415 /client refactor, reduce genutil dependancy on staking

160
client/alias.go Normal file
View File

@ -0,0 +1,160 @@
// nolint
// autogenerated code using github.com/rigelrozanski/multitool
// aliases generated for the following subdirectories:
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/context
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/flags
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/keys
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/lcd
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/rest
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/rpc
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/tx
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/utils
// ALIASGEN: github.com/cosmos/cosmos-sdk/client/input
package client
import (
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/lcd"
"github.com/cosmos/cosmos-sdk/client/rest"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/client/utils"
)
const (
DefaultGasAdjustment = flags.DefaultGasAdjustment
DefaultGasLimit = flags.DefaultGasLimit
GasFlagAuto = flags.GasFlagAuto
BroadcastBlock = flags.BroadcastBlock
BroadcastSync = flags.BroadcastSync
BroadcastAsync = flags.BroadcastAsync
FlagHome = flags.FlagHome
FlagUseLedger = flags.FlagUseLedger
FlagChainID = flags.FlagChainID
FlagNode = flags.FlagNode
FlagHeight = flags.FlagHeight
FlagGasAdjustment = flags.FlagGasAdjustment
FlagTrustNode = flags.FlagTrustNode
FlagFrom = flags.FlagFrom
FlagName = flags.FlagName
FlagAccountNumber = flags.FlagAccountNumber
FlagSequence = flags.FlagSequence
FlagMemo = flags.FlagMemo
FlagFees = flags.FlagFees
FlagGasPrices = flags.FlagGasPrices
FlagBroadcastMode = flags.FlagBroadcastMode
FlagPrintResponse = flags.FlagPrintResponse
FlagDryRun = flags.FlagDryRun
FlagGenerateOnly = flags.FlagGenerateOnly
FlagIndentResponse = flags.FlagIndentResponse
FlagListenAddr = flags.FlagListenAddr
FlagCORS = flags.FlagCORS
FlagMaxOpenConnections = flags.FlagMaxOpenConnections
FlagRPCReadTimeout = flags.FlagRPCReadTimeout
FlagRPCWriteTimeout = flags.FlagRPCWriteTimeout
FlagOutputDocument = flags.FlagOutputDocument
FlagSkipConfirmation = flags.FlagSkipConfirmation
DefaultKeyPass = keys.DefaultKeyPass
FlagAddress = keys.FlagAddress
FlagPublicKey = keys.FlagPublicKey
FlagBechPrefix = keys.FlagBechPrefix
FlagDevice = keys.FlagDevice
OutputFormatText = keys.OutputFormatText
OutputFormatJSON = keys.OutputFormatJSON
MinPassLength = input.MinPassLength
)
var (
// functions aliases
NewCLIContextWithFrom = context.NewCLIContextWithFrom
NewCLIContext = context.NewCLIContext
GetAccountDecoder = context.GetAccountDecoder
GetFromFields = context.GetFromFields
ErrInvalidAccount = context.ErrInvalidAccount
ErrVerifyCommit = context.ErrVerifyCommit
GetCommands = flags.GetCommands
PostCommands = flags.PostCommands
RegisterRestServerFlags = flags.RegisterRestServerFlags
ParseGas = flags.ParseGas
NewCompletionCmd = flags.NewCompletionCmd
MarshalJSON = keys.MarshalJSON
UnmarshalJSON = keys.UnmarshalJSON
Commands = keys.Commands
NewAddNewKey = keys.NewAddNewKey
NewRecoverKey = keys.NewRecoverKey
NewUpdateKeyReq = keys.NewUpdateKeyReq
NewDeleteKeyReq = keys.NewDeleteKeyReq
GetKeyInfo = keys.GetKeyInfo
GetPassphrase = keys.GetPassphrase
ReadPassphraseFromStdin = keys.ReadPassphraseFromStdin
NewKeyBaseFromHomeFlag = keys.NewKeyBaseFromHomeFlag
NewKeyBaseFromDir = keys.NewKeyBaseFromDir
NewInMemoryKeyBase = keys.NewInMemoryKeyBase
NewRestServer = lcd.NewRestServer
ServeCommand = lcd.ServeCommand
WriteGenerateStdTxResponse = rest.WriteGenerateStdTxResponse
BlockCommand = rpc.BlockCommand
GetChainHeight = rpc.GetChainHeight
BlockRequestHandlerFn = rpc.BlockRequestHandlerFn
LatestBlockRequestHandlerFn = rpc.LatestBlockRequestHandlerFn
RegisterRPCRoutes = rpc.RegisterRPCRoutes
CLIVersionRequestHandler = rpc.CLIVersionRequestHandler
NodeVersionRequestHandler = rpc.NodeVersionRequestHandler
StatusCommand = rpc.StatusCommand
NodeInfoRequestHandlerFn = rpc.NodeInfoRequestHandlerFn
NodeSyncingRequestHandlerFn = rpc.NodeSyncingRequestHandlerFn
ValidatorCommand = rpc.ValidatorCommand
GetValidators = rpc.GetValidators
ValidatorSetRequestHandlerFn = rpc.ValidatorSetRequestHandlerFn
LatestValidatorSetRequestHandlerFn = rpc.LatestValidatorSetRequestHandlerFn
BroadcastTxRequest = tx.BroadcastTxRequest
GetBroadcastCommand = tx.GetBroadcastCommand
EncodeTxRequestHandlerFn = tx.EncodeTxRequestHandlerFn
GetEncodeCommand = tx.GetEncodeCommand
SearchTxCmd = tx.SearchTxCmd
QueryTxCmd = tx.QueryTxCmd
QueryTxsByTagsRequestHandlerFn = tx.QueryTxsByTagsRequestHandlerFn
QueryTxRequestHandlerFn = tx.QueryTxRequestHandlerFn
RegisterTxRoutes = tx.RegisterTxRoutes
SearchTxs = tx.SearchTxs
ValidateTxResult = tx.ValidateTxResult
GenerateOrBroadcastMsgs = utils.GenerateOrBroadcastMsgs
CompleteAndBroadcastTxCLI = utils.CompleteAndBroadcastTxCLI
EnrichWithGas = utils.EnrichWithGas
CalculateGas = utils.CalculateGas
PrintUnsignedStdTx = utils.PrintUnsignedStdTx
SignStdTx = utils.SignStdTx
SignStdTxWithSignerAddress = utils.SignStdTxWithSignerAddress
ReadStdTxFromFile = utils.ReadStdTxFromFile
GetTxEncoder = utils.GetTxEncoder
PrepareTxBuilder = utils.PrepareTxBuilder
BufferStdin = input.BufferStdin
OverrideStdin = input.OverrideStdin
GetPassword = input.GetPassword
GetCheckPassword = input.GetCheckPassword
GetConfirmation = input.GetConfirmation
GetString = input.GetString
PrintPrefixed = input.PrintPrefixed
// variable aliases
LineBreak = flags.LineBreak
GasFlagVar = flags.GasFlagVar
)
type (
CLIContext = context.CLIContext
GasSetting = flags.GasSetting
AddNewKey = keys.AddNewKey
RecoverKey = keys.RecoverKey
UpdateKeyReq = keys.UpdateKeyReq
DeleteKeyReq = keys.DeleteKeyReq
RestServer = lcd.RestServer
ValidatorOutput = rpc.ValidatorOutput
ResultValidatorsOutput = rpc.ResultValidatorsOutput
BroadcastReq = tx.BroadcastReq
EncodeResp = tx.EncodeResp
GasEstimateResponse = utils.GasEstimateResponse
)

View File

@ -7,18 +7,15 @@ import (
"path" "path"
"strconv" "strconv"
"github.com/tendermint/tendermint/libs/cli"
toml "github.com/pelletier/go-toml" toml "github.com/pelletier/go-toml"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client/flags"
) )
const ( const (
flagGet = "get" flagGet = "get"
// DefaultKeyPass contains the default key password for genesis transactions
DefaultKeyPass = "12345678"
) )
var configDefaults = map[string]string{ var configDefaults = map[string]string{
@ -38,7 +35,7 @@ func ConfigCmd(defaultCLIHome string) *cobra.Command {
Args: cobra.RangeArgs(0, 2), Args: cobra.RangeArgs(0, 2),
} }
cmd.Flags().String(cli.HomeFlag, defaultCLIHome, cmd.Flags().String(flags.FlagHome, defaultCLIHome,
"set client's home directory for configuration") "set client's home directory for configuration")
cmd.Flags().Bool(flagGet, false, cmd.Flags().Bool(flagGet, false,
"print configuration value or its default if unset") "print configuration value or its default if unset")
@ -46,7 +43,7 @@ func ConfigCmd(defaultCLIHome string) *cobra.Command {
} }
func runConfigCmd(cmd *cobra.Command, args []string) error { func runConfigCmd(cmd *cobra.Command, args []string) error {
cfgFile, err := ensureConfFile(viper.GetString(cli.HomeFlag)) cfgFile, err := ensureConfFile(viper.GetString(flags.FlagHome))
if err != nil { if err != nil {
return err return err
} }

View File

@ -9,7 +9,8 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
) )
// For https://github.com/cosmos/cosmos-sdk/issues/3899 // For https://github.com/cosmos/cosmos-sdk/issues/3899
@ -19,7 +20,7 @@ func Test_runConfigCmdTwiceWithShorterNodeValue(t *testing.T) {
configHome, cleanup := tmpDir(t) configHome, cleanup := tmpDir(t)
defer cleanup() defer cleanup()
_ = os.RemoveAll(filepath.Join(configHome, "config")) _ = os.RemoveAll(filepath.Join(configHome, "config"))
viper.Set(cli.HomeFlag, configHome) viper.Set(flags.FlagHome, configHome)
// Init command config // Init command config
cmd := ConfigCmd(configHome) cmd := ConfigCmd(configHome)

View File

@ -3,7 +3,7 @@ package context
import ( import (
"fmt" "fmt"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
) )
@ -13,13 +13,13 @@ import (
// defined. // defined.
func (ctx CLIContext) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) { func (ctx CLIContext) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) {
switch ctx.BroadcastMode { switch ctx.BroadcastMode {
case client.BroadcastSync: case flags.BroadcastSync:
res, err = ctx.BroadcastTxSync(txBytes) res, err = ctx.BroadcastTxSync(txBytes)
case client.BroadcastAsync: case flags.BroadcastAsync:
res, err = ctx.BroadcastTxAsync(txBytes) res, err = ctx.BroadcastTxAsync(txBytes)
case client.BroadcastBlock: case flags.BroadcastBlock:
res, err = ctx.BroadcastTxCommit(txBytes) res, err = ctx.BroadcastTxCommit(txBytes)
default: default:

View File

@ -9,7 +9,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys"
@ -65,7 +65,7 @@ func NewCLIContextWithFrom(from string) CLIContext {
var nodeURI string var nodeURI string
var rpc rpcclient.Client var rpc rpcclient.Client
genOnly := viper.GetBool(client.FlagGenerateOnly) genOnly := viper.GetBool(flags.FlagGenerateOnly)
fromAddress, fromName, err := GetFromFields(from, genOnly) fromAddress, fromName, err := GetFromFields(from, genOnly)
if err != nil { if err != nil {
fmt.Printf("failed to get from fields: %v", err) fmt.Printf("failed to get from fields: %v", err)
@ -73,16 +73,16 @@ func NewCLIContextWithFrom(from string) CLIContext {
} }
if !genOnly { if !genOnly {
nodeURI = viper.GetString(client.FlagNode) nodeURI = viper.GetString(flags.FlagNode)
if nodeURI != "" { if nodeURI != "" {
rpc = rpcclient.NewHTTP(nodeURI, "/websocket") rpc = rpcclient.NewHTTP(nodeURI, "/websocket")
} }
} }
// We need to use a single verifier for all contexts // We need to use a single verifier for all contexts
if verifier == nil || verifierHome != viper.GetString(cli.HomeFlag) { if verifier == nil || verifierHome != viper.GetString(flags.FlagHome) {
verifier = createVerifier() verifier = createVerifier()
verifierHome = viper.GetString(cli.HomeFlag) verifierHome = viper.GetString(flags.FlagHome)
} }
return CLIContext{ return CLIContext{
@ -90,41 +90,41 @@ func NewCLIContextWithFrom(from string) CLIContext {
Output: os.Stdout, Output: os.Stdout,
NodeURI: nodeURI, NodeURI: nodeURI,
AccountStore: auth.StoreKey, AccountStore: auth.StoreKey,
From: viper.GetString(client.FlagFrom), From: viper.GetString(flags.FlagFrom),
OutputFormat: viper.GetString(cli.OutputFlag), OutputFormat: viper.GetString(cli.OutputFlag),
Height: viper.GetInt64(client.FlagHeight), Height: viper.GetInt64(flags.FlagHeight),
TrustNode: viper.GetBool(client.FlagTrustNode), TrustNode: viper.GetBool(flags.FlagTrustNode),
UseLedger: viper.GetBool(client.FlagUseLedger), UseLedger: viper.GetBool(flags.FlagUseLedger),
BroadcastMode: viper.GetString(client.FlagBroadcastMode), BroadcastMode: viper.GetString(flags.FlagBroadcastMode),
PrintResponse: viper.GetBool(client.FlagPrintResponse), PrintResponse: viper.GetBool(flags.FlagPrintResponse),
Verifier: verifier, Verifier: verifier,
Simulate: viper.GetBool(client.FlagDryRun), Simulate: viper.GetBool(flags.FlagDryRun),
GenerateOnly: genOnly, GenerateOnly: genOnly,
FromAddress: fromAddress, FromAddress: fromAddress,
FromName: fromName, FromName: fromName,
Indent: viper.GetBool(client.FlagIndentResponse), Indent: viper.GetBool(flags.FlagIndentResponse),
SkipConfirm: viper.GetBool(client.FlagSkipConfirmation), SkipConfirm: viper.GetBool(flags.FlagSkipConfirmation),
} }
} }
// NewCLIContext returns a new initialized CLIContext with parameters from the // NewCLIContext returns a new initialized CLIContext with parameters from the
// command line using Viper. // command line using Viper.
func NewCLIContext() CLIContext { return NewCLIContextWithFrom(viper.GetString(client.FlagFrom)) } func NewCLIContext() CLIContext { return NewCLIContextWithFrom(viper.GetString(flags.FlagFrom)) }
func createVerifier() tmlite.Verifier { func createVerifier() tmlite.Verifier {
trustNodeDefined := viper.IsSet(client.FlagTrustNode) trustNodeDefined := viper.IsSet(flags.FlagTrustNode)
if !trustNodeDefined { if !trustNodeDefined {
return nil return nil
} }
trustNode := viper.GetBool(client.FlagTrustNode) trustNode := viper.GetBool(flags.FlagTrustNode)
if trustNode { if trustNode {
return nil return nil
} }
chainID := viper.GetString(client.FlagChainID) chainID := viper.GetString(flags.FlagChainID)
home := viper.GetString(cli.HomeFlag) home := viper.GetString(flags.FlagHome)
nodeURI := viper.GetString(client.FlagNode) nodeURI := viper.GetString(flags.FlagNode)
var errMsg bytes.Buffer var errMsg bytes.Buffer
if chainID == "" { if chainID == "" {

View File

@ -2,14 +2,10 @@ package context
import ( import (
"fmt" "fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/pkg/errors" "github.com/pkg/errors"
"strings"
abci "github.com/tendermint/tendermint/abci/types" abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/crypto/merkle"
cmn "github.com/tendermint/tendermint/libs/common" cmn "github.com/tendermint/tendermint/libs/common"
@ -19,6 +15,8 @@ import (
tmtypes "github.com/tendermint/tendermint/types" tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/store/rootmulti" "github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
) )
// GetNode returns an RPC client. If the context's client is not defined, an // GetNode returns an RPC client. If the context's client is not defined, an

View File

@ -1,9 +0,0 @@
package client
import "errors"
// common errors for CLI and REST clients
var (
ErrInvalidGasAdjustment = errors.New("invalid gas adjustment")
ErrInvalidSigner = errors.New("tx intended signer does not match the given signer")
)

View File

@ -1,4 +1,4 @@
package client package flags
import ( import (
"fmt" "fmt"
@ -7,6 +7,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
tmcli "github.com/tendermint/tendermint/libs/cli"
) )
// nolint // nolint
@ -28,6 +30,7 @@ const (
// immediately. // immediately.
BroadcastAsync = "async" BroadcastAsync = "async"
FlagHome = tmcli.HomeFlag
FlagUseLedger = "ledger" FlagUseLedger = "ledger"
FlagChainID = "chain-id" FlagChainID = "chain-id"
FlagNode = "node" FlagNode = "node"

View File

@ -1,13 +1,12 @@
package client package input
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"os" "os"
"strings" "strings"
"errors"
"github.com/bgentry/speakeasy" "github.com/bgentry/speakeasy"
isatty "github.com/mattn/go-isatty" isatty "github.com/mattn/go-isatty"
) )

View File

@ -6,7 +6,8 @@ import (
"os" "os"
"sort" "sort"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -31,6 +32,9 @@ const (
flagIndex = "index" flagIndex = "index"
flagMultisig = "multisig" flagMultisig = "multisig"
flagNoSort = "nosort" flagNoSort = "nosort"
// DefaultKeyPass contains the default key password for genesis transactions
DefaultKeyPass = "12345678"
) )
func addKeyCommand() *cobra.Command { func addKeyCommand() *cobra.Command {
@ -62,13 +66,13 @@ the flag --nosort is set.
cmd.Flags().Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied") cmd.Flags().Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied")
cmd.Flags().String(FlagPublicKey, "", "Parse a public key in bech32 format and save it to disk") cmd.Flags().String(FlagPublicKey, "", "Parse a public key in bech32 format and save it to disk")
cmd.Flags().BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic") cmd.Flags().BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic")
cmd.Flags().Bool(client.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device") cmd.Flags().Bool(flags.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device")
cmd.Flags().Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating") cmd.Flags().Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
cmd.Flags().Bool(flagNoBackup, false, "Don't print out seed phrase (if others are watching the terminal)") cmd.Flags().Bool(flagNoBackup, false, "Don't print out seed phrase (if others are watching the terminal)")
cmd.Flags().Bool(flagDryRun, false, "Perform action, but don't add key to local keystore") cmd.Flags().Bool(flagDryRun, false, "Perform action, but don't add key to local keystore")
cmd.Flags().Uint32(flagAccount, 0, "Account number for HD derivation") cmd.Flags().Uint32(flagAccount, 0, "Account number for HD derivation")
cmd.Flags().Uint32(flagIndex, 0, "Address index number for HD derivation") cmd.Flags().Uint32(flagIndex, 0, "Address index number for HD derivation")
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response") cmd.Flags().Bool(flags.FlagIndentResponse, false, "Add indent to JSON response")
return cmd return cmd
} }
@ -86,7 +90,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
var err error var err error
var encryptPassword string var encryptPassword string
buf := client.BufferStdin() buf := input.BufferStdin()
name := args[0] name := args[0]
interactive := viper.GetBool(flagInteractive) interactive := viper.GetBool(flagInteractive)
@ -96,7 +100,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
// we throw this away, so don't enforce args, // we throw this away, so don't enforce args,
// we want to get a new random seed phrase quickly // we want to get a new random seed phrase quickly
kb = keys.NewInMemory() kb = keys.NewInMemory()
encryptPassword = client.DefaultKeyPass encryptPassword = DefaultKeyPass
} else { } else {
kb, err = NewKeyBaseFromHomeFlag() kb, err = NewKeyBaseFromHomeFlag()
if err != nil { if err != nil {
@ -106,7 +110,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
_, err = kb.Get(name) _, err = kb.Get(name)
if err == nil { if err == nil {
// account exists, ask for user confirmation // account exists, ask for user confirmation
if response, err2 := client.GetConfirmation( if response, err2 := input.GetConfirmation(
fmt.Sprintf("override the existing name %s", name), buf); err2 != nil || !response { fmt.Sprintf("override the existing name %s", name), buf); err2 != nil || !response {
return err2 return err2
} }
@ -146,8 +150,8 @@ func runAddCmd(_ *cobra.Command, args []string) error {
} }
// ask for a password when generating a local key // ask for a password when generating a local key
if viper.GetString(FlagPublicKey) == "" && !viper.GetBool(client.FlagUseLedger) { if viper.GetString(FlagPublicKey) == "" && !viper.GetBool(flags.FlagUseLedger) {
encryptPassword, err = client.GetCheckPassword( encryptPassword, err = input.GetCheckPassword(
"Enter a passphrase to encrypt your key to disk:", "Enter a passphrase to encrypt your key to disk:",
"Repeat the passphrase:", buf) "Repeat the passphrase:", buf)
if err != nil { if err != nil {
@ -172,7 +176,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
index := uint32(viper.GetInt(flagIndex)) index := uint32(viper.GetInt(flagIndex))
// If we're using ledger, only thing we need is the path and the bech32 prefix. // If we're using ledger, only thing we need is the path and the bech32 prefix.
if viper.GetBool(client.FlagUseLedger) { if viper.GetBool(flags.FlagUseLedger) {
bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix()
info, err := kb.CreateLedger(name, keys.Secp256k1, bech32PrefixAccAddr, account, index) info, err := kb.CreateLedger(name, keys.Secp256k1, bech32PrefixAccAddr, account, index)
if err != nil { if err != nil {
@ -192,7 +196,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
bip39Message = "Enter your bip39 mnemonic, or hit enter to generate one." bip39Message = "Enter your bip39 mnemonic, or hit enter to generate one."
} }
mnemonic, err = client.GetString(bip39Message, buf) mnemonic, err = input.GetString(bip39Message, buf)
if err != nil { if err != nil {
return err return err
} }
@ -217,7 +221,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
// override bip39 passphrase // override bip39 passphrase
if interactive { if interactive {
bip39Passphrase, err = client.GetString( bip39Passphrase, err = input.GetString(
"Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed. "+ "Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed. "+
"Most users should just hit enter to use the default, \"\"", buf) "Most users should just hit enter to use the default, \"\"", buf)
if err != nil { if err != nil {
@ -226,7 +230,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
// if they use one, make them re-enter it // if they use one, make them re-enter it
if len(bip39Passphrase) != 0 { if len(bip39Passphrase) != 0 {
p2, err := client.GetString("Repeat the passphrase:", buf) p2, err := input.GetString("Repeat the passphrase:", buf)
if err != nil { if err != nil {
return err return err
} }
@ -278,7 +282,7 @@ func printCreate(info keys.Info, showMnemonic bool, mnemonic string) error {
} }
var jsonString []byte var jsonString []byte
if viper.GetBool(client.FlagIndentResponse) { if viper.GetBool(flags.FlagIndentResponse) {
jsonString, err = cdc.MarshalJSONIndent(out, "", " ") jsonString, err = cdc.MarshalJSONIndent(out, "", " ")
} else { } else {
jsonString, err = cdc.MarshalJSON(out) jsonString, err = cdc.MarshalJSON(out)

View File

@ -7,17 +7,16 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/stretchr/testify/assert"
) )
func Test_runAddCmdLedger(t *testing.T) { func Test_runAddCmdLedger(t *testing.T) {
@ -28,13 +27,13 @@ func Test_runAddCmdLedger(t *testing.T) {
kbHome, kbCleanUp := tests.NewTestCaseDir(t) kbHome, kbCleanUp := tests.NewTestCaseDir(t)
assert.NotNil(t, kbHome) assert.NotNil(t, kbHome)
defer kbCleanUp() defer kbCleanUp()
viper.Set(cli.HomeFlag, kbHome) viper.Set(flags.FlagHome, kbHome)
viper.Set(client.FlagUseLedger, true) viper.Set(flags.FlagUseLedger, true)
/// Test Text /// Test Text
viper.Set(cli.OutputFlag, OutputFormatText) viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password // Now enter password
cleanUp1 := client.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n"))) cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp1() defer cleanUp1()
err := runAddCmd(cmd, []string{"keyname1"}) err := runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -6,13 +6,13 @@ import (
"testing" "testing"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
"github.com/cosmos/cosmos-sdk/client"
"github.com/stretchr/testify/assert"
) )
func Test_runAddCmdBasic(t *testing.T) { func Test_runAddCmdBasic(t *testing.T) {
@ -23,12 +23,12 @@ func Test_runAddCmdBasic(t *testing.T) {
kbHome, kbCleanUp := tests.NewTestCaseDir(t) kbHome, kbCleanUp := tests.NewTestCaseDir(t)
assert.NotNil(t, kbHome) assert.NotNil(t, kbHome)
defer kbCleanUp() defer kbCleanUp()
viper.Set(cli.HomeFlag, kbHome) viper.Set(flags.FlagHome, kbHome)
/// Test Text /// Test Text
viper.Set(cli.OutputFlag, OutputFormatText) viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password // Now enter password
cleanUp1 := client.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n"))) cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp1() defer cleanUp1()
err := runAddCmd(cmd, []string{"keyname1"}) err := runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err) assert.NoError(t, err)
@ -36,7 +36,7 @@ func Test_runAddCmdBasic(t *testing.T) {
/// Test Text - Replace? >> FAIL /// Test Text - Replace? >> FAIL
viper.Set(cli.OutputFlag, OutputFormatText) viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password // Now enter password
cleanUp2 := client.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n"))) cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp2() defer cleanUp2()
err = runAddCmd(cmd, []string{"keyname1"}) err = runAddCmd(cmd, []string{"keyname1"})
assert.Error(t, err) assert.Error(t, err)
@ -44,7 +44,7 @@ func Test_runAddCmdBasic(t *testing.T) {
/// Test Text - Replace? Answer >> PASS /// Test Text - Replace? Answer >> PASS
viper.Set(cli.OutputFlag, OutputFormatText) viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password // Now enter password
cleanUp3 := client.OverrideStdin(bufio.NewReader(strings.NewReader("y\ntest1234\ntest1234\n"))) cleanUp3 := input.OverrideStdin(bufio.NewReader(strings.NewReader("y\ntest1234\ntest1234\n")))
defer cleanUp3() defer cleanUp3()
err = runAddCmd(cmd, []string{"keyname1"}) err = runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err) assert.NoError(t, err)
@ -52,7 +52,7 @@ func Test_runAddCmdBasic(t *testing.T) {
// Check JSON // Check JSON
viper.Set(cli.OutputFlag, OutputFormatJSON) viper.Set(cli.OutputFlag, OutputFormatJSON)
// Now enter password // Now enter password
cleanUp4 := client.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n"))) cleanUp4 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp4() defer cleanUp4()
err = runAddCmd(cmd, []string{"keyname2"}) err = runAddCmd(cmd, []string{"keyname2"})
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -8,7 +8,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -53,7 +53,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
return err return err
} }
buf := client.BufferStdin() buf := input.BufferStdin()
if info.GetType() == keys.TypeLedger || info.GetType() == keys.TypeOffline { if info.GetType() == keys.TypeLedger || info.GetType() == keys.TypeOffline {
if !viper.GetBool(flagYes) { if !viper.GetBool(flagYes) {
if err := confirmDeletion(buf); err != nil { if err := confirmDeletion(buf); err != nil {
@ -71,7 +71,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
skipPass := viper.GetBool(flagForce) skipPass := viper.GetBool(flagForce)
var oldpass string var oldpass string
if !skipPass { if !skipPass {
if oldpass, err = client.GetPassword( if oldpass, err = input.GetPassword(
"DANGER - enter password to permanently delete key:", buf); err != nil { "DANGER - enter password to permanently delete key:", buf); err != nil {
return err return err
} }
@ -86,7 +86,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
} }
func confirmDeletion(buf *bufio.Reader) error { func confirmDeletion(buf *bufio.Reader) error {
answer, err := client.GetConfirmation("Key reference will be deleted. Continue?", buf) answer, err := input.GetConfirmation("Key reference will be deleted. Continue?", buf)
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,13 +5,12 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/cosmos/cosmos-sdk/client"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
) )
@ -29,7 +28,7 @@ func Test_runDeleteCmd(t *testing.T) {
// Now add a temporary keybase // Now add a temporary keybase
kbHome, cleanUp := tests.NewTestCaseDir(t) kbHome, cleanUp := tests.NewTestCaseDir(t)
defer cleanUp() defer cleanUp()
viper.Set(cli.HomeFlag, kbHome) viper.Set(flags.FlagHome, kbHome)
// Now // Now
kb, err := NewKeyBaseFromHomeFlag() kb, err := NewKeyBaseFromHomeFlag()
@ -53,7 +52,7 @@ func Test_runDeleteCmd(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
// Now there is a confirmation // Now there is a confirmation
cleanUp := client.OverrideStdin(bufio.NewReader(strings.NewReader("y\n"))) cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("y\n")))
defer cleanUp() defer cleanUp()
err = runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1}) err = runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1})
require.NoError(t, err) require.NoError(t, err)

View File

@ -1,9 +1,8 @@
package keys package keys
import ( import (
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
) )
func listKeysCmd() *cobra.Command { func listKeysCmd() *cobra.Command {
@ -14,7 +13,7 @@ func listKeysCmd() *cobra.Command {
along with their associated name and address.`, along with their associated name and address.`,
RunE: runListCmd, RunE: runListCmd,
} }
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response") cmd.Flags().Bool(flags.FlagIndentResponse, false, "Add indent to JSON response")
return cmd return cmd
} }

View File

@ -3,14 +3,12 @@ package keys
import ( import (
"testing" "testing"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/tests"
"github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/cli"
"github.com/spf13/cobra"
) )
func Test_runListCmd(t *testing.T) { func Test_runListCmd(t *testing.T) {
@ -28,7 +26,7 @@ func Test_runListCmd(t *testing.T) {
kbHome2, cleanUp2 := tests.NewTestCaseDir(t) kbHome2, cleanUp2 := tests.NewTestCaseDir(t)
defer cleanUp2() defer cleanUp2()
viper.Set(cli.HomeFlag, kbHome2) viper.Set(flags.FlagHome, kbHome2)
kb, err := NewKeyBaseFromHomeFlag() kb, err := NewKeyBaseFromHomeFlag()
assert.NoError(t, err) assert.NoError(t, err)
@ -47,7 +45,7 @@ func Test_runListCmd(t *testing.T) {
} }
for _, tt := range testData { for _, tt := range testData {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
viper.Set(cli.HomeFlag, tt.kbDir) viper.Set(flags.FlagHome, tt.kbDir)
if err := runListCmd(tt.args.cmd, tt.args.args); (err != nil) != tt.wantErr { if err := runListCmd(tt.args.cmd, tt.args.args); (err != nil) != tt.wantErr {
t.Errorf("runListCmd() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("runListCmd() error = %v, wantErr %v", err, tt.wantErr)
} }

View File

@ -7,7 +7,7 @@ import (
bip39 "github.com/bartekn/go-bip39" bip39 "github.com/bartekn/go-bip39"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/input"
) )
const ( const (
@ -36,15 +36,15 @@ func runMnemonicCmd(cmd *cobra.Command, args []string) error {
if userEntropy { if userEntropy {
// prompt the user to enter some entropy // prompt the user to enter some entropy
buf := client.BufferStdin() buf := input.BufferStdin()
inputEntropy, err := client.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf) inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf)
if err != nil { if err != nil {
return err return err
} }
if len(inputEntropy) < 43 { if len(inputEntropy) < 43 {
return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy)) return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy))
} }
conf, err := client.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf) conf, err := input.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf)
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,10 +5,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/input"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -28,7 +26,7 @@ func Test_RunMnemonicCmdUser(t *testing.T) {
require.Equal(t, "EOF", err.Error()) require.Equal(t, "EOF", err.Error())
// Try again // Try again
cleanUp := client.OverrideStdin(bufio.NewReader(strings.NewReader("Hi!\n"))) cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("Hi!\n")))
defer cleanUp() defer cleanUp()
err = runMnemonicCmd(cmdUser, []string{}) err = runMnemonicCmd(cmdUser, []string{})
require.Error(t, err) require.Error(t, err)
@ -38,21 +36,21 @@ func Test_RunMnemonicCmdUser(t *testing.T) {
// Now provide "good" entropy :) // Now provide "good" entropy :)
fakeEntropy := strings.Repeat(":)", 40) + "\ny\n" // entropy + accept count fakeEntropy := strings.Repeat(":)", 40) + "\ny\n" // entropy + accept count
cleanUp2 := client.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy))) cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp2() defer cleanUp2()
err = runMnemonicCmd(cmdUser, []string{}) err = runMnemonicCmd(cmdUser, []string{})
require.NoError(t, err) require.NoError(t, err)
// Now provide "good" entropy but no answer // Now provide "good" entropy but no answer
fakeEntropy = strings.Repeat(":)", 40) + "\n" // entropy + accept count fakeEntropy = strings.Repeat(":)", 40) + "\n" // entropy + accept count
cleanUp3 := client.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy))) cleanUp3 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp3() defer cleanUp3()
err = runMnemonicCmd(cmdUser, []string{}) err = runMnemonicCmd(cmdUser, []string{})
require.Error(t, err) require.Error(t, err)
// Now provide "good" entropy but say no // Now provide "good" entropy but say no
fakeEntropy = strings.Repeat(":)", 40) + "\nn\n" // entropy + accept count fakeEntropy = strings.Repeat(":)", 40) + "\nn\n" // entropy + accept count
cleanUp4 := client.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy))) cleanUp4 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp4() defer cleanUp4()
err = runMnemonicCmd(cmdUser, []string{}) err = runMnemonicCmd(cmdUser, []string{})
require.NoError(t, err) require.NoError(t, err)

View File

@ -8,10 +8,11 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/bech32" "github.com/tendermint/tendermint/libs/bech32"
"github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
) )
@ -74,7 +75,7 @@ hexadecimal into bech32 cosmos prefixed format and vice versa.
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
RunE: parseKey, RunE: parseKey,
} }
cmd.Flags().Bool(client.FlagIndentResponse, false, "Indent JSON output") cmd.Flags().Bool(flags.FlagIndentResponse, false, "Indent JSON output")
return cmd return cmd
} }
@ -119,7 +120,7 @@ func displayParseKeyInfo(stringer fmt.Stringer) {
var out []byte var out []byte
var err error var err error
if viper.GetBool(client.FlagIndentResponse) { if viper.GetBool(flags.FlagIndentResponse) {
out, err = cdc.MarshalJSONIndent(stringer, "", " ") out, err = cdc.MarshalJSONIndent(stringer, "", " ")
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -3,7 +3,7 @@ package keys
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
) )
// Commands registers a sub-tree of commands to interact with // Commands registers a sub-tree of commands to interact with
@ -23,7 +23,7 @@ func Commands() *cobra.Command {
addKeyCommand(), addKeyCommand(),
listKeysCmd(), listKeysCmd(),
showKeysCmd(), showKeysCmd(),
client.LineBreak, flags.LineBreak,
deleteKeyCommand(), deleteKeyCommand(),
updateKeyCommand(), updateKeyCommand(),
parseKeyStringCommand(), parseKeyStringCommand(),

View File

@ -4,18 +4,17 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
tmcrypto "github.com/tendermint/tendermint/crypto" tmcrypto "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/multisig"
"github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
) )
const ( const (
@ -51,7 +50,7 @@ consisting of all the keys provided by name and multisig threshold.`,
cmd.Flags().BoolP(FlagDevice, "d", false, "Output the address in a ledger device") cmd.Flags().BoolP(FlagDevice, "d", false, "Output the address in a ledger device")
cmd.Flags().Uint(flagMultiSigThreshold, 1, "K out of N required signatures") cmd.Flags().Uint(flagMultiSigThreshold, 1, "K out of N required signatures")
cmd.Flags().BoolP(flagShowMultiSig, "m", false, "Output multisig pubkey constituents, threshold, and weights") cmd.Flags().BoolP(flagShowMultiSig, "m", false, "Output multisig pubkey constituents, threshold, and weights")
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response") cmd.Flags().Bool(flags.FlagIndentResponse, false, "Add indent to JSON response")
return cmd return cmd
} }

View File

@ -3,17 +3,17 @@ package keys
import ( import (
"testing" "testing"
"github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/multisig"
"github.com/tendermint/tendermint/crypto/secp256k1" "github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
) )
func Test_multiSigKey_Properties(t *testing.T) { func Test_multiSigKey_Properties(t *testing.T) {
@ -47,7 +47,7 @@ func Test_runShowCmd(t *testing.T) {
// Now add a temporary keybase // Now add a temporary keybase
kbHome, cleanUp := tests.NewTestCaseDir(t) kbHome, cleanUp := tests.NewTestCaseDir(t)
defer cleanUp() defer cleanUp()
viper.Set(cli.HomeFlag, kbHome) viper.Set(flags.FlagHome, kbHome)
fakeKeyName1 := "runShowCmd_Key1" fakeKeyName1 := "runShowCmd_Key1"
fakeKeyName2 := "runShowCmd_Key2" fakeKeyName2 := "runShowCmd_Key2"

View File

@ -3,8 +3,7 @@ package keys
import ( import (
"fmt" "fmt"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/input"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -21,19 +20,19 @@ func updateKeyCommand() *cobra.Command {
func runUpdateCmd(cmd *cobra.Command, args []string) error { func runUpdateCmd(cmd *cobra.Command, args []string) error {
name := args[0] name := args[0]
buf := client.BufferStdin() buf := input.BufferStdin()
kb, err := NewKeyBaseFromHomeFlag() kb, err := NewKeyBaseFromHomeFlag()
if err != nil { if err != nil {
return err return err
} }
oldpass, err := client.GetPassword( oldpass, err := input.GetPassword(
"Enter the current passphrase:", buf) "Enter the current passphrase:", buf)
if err != nil { if err != nil {
return err return err
} }
getNewpass := func() (string, error) { getNewpass := func() (string, error) {
return client.GetCheckPassword( return input.GetCheckPassword(
"Enter the new passphrase:", "Enter the new passphrase:",
"Repeat the new passphrase:", buf) "Repeat the new passphrase:", buf)
} }

View File

@ -5,14 +5,12 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/cosmos/cosmos-sdk/client"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
) )
func Test_updateKeyCommand(t *testing.T) { func Test_updateKeyCommand(t *testing.T) {
@ -31,7 +29,7 @@ func Test_runUpdateCmd(t *testing.T) {
err := runUpdateCmd(cmd, []string{fakeKeyName1}) err := runUpdateCmd(cmd, []string{fakeKeyName1})
assert.EqualError(t, err, "EOF") assert.EqualError(t, err, "EOF")
cleanUp := client.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\n"))) cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\n")))
defer cleanUp() defer cleanUp()
// try again // try again
@ -42,7 +40,7 @@ func Test_runUpdateCmd(t *testing.T) {
// Now add a temporary keybase // Now add a temporary keybase
kbHome, cleanUp1 := tests.NewTestCaseDir(t) kbHome, cleanUp1 := tests.NewTestCaseDir(t)
defer cleanUp1() defer cleanUp1()
viper.Set(cli.HomeFlag, kbHome) viper.Set(flags.FlagHome, kbHome)
kb, err := NewKeyBaseFromHomeFlag() kb, err := NewKeyBaseFromHomeFlag()
assert.NoError(t, err) assert.NoError(t, err)
@ -52,7 +50,7 @@ func Test_runUpdateCmd(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
// Try again now that we have keys // Try again now that we have keys
cleanUp2 := client.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\nNew1234\nNew1234"))) cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\nNew1234\nNew1234")))
defer cleanUp2() defer cleanUp2()
// Incorrect key type // Incorrect key type

View File

@ -9,7 +9,8 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/crypto/keys"
) )
@ -62,10 +63,10 @@ func GetPassphrase(name string) (string, error) {
// ReadPassphraseFromStdin attempts to read a passphrase from STDIN return an // ReadPassphraseFromStdin attempts to read a passphrase from STDIN return an
// error upon failure. // error upon failure.
func ReadPassphraseFromStdin(name string) (string, error) { func ReadPassphraseFromStdin(name string) (string, error) {
buf := client.BufferStdin() buf := input.BufferStdin()
prompt := fmt.Sprintf("Password to sign with '%s':", name) prompt := fmt.Sprintf("Password to sign with '%s':", name)
passphrase, err := client.GetPassword(prompt, buf) passphrase, err := input.GetPassword(prompt, buf)
if err != nil { if err != nil {
return passphrase, fmt.Errorf("Error reading passphrase: %v", err) return passphrase, fmt.Errorf("Error reading passphrase: %v", err)
} }
@ -75,7 +76,7 @@ func ReadPassphraseFromStdin(name string) (string, error) {
// NewKeyBaseFromHomeFlag initializes a Keybase based on the configuration. // NewKeyBaseFromHomeFlag initializes a Keybase based on the configuration.
func NewKeyBaseFromHomeFlag() (keys.Keybase, error) { func NewKeyBaseFromHomeFlag() (keys.Keybase, error) {
rootDir := viper.GetString(cli.HomeFlag) rootDir := viper.GetString(flags.FlagHome)
return NewKeyBaseFromDir(rootDir) return NewKeyBaseFromDir(rootDir)
} }
@ -120,7 +121,7 @@ func printKeyInfo(keyInfo keys.Info, bechKeyOut bechKeyOutFn) {
case OutputFormatJSON: case OutputFormatJSON:
var out []byte var out []byte
var err error var err error
if viper.GetBool(client.FlagIndentResponse) { if viper.GetBool(flags.FlagIndentResponse) {
out, err = cdc.MarshalJSONIndent(ko, "", " ") out, err = cdc.MarshalJSONIndent(ko, "", " ")
} else { } else {
out, err = cdc.MarshalJSON(ko) out, err = cdc.MarshalJSON(ko)
@ -147,7 +148,7 @@ func printInfos(infos []keys.Info) {
var out []byte var out []byte
var err error var err error
if viper.GetBool(client.FlagIndentResponse) { if viper.GetBool(flags.FlagIndentResponse) {
out, err = cdc.MarshalJSONIndent(kos, "", " ") out, err = cdc.MarshalJSONIndent(kos, "", " ")
} else { } else {
out, err = cdc.MarshalJSON(kos) out, err = cdc.MarshalJSON(kos)

View File

@ -12,8 +12,8 @@ import (
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
rpcserver "github.com/tendermint/tendermint/rpc/lib/server" rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
keybase "github.com/cosmos/cosmos-sdk/crypto/keys" keybase "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
@ -65,7 +65,7 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi
rs.log.Info( rs.log.Info(
fmt.Sprintf( fmt.Sprintf(
"Starting application REST service (chain-id: %q)...", "Starting application REST service (chain-id: %q)...",
viper.GetString(client.FlagChainID), viper.GetString(flags.FlagChainID),
), ),
) )
@ -86,15 +86,15 @@ func ServeCommand(cdc *codec.Codec, registerRoutesFn func(*RestServer)) *cobra.C
// Start the rest server and return error if one exists // Start the rest server and return error if one exists
err = rs.Start( err = rs.Start(
viper.GetString(client.FlagListenAddr), viper.GetString(flags.FlagListenAddr),
viper.GetInt(client.FlagMaxOpenConnections), viper.GetInt(flags.FlagMaxOpenConnections),
uint(viper.GetInt(client.FlagRPCReadTimeout)), uint(viper.GetInt(flags.FlagRPCReadTimeout)),
uint(viper.GetInt(client.FlagRPCWriteTimeout)), uint(viper.GetInt(flags.FlagRPCWriteTimeout)),
) )
return err return err
}, },
} }
return client.RegisterRestServerFlags(cmd) return flags.RegisterRestServerFlags(cmd)
} }

5
client/rest/errors.go Normal file
View File

@ -0,0 +1,5 @@
package rest
import "errors"
var errInvalidGasAdjustment = errors.New("invalid gas adjustment")

View File

@ -4,8 +4,8 @@ import (
"log" "log"
"net/http" "net/http"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -21,12 +21,12 @@ import (
func WriteGenerateStdTxResponse(w http.ResponseWriter, cdc *codec.Codec, func WriteGenerateStdTxResponse(w http.ResponseWriter, cdc *codec.Codec,
cliCtx context.CLIContext, br rest.BaseReq, msgs []sdk.Msg) { cliCtx context.CLIContext, br rest.BaseReq, msgs []sdk.Msg) {
gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(w, br.GasAdjustment, client.DefaultGasAdjustment) gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(w, br.GasAdjustment, flags.DefaultGasAdjustment)
if !ok { if !ok {
return return
} }
simAndExec, gas, err := client.ParseGas(br.Gas) simAndExec, gas, err := flags.ParseGas(br.Gas)
if err != nil { if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return return
@ -39,7 +39,7 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cdc *codec.Codec,
if br.Simulate || simAndExec { if br.Simulate || simAndExec {
if gasAdj < 0 { if gasAdj < 0 {
rest.WriteErrorResponse(w, http.StatusBadRequest, client.ErrInvalidGasAdjustment.Error()) rest.WriteErrorResponse(w, http.StatusBadRequest, errInvalidGasAdjustment.Error())
return return
} }

View File

@ -9,8 +9,9 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
tmliteProxy "github.com/tendermint/tendermint/lite/proxy" tmliteProxy "github.com/tendermint/tendermint/lite/proxy"
@ -24,10 +25,10 @@ func BlockCommand() *cobra.Command {
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
RunE: printBlock, RunE: printBlock,
} }
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode))
cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode)) viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode))
return cmd return cmd
} }
@ -64,9 +65,9 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
} }
if cliCtx.Indent { if cliCtx.Indent {
return cdc.MarshalJSONIndent(res, "", " ") return codec.Cdc.MarshalJSONIndent(res, "", " ")
} }
return cdc.MarshalJSON(res) return codec.Cdc.MarshalJSON(res)
} }
// get the current blockchain height // get the current blockchain height
@ -130,7 +131,7 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return return
} }
rest.PostProcessResponse(w, cdc, output, cliCtx.Indent) rest.PostProcessResponse(w, codec.Cdc, output, cliCtx.Indent)
} }
} }
@ -143,6 +144,6 @@ func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return return
} }
rest.PostProcessResponse(w, cdc, output, cliCtx.Indent) rest.PostProcessResponse(w, codec.Cdc, output, cliCtx.Indent)
} }
} }

View File

@ -1,12 +0,0 @@
package rpc
import (
amino "github.com/tendermint/go-amino"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
)
var cdc = amino.NewCodec()
func init() {
ctypes.RegisterAmino(cdc)
}

View File

@ -13,7 +13,7 @@ import (
) )
// Register REST endpoints // Register REST endpoints
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { func RegisterRPCRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET") r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET")
r.HandleFunc("/node_version", NodeVersionRequestHandler(cliCtx)).Methods("GET") r.HandleFunc("/node_version", NodeVersionRequestHandler(cliCtx)).Methods("GET")
r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(cliCtx)).Methods("GET")

View File

@ -11,8 +11,9 @@ import (
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
) )
@ -24,9 +25,9 @@ func StatusCommand() *cobra.Command {
RunE: printNodeStatus, RunE: printNodeStatus,
} }
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode))
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response") cmd.Flags().Bool(flags.FlagIndentResponse, false, "Add indent to JSON response")
return cmd return cmd
} }
@ -44,7 +45,7 @@ func getNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) {
func printNodeStatus(cmd *cobra.Command, args []string) error { func printNodeStatus(cmd *cobra.Command, args []string) error {
// No need to verify proof in getting node status // No need to verify proof in getting node status
viper.Set(client.FlagTrustNode, true) viper.Set(flags.FlagTrustNode, true)
cliCtx := context.NewCLIContext() cliCtx := context.NewCLIContext()
status, err := getNodeStatus(cliCtx) status, err := getNodeStatus(cliCtx)
if err != nil { if err != nil {
@ -53,9 +54,9 @@ func printNodeStatus(cmd *cobra.Command, args []string) error {
var output []byte var output []byte
if cliCtx.Indent { if cliCtx.Indent {
output, err = cdc.MarshalJSONIndent(status, "", " ") output, err = codec.Cdc.MarshalJSONIndent(status, "", " ")
} else { } else {
output, err = cdc.MarshalJSON(status) output, err = codec.Cdc.MarshalJSON(status)
} }
if err != nil { if err != nil {
return err return err
@ -77,7 +78,7 @@ func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
} }
nodeInfo := status.NodeInfo nodeInfo := status.NodeInfo
rest.PostProcessResponse(w, cdc, nodeInfo, cliCtx.Indent) rest.PostProcessResponse(w, codec.Cdc, nodeInfo, cliCtx.Indent)
} }
} }

View File

@ -13,8 +13,8 @@ import (
tmtypes "github.com/tendermint/tendermint/types" tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
@ -54,12 +54,12 @@ func ValidatorCommand(cdc *codec.Codec) *cobra.Command {
}, },
} }
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode))
cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode)) viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode))
cmd.Flags().Bool(client.FlagIndentResponse, false, "indent JSON response") cmd.Flags().Bool(flags.FlagIndentResponse, false, "indent JSON response")
viper.BindPFlag(client.FlagIndentResponse, cmd.Flags().Lookup(client.FlagIndentResponse)) viper.BindPFlag(flags.FlagIndentResponse, cmd.Flags().Lookup(flags.FlagIndentResponse))
return cmd return cmd
} }
@ -113,6 +113,7 @@ func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error
}, nil }, nil
} }
// GetValidators from client
func GetValidators(cliCtx context.CLIContext, height *int64) (ResultValidatorsOutput, error) { func GetValidators(cliCtx context.CLIContext, height *int64) (ResultValidatorsOutput, error) {
// get the node // get the node
node, err := cliCtx.GetNode() node, err := cliCtx.GetNode()
@ -175,7 +176,7 @@ func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return return
} }
rest.PostProcessResponse(w, cdc, output, cliCtx.Indent) rest.PostProcessResponse(w, codec.Cdc, output, cliCtx.Indent)
} }
} }
@ -188,6 +189,6 @@ func LatestValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerF
return return
} }
rest.PostProcessResponse(w, cdc, output, cliCtx.Indent) rest.PostProcessResponse(w, codec.Cdc, output, cliCtx.Indent)
} }
} }

View File

@ -7,13 +7,13 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"io/ioutil" "io/ioutil"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
) )
@ -92,5 +92,5 @@ $ <appcli> tx broadcast ./mytxn.json
}, },
} }
return client.PostCommands(cmd)[0] return flags.PostCommands(cmd)[0]
} }

View File

@ -8,8 +8,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
amino "github.com/tendermint/go-amino" amino "github.com/tendermint/go-amino"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
@ -101,5 +101,5 @@ If you supply a dash (-) argument in place of an input filename, the command rea
}, },
} }
return client.PostCommands(cmd)[0] return flags.PostCommands(cmd)[0]
} }

View File

@ -11,8 +11,8 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
@ -92,10 +92,10 @@ $ <appcli> query txs --tags '<tag1>:<value1>&<tag2>:<value2>' --page 1 --limit 3
}, },
} }
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode))
cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode)) viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode))
cmd.Flags().String(flagTags, "", "tag:value list of tags that must match") cmd.Flags().String(flagTags, "", "tag:value list of tags that must match")
cmd.Flags().Uint32(flagPage, rest.DefaultPage, "Query a specific page of paginated results") cmd.Flags().Uint32(flagPage, rest.DefaultPage, "Query a specific page of paginated results")
@ -127,10 +127,10 @@ func QueryTxCmd(cdc *codec.Codec) *cobra.Command {
}, },
} }
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode))
cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") cmd.Flags().Bool(flags.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode)) viper.BindPFlag(flags.FlagTrustNode, cmd.Flags().Lookup(flags.FlagTrustNode))
return cmd return cmd
} }

View File

@ -8,7 +8,7 @@ import (
) )
// register REST routes // register REST routes
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { func RegisterTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) {
r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cdc, cliCtx)).Methods("GET") r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cdc, cliCtx)).Methods("GET")
r.HandleFunc("/txs", QueryTxsByTagsRequestHandlerFn(cliCtx, cdc)).Methods("GET") r.HandleFunc("/txs", QueryTxsByTagsRequestHandlerFn(cliCtx, cdc)).Methods("GET")
r.HandleFunc("/txs", BroadcastTxRequest(cliCtx, cdc)).Methods("POST") r.HandleFunc("/txs", BroadcastTxRequest(cliCtx, cdc)).Methods("POST")

5
client/utils/errors.go Normal file
View File

@ -0,0 +1,5 @@
package utils
import "errors"
var errInvalidSigner = errors.New("tx intended signer does not match the given signer")

View File

@ -9,14 +9,13 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/common"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
@ -77,7 +76,7 @@ func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIConte
} }
var json []byte var json []byte
if viper.GetBool(client.FlagIndentResponse) { if viper.GetBool(flags.FlagIndentResponse) {
json, err = cliCtx.Codec.MarshalJSONIndent(stdSignMsg, "", " ") json, err = cliCtx.Codec.MarshalJSONIndent(stdSignMsg, "", " ")
if err != nil { if err != nil {
panic(err) panic(err)
@ -88,8 +87,8 @@ func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIConte
fmt.Fprintf(os.Stderr, "%s\n\n", json) fmt.Fprintf(os.Stderr, "%s\n\n", json)
buf := client.BufferStdin() buf := input.BufferStdin()
ok, err := client.GetConfirmation("confirm transaction before signing and broadcasting", buf) ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf)
if err != nil || !ok { if err != nil || !ok {
fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction") fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction")
return err return err
@ -129,7 +128,7 @@ func EnrichWithGas(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []s
// CalculateGas simulates the execution of a transaction and returns // CalculateGas simulates the execution of a transaction and returns
// both the estimate obtained by the query and the adjusted amount. // both the estimate obtained by the query and the adjusted amount.
func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error), func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error),
cdc *amino.Codec, txBytes []byte, adjustment float64) (estimate, adjusted uint64, err error) { cdc *codec.Codec, txBytes []byte, adjustment float64) (estimate, adjusted uint64, err error) {
// run a simulation (via /app/simulate query) to // run a simulation (via /app/simulate query) to
// estimate gas and update TxBuilder accordingly // estimate gas and update TxBuilder accordingly
@ -180,7 +179,7 @@ func SignStdTx(
// check whether the address is a signer // check whether the address is a signer
if !isTxSigner(sdk.AccAddress(addr), stdTx.GetSigners()) { if !isTxSigner(sdk.AccAddress(addr), stdTx.GetSigners()) {
return signedStdTx, fmt.Errorf("%s: %s", client.ErrInvalidSigner, name) return signedStdTx, fmt.Errorf("%s: %s", errInvalidSigner, name)
} }
if !offline { if !offline {
@ -207,7 +206,7 @@ func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLICont
// check whether the address is a signer // check whether the address is a signer
if !isTxSigner(addr, stdTx.GetSigners()) { if !isTxSigner(addr, stdTx.GetSigners()) {
return signedStdTx, fmt.Errorf("%s: %s", client.ErrInvalidSigner, name) return signedStdTx, fmt.Errorf("%s: %s", errInvalidSigner, name)
} }
if !offline { if !offline {
@ -226,7 +225,7 @@ func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLICont
} }
// Read and decode a StdTx from the given filename. Can pass "-" to read from stdin. // Read and decode a StdTx from the given filename. Can pass "-" to read from stdin.
func ReadStdTxFromFile(cdc *amino.Codec, filename string) (stdTx auth.StdTx, err error) { func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx auth.StdTx, err error) {
var bytes []byte var bytes []byte
if filename == "-" { if filename == "-" {
bytes, err = ioutil.ReadAll(os.Stdin) bytes, err = ioutil.ReadAll(os.Stdin)
@ -284,7 +283,7 @@ func adjustGasEstimate(estimate uint64, adjustment float64) uint64 {
return uint64(adjustment * float64(estimate)) return uint64(adjustment * float64(estimate))
} }
func parseQueryResponse(cdc *amino.Codec, rawRes []byte) (uint64, error) { func parseQueryResponse(cdc *codec.Codec, rawRes []byte) (uint64, error) {
var simulationResult sdk.Result var simulationResult sdk.Result
if err := cdc.UnmarshalBinaryLengthPrefixed(rawRes, &simulationResult); err != nil { if err := cdc.UnmarshalBinaryLengthPrefixed(rawRes, &simulationResult); err != nil {
return 0, err return 0, err

View File

@ -15,13 +15,6 @@ import (
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/crisis"
"github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/gov"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking"
) )
var ( var (
@ -77,7 +70,7 @@ func TestCalculateGas(t *testing.T) {
} }
func TestDefaultTxEncoder(t *testing.T) { func TestDefaultTxEncoder(t *testing.T) {
cdc := makeTestCodec() cdc := makeCodec()
defaultEncoder := auth.DefaultTxEncoder(cdc) defaultEncoder := auth.DefaultTxEncoder(cdc)
encoder := GetTxEncoder(cdc) encoder := GetTxEncoder(cdc)
@ -86,7 +79,7 @@ func TestDefaultTxEncoder(t *testing.T) {
} }
func TestConfiguredTxEncoder(t *testing.T) { func TestConfiguredTxEncoder(t *testing.T) {
cdc := makeTestCodec() cdc := makeCodec()
customEncoder := func(tx sdk.Tx) ([]byte, error) { customEncoder := func(tx sdk.Tx) ([]byte, error) {
return json.Marshal(tx) return json.Marshal(tx)
@ -144,21 +137,9 @@ func writeToNewTempFile(t *testing.T, data string) *os.File {
func makeCodec() *codec.Codec { func makeCodec() *codec.Codec {
var cdc = codec.New() var cdc = codec.New()
bank.RegisterCodec(cdc)
staking.RegisterCodec(cdc)
distribution.RegisterCodec(cdc)
slashing.RegisterCodec(cdc)
params.RegisterCodec(cdc)
gov.RegisterCodec(cdc)
auth.RegisterCodec(cdc)
crisis.RegisterCodec(cdc)
sdk.RegisterCodec(cdc) sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc) codec.RegisterCrypto(cdc)
return cdc auth.RegisterCodec(cdc)
}
func makeTestCodec() *codec.Codec {
cdc := makeCodec()
cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil)
return cdc return cdc
} }

View File

@ -12,8 +12,7 @@ import (
type Codec = amino.Codec type Codec = amino.Codec
func New() *Codec { func New() *Codec {
cdc := amino.NewCodec() return amino.NewCodec()
return cdc
} }
// Register the go-crypto to the codec // Register the go-crypto to the codec

8
go.mod
View File

@ -1,6 +1,8 @@
module github.com/cosmos/cosmos-sdk module github.com/cosmos/cosmos-sdk
require ( require (
github.com/Masterminds/glide v0.13.2
github.com/Masterminds/vcs v1.13.0 // indirect
github.com/VividCortex/gohistogram v1.0.0 // indirect github.com/VividCortex/gohistogram v1.0.0 // indirect
github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d
github.com/bgentry/speakeasy v0.1.0 github.com/bgentry/speakeasy v0.1.0
@ -20,6 +22,7 @@ require (
github.com/magiconair/properties v1.8.0 // indirect github.com/magiconair/properties v1.8.0 // indirect
github.com/mattn/go-isatty v0.0.6 github.com/mattn/go-isatty v0.0.6
github.com/mattn/go-runewidth v0.0.4 // indirect github.com/mattn/go-runewidth v0.0.4 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/olekukonko/tablewriter v0.0.1 github.com/olekukonko/tablewriter v0.0.1
github.com/pelletier/go-toml v1.2.0 github.com/pelletier/go-toml v1.2.0
@ -39,9 +42,14 @@ require (
github.com/stretchr/testify v1.3.0 github.com/stretchr/testify v1.3.0
github.com/syndtr/goleveldb v0.0.0-20180708030551-c4c61651e9e3 // indirect github.com/syndtr/goleveldb v0.0.0-20180708030551-c4c61651e9e3 // indirect
github.com/tendermint/btcd v0.1.1 github.com/tendermint/btcd v0.1.1
github.com/tendermint/ed25519 v0.0.0-20171027050219-d8387025d2b9 // indirect
github.com/tendermint/go-amino v0.15.0 github.com/tendermint/go-amino v0.15.0
github.com/tendermint/go-crypto v0.9.0
github.com/tendermint/iavl v0.12.2 github.com/tendermint/iavl v0.12.2
github.com/tendermint/tendermint v0.31.5 github.com/tendermint/tendermint v0.31.5
github.com/tendermint/tmlibs v0.9.0 // indirect
github.com/zondax/ledger-go v0.9.0 // indirect
github.com/zondax/ledger-goclient v0.9.9 // indirect
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
google.golang.org/grpc v1.19.0 // indirect google.golang.org/grpc v1.19.0 // indirect
gopkg.in/yaml.v2 v2.2.2 // indirect gopkg.in/yaml.v2 v2.2.2 // indirect

16
go.sum
View File

@ -1,6 +1,10 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Masterminds/glide v0.13.2 h1:M5MOH04TyRiMBVeWHbifqTpnauxWINIubTCOkhXh+2g=
github.com/Masterminds/glide v0.13.2/go.mod h1:STyF5vcenH/rUqTEv+/hBXlSTo7KYwg2oc2f4tzPWic=
github.com/Masterminds/vcs v1.13.0 h1:USF5TvZGYgIpcbNAEMLfFhHqP08tFZVlUVrmTSpqnyA=
github.com/Masterminds/vcs v1.13.0/go.mod h1:N09YCmOQr6RLxC6UNHzuVwAdodYbbnycGHSmwVJjcKA=
github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE=
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
@ -85,6 +89,8 @@ github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
@ -145,14 +151,24 @@ github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s
github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U=
github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5 h1:u8i49c+BxloX3XQ55cvzFNXplizZP/q00i+IlttUjAU= github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5 h1:u8i49c+BxloX3XQ55cvzFNXplizZP/q00i+IlttUjAU=
github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk=
github.com/tendermint/ed25519 v0.0.0-20171027050219-d8387025d2b9 h1:zccWau0P8FELSb4HTDJ88hRo+WVNMbIbg27rFqDrhCE=
github.com/tendermint/ed25519 v0.0.0-20171027050219-d8387025d2b9/go.mod h1:nt45hbhDkWVdMBkr2TOgOzCrpBccXdN09WOiOYTHVEk=
github.com/tendermint/go-amino v0.15.0 h1:TC4e66P59W7ML9+bxio17CPKnxW3nKIRAYskntMAoRk= github.com/tendermint/go-amino v0.15.0 h1:TC4e66P59W7ML9+bxio17CPKnxW3nKIRAYskntMAoRk=
github.com/tendermint/go-amino v0.15.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tendermint/go-amino v0.15.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME=
github.com/tendermint/go-crypto v0.9.0 h1:knZL34Ccy6BDjsPXwBslVTtyUpvOVAGbZMHcQriXulM=
github.com/tendermint/go-crypto v0.9.0/go.mod h1:bL+jG0FvO892QRYHtA/lEIQSMMq7anlRPTGbsWzQntU=
github.com/tendermint/iavl v0.12.2 h1:Ls5p5VINCM1HRT9g5Vvs2zmDOCU/CCIvIHzd/pZ8P0E= github.com/tendermint/iavl v0.12.2 h1:Ls5p5VINCM1HRT9g5Vvs2zmDOCU/CCIvIHzd/pZ8P0E=
github.com/tendermint/iavl v0.12.2/go.mod h1:EoKMMv++tDOL5qKKVnoIqtVPshRrEPeJ0WsgDOLAauM= github.com/tendermint/iavl v0.12.2/go.mod h1:EoKMMv++tDOL5qKKVnoIqtVPshRrEPeJ0WsgDOLAauM=
github.com/tendermint/tendermint v0.31.5 h1:vTet8tCq3B9/J9Yo11dNZ8pOB7NtSy++bVSfkP4KzR4= github.com/tendermint/tendermint v0.31.5 h1:vTet8tCq3B9/J9Yo11dNZ8pOB7NtSy++bVSfkP4KzR4=
github.com/tendermint/tendermint v0.31.5/go.mod h1:ymcPyWblXCplCPQjbOYbrF1fWnpslATMVqiGgWbZrlc= github.com/tendermint/tendermint v0.31.5/go.mod h1:ymcPyWblXCplCPQjbOYbrF1fWnpslATMVqiGgWbZrlc=
github.com/tendermint/tmlibs v0.9.0 h1:3aU/D2v3aecqpODOuBXCfi950bHTefD5Pps5X3XuJDc=
github.com/tendermint/tmlibs v0.9.0/go.mod h1:4L0tAKpLTioy14VnmbXYTLIJN0pCMiehxDMdN6zZfM8=
github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8=
github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM=
github.com/zondax/ledger-go v0.9.0 h1:oTrtFqPFA4VdCPRvqMaN45mQnJxkPc0JxoVZfCoUpjI=
github.com/zondax/ledger-go v0.9.0/go.mod h1:b2vIcu3u9gJoIx4kTWuXOgzGV7FPWeUktqRqVf6feG0=
github.com/zondax/ledger-goclient v0.9.9 h1:XBvqkjluVda8dTYwPh2DPnlSGVEeoH1a1OprEAn8C98=
github.com/zondax/ledger-goclient v0.9.9/go.mod h1:ILyu7qO5zsod0bzyxY9NCMlFTb8AXZzJAJf0T85b2jA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=

View File

@ -11,10 +11,10 @@ import (
"io/ioutil" "io/ioutil"
"github.com/tendermint/tendermint/libs/cli"
dbm "github.com/tendermint/tendermint/libs/db" dbm "github.com/tendermint/tendermint/libs/db"
tmtypes "github.com/tendermint/tendermint/types" tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
) )
@ -31,7 +31,7 @@ func ExportCmd(ctx *Context, cdc *codec.Codec, appExporter AppExporter) *cobra.C
Short: "Export state to JSON", Short: "Export state to JSON",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
config := ctx.Config config := ctx.Config
config.SetRoot(viper.GetString(cli.HomeFlag)) config.SetRoot(viper.GetString(flags.FlagHome))
traceWriterFile := viper.GetString(flagTraceStore) traceWriterFile := viper.GetString(flagTraceStore)

View File

@ -7,11 +7,10 @@ import (
"os" "os"
"testing" "testing"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/cli"
) )
// Get a free address for a test tendermint server // Get a free address for a test tendermint server
@ -43,8 +42,8 @@ func FreeTCPAddr() (addr, port string, err error) {
func SetupViper(t *testing.T) func() { func SetupViper(t *testing.T) func() {
rootDir, err := ioutil.TempDir("", "mock-sdk-cmd") rootDir, err := ioutil.TempDir("", "mock-sdk-cmd")
require.Nil(t, err) require.Nil(t, err)
viper.Set(cli.HomeFlag, rootDir) viper.Set(flags.FlagHome, rootDir)
viper.Set(client.FlagName, "moniker") viper.Set(flags.FlagName, "moniker")
return func() { return func() {
err := os.RemoveAll(rootDir) err := os.RemoveAll(rootDir)
if err != nil { if err != nil {

View File

@ -21,7 +21,7 @@ import (
"github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/log"
pvm "github.com/tendermint/tendermint/privval" pvm "github.com/tendermint/tendermint/privval"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/server/config"
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
@ -148,10 +148,10 @@ func AddCommands(
rootCmd.AddCommand( rootCmd.AddCommand(
StartCmd(ctx, appCreator), StartCmd(ctx, appCreator),
UnsafeResetAllCmd(ctx), UnsafeResetAllCmd(ctx),
client.LineBreak, flags.LineBreak,
tendermintCmd, tendermintCmd,
ExportCmd(ctx, cdc, appExport), ExportCmd(ctx, cdc, appExport),
client.LineBreak, flags.LineBreak,
version.Cmd, version.Cmd,
) )
} }

View File

@ -1,19 +1,17 @@
package context package context
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/keys"
crkeys "github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"errors"
"github.com/spf13/viper"
) )
// TxBuilder implements a transaction context created in SDK modules. // TxBuilder implements a transaction context created in SDK modules.
@ -61,17 +59,17 @@ func NewTxBuilderFromCLI() TxBuilder {
} }
txbldr := TxBuilder{ txbldr := TxBuilder{
keybase: kb, keybase: kb,
accountNumber: uint64(viper.GetInt64(client.FlagAccountNumber)), accountNumber: uint64(viper.GetInt64(flags.FlagAccountNumber)),
sequence: uint64(viper.GetInt64(client.FlagSequence)), sequence: uint64(viper.GetInt64(flags.FlagSequence)),
gas: client.GasFlagVar.Gas, gas: flags.GasFlagVar.Gas,
gasAdjustment: viper.GetFloat64(client.FlagGasAdjustment), gasAdjustment: viper.GetFloat64(flags.FlagGasAdjustment),
simulateAndExecute: client.GasFlagVar.Simulate, simulateAndExecute: flags.GasFlagVar.Simulate,
chainID: viper.GetString(client.FlagChainID), chainID: viper.GetString(flags.FlagChainID),
memo: viper.GetString(client.FlagMemo), memo: viper.GetString(flags.FlagMemo),
} }
txbldr = txbldr.WithFees(viper.GetString(client.FlagFees)) txbldr = txbldr.WithFees(viper.GetString(flags.FlagFees))
txbldr = txbldr.WithGasPrices(viper.GetString(client.FlagGasPrices)) txbldr = txbldr.WithGasPrices(viper.GetString(flags.FlagGasPrices))
return txbldr return txbldr
} }

View File

@ -10,76 +10,70 @@ import (
"path/filepath" "path/filepath"
"github.com/spf13/cobra" "github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/spf13/viper" "github.com/spf13/viper"
cfg "github.com/tendermint/tendermint/config" cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/common"
tmtypes "github.com/tendermint/tendermint/types" tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
kbkeys "github.com/cosmos/cosmos-sdk/crypto/keys" kbkeys "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
) )
var ( // helpers for message building gen-tx command
defaultTokens = sdk.TokensFromTendermintPower(100) type StakingMsgBuildingHelpers interface {
defaultAmount = defaultTokens.String() + sdk.DefaultBondDenom CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string)
defaultCommissionRate = "0.1" PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey)
defaultCommissionMaxRate = "0.2" BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error)
defaultCommissionMaxChangeRate = "0.01" }
defaultMinSelfDelegation = "1"
)
// GenTxCmd builds the application's gentx command. // GenTxCmd builds the application's gentx command.
// nolint: errcheck // nolint: errcheck
func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, smbh StakingMsgBuildingHelpers,
genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command {
ipDefault, _ := server.ExternalIP()
fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault)
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "gentx", Use: "gentx",
Short: "Generate a genesis tx carrying a self delegation", Short: "Generate a genesis tx carrying a self delegation",
Args: cobra.NoArgs, Args: cobra.NoArgs,
Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'. Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'.
It creates a genesis piece carrying a self delegation with the It creates a genesis transaction to create a validator.
following delegation and commission default parameters: The following default parameters are included:
%s`, defaultsDesc),
delegation amount: %s
commission rate: %s
commission max rate: %s
commission max change rate: %s
minimum self delegation: %s
`, defaultAmount, defaultCommissionRate, defaultCommissionMaxRate, defaultCommissionMaxChangeRate, defaultMinSelfDelegation),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
config := ctx.Config config := ctx.Config
config.SetRoot(viper.GetString(tmcli.HomeFlag)) config.SetRoot(viper.GetString(client.FlagHome))
nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config)
if err != nil { if err != nil {
return err return err
} }
// Read --nodeID, if empty take it from priv_validator.json // Read --nodeID, if empty take it from priv_validator.json
if nodeIDString := viper.GetString(cli.FlagNodeID); nodeIDString != "" { if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" {
nodeID = nodeIDString nodeID = nodeIDString
} }
// Read --pubkey, if empty take it from priv_validator.json
ip := viper.GetString(cli.FlagIP) if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" {
if ip == "" { valPubKey, err = sdk.GetConsPubKeyBech32(valPubKeyString)
fmt.Fprintf(os.Stderr, "couldn't retrieve an external IP; "+ if err != nil {
"the tx's memo field will be unset") return err
}
} }
genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile()) genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile())
@ -96,7 +90,7 @@ following delegation and commission default parameters:
return err return err
} }
kb, err := keys.NewKeyBaseFromDir(viper.GetString(flagClientHome)) kb, err := client.NewKeyBaseFromDir(viper.GetString(flagClientHome))
if err != nil { if err != nil {
return err return err
} }
@ -107,23 +101,12 @@ following delegation and commission default parameters:
return err return err
} }
// Read --pubkey, if empty take it from priv_validator.json
if valPubKeyString := viper.GetString(cli.FlagPubKey); valPubKeyString != "" {
valPubKey, err = sdk.GetConsPubKeyBech32(valPubKeyString)
if err != nil {
return err
}
}
website := viper.GetString(cli.FlagWebsite)
details := viper.GetString(cli.FlagDetails)
identity := viper.GetString(cli.FlagIdentity)
// Set flags for creating gentx // Set flags for creating gentx
prepareFlagsForTxCreateValidator(config, nodeID, ip, genDoc.ChainID, valPubKey, website, details, identity) viper.Set(client.FlagHome, viper.GetString(flagClientHome))
smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey)
// Fetch the amount of coins staked // Fetch the amount of coins staked
amount := viper.GetString(cli.FlagAmount) amount := viper.GetString(flagAmount)
coins, err := sdk.ParseCoins(amount) coins, err := sdk.ParseCoins(amount)
if err != nil { if err != nil {
return err return err
@ -134,8 +117,8 @@ following delegation and commission default parameters:
return err return err
} }
txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc))
cliCtx := context.NewCLIContext().WithCodec(cdc) cliCtx := client.NewCLIContext().WithCodec(cdc)
// XXX: Set the generate-only flag here after the CLI context has // XXX: Set the generate-only flag here after the CLI context has
// been created. This allows the from name/key to be correctly populated. // been created. This allows the from name/key to be correctly populated.
@ -145,7 +128,7 @@ following delegation and commission default parameters:
viper.Set(client.FlagGenerateOnly, true) viper.Set(client.FlagGenerateOnly, true)
// create a 'create-validator' message // create a 'create-validator' message
txBldr, msg, err := cli.BuildCreateValidatorMsg(cliCtx, txBldr) txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr)
if err != nil { if err != nil {
return err return err
} }
@ -157,14 +140,14 @@ following delegation and commission default parameters:
if info.GetType() == kbkeys.TypeOffline || info.GetType() == kbkeys.TypeMulti { if info.GetType() == kbkeys.TypeOffline || info.GetType() == kbkeys.TypeMulti {
fmt.Println("Offline key passed in. Use `tx sign` command to sign:") fmt.Println("Offline key passed in. Use `tx sign` command to sign:")
return utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}) return client.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg})
} }
// write the unsigned transaction to the buffer // write the unsigned transaction to the buffer
w := bytes.NewBuffer([]byte{}) w := bytes.NewBuffer([]byte{})
cliCtx = cliCtx.WithOutput(w) cliCtx = cliCtx.WithOutput(w)
if err = utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil { if err = client.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil {
return err return err
} }
@ -175,7 +158,7 @@ following delegation and commission default parameters:
} }
// sign the transaction and write it to the output file // sign the transaction and write it to the output file
signedTx, err := utils.SignStdTx(txBldr, cliCtx, name, stdTx, false, true) signedTx, err := client.SignStdTx(txBldr, cliCtx, name, stdTx, false, true)
if err != nil { if err != nil {
return err return err
} }
@ -199,22 +182,13 @@ following delegation and commission default parameters:
}, },
} }
ip, _ := server.ExternalIP() cmd.Flags().String(client.FlagHome, defaultNodeHome, "node's home directory")
cmd.Flags().String(tmcli.HomeFlag, defaultNodeHome, "node's home directory")
cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory") cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory")
cmd.Flags().String(client.FlagName, "", "name of private key with which to sign the gentx") cmd.Flags().String(client.FlagName, "", "name of private key with which to sign the gentx")
cmd.Flags().String(client.FlagOutputDocument, "", cmd.Flags().String(client.FlagOutputDocument, "",
"write the genesis transaction JSON document to the given file instead of the default location") "write the genesis transaction JSON document to the given file instead of the default location")
cmd.Flags().String(cli.FlagIP, ip, "The node's public IP") cmd.Flags().AddFlagSet(fsCreateValidator)
cmd.Flags().String(cli.FlagNodeID, "", "The node's NodeID")
cmd.Flags().String(cli.FlagWebsite, "", "The validator's (optional) website")
cmd.Flags().String(cli.FlagDetails, "", "The validator's (optional) details")
cmd.Flags().String(cli.FlagIdentity, "", "The (optional) identity signature (ex. UPort or Keybase)")
cmd.Flags().AddFlagSet(cli.FsCommissionCreate)
cmd.Flags().AddFlagSet(cli.FsMinSelfDelegation)
cmd.Flags().AddFlagSet(cli.FsAmount)
cmd.Flags().AddFlagSet(cli.FsPk)
cmd.MarkFlagRequired(client.FlagName) cmd.MarkFlagRequired(client.FlagName)
return cmd return cmd
} }
@ -251,38 +225,4 @@ func writeSignedGenTx(cdc *codec.Codec, outputDocument string, tx auth.StdTx) er
return err return err
} }
func prepareFlagsForTxCreateValidator(
config *cfg.Config, nodeID, ip, chainID string, valPubKey crypto.PubKey, website, details, identity string,
) {
viper.Set(tmcli.HomeFlag, viper.GetString(flagClientHome))
viper.Set(client.FlagChainID, chainID)
viper.Set(client.FlagFrom, viper.GetString(client.FlagName))
viper.Set(cli.FlagNodeID, nodeID)
viper.Set(cli.FlagIP, ip)
viper.Set(cli.FlagPubKey, sdk.MustBech32ifyConsPub(valPubKey))
viper.Set(cli.FlagMoniker, config.Moniker)
viper.Set(cli.FlagWebsite, website)
viper.Set(cli.FlagDetails, details)
viper.Set(cli.FlagIdentity, identity)
if config.Moniker == "" {
viper.Set(cli.FlagMoniker, viper.GetString(client.FlagName))
}
if viper.GetString(cli.FlagAmount) == "" {
viper.Set(cli.FlagAmount, defaultAmount)
}
if viper.GetString(cli.FlagCommissionRate) == "" {
viper.Set(cli.FlagCommissionRate, defaultCommissionRate)
}
if viper.GetString(cli.FlagCommissionMaxRate) == "" {
viper.Set(cli.FlagCommissionMaxRate, defaultCommissionMaxRate)
}
if viper.GetString(cli.FlagCommissionMaxChangeRate) == "" {
viper.Set(cli.FlagCommissionMaxChangeRate, defaultCommissionMaxChangeRate)
}
if viper.GetString(cli.FlagMinSelfDelegation) == "" {
viper.Set(cli.FlagMinSelfDelegation, defaultMinSelfDelegation)
}
}
// DONTCOVER // DONTCOVER

View File

@ -167,7 +167,7 @@ func CollectStdTxs(cdc *codec.Codec, moniker, genTxsDir string,
"each genesis transaction must provide a single genesis message") "each genesis transaction must provide a single genesis message")
} }
// TODO abstract out staking reference here through the expected staking keeper // TODO abstract out staking message validation back to staking
msg := msgs[0].(staking.MsgCreateValidator) msg := msgs[0].(staking.MsgCreateValidator)
// validate delegator and validator addresses and funds against the accounts in the state // validate delegator and validator addresses and funds against the accounts in the state
delAddr := msg.DelegatorAddress.String() delAddr := msg.DelegatorAddress.String()

View File

@ -5,11 +5,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/tendermint/tendermint/libs/common"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking"
"github.com/tendermint/tendermint/libs/common"
tmtypes "github.com/tendermint/tendermint/types"
) )
// State to Unmarshal // State to Unmarshal
@ -99,6 +100,7 @@ func ValidateGenesis(genesisState GenesisState) error {
"must provide genesis StdTx with exactly 1 CreateValidator message") "must provide genesis StdTx with exactly 1 CreateValidator message")
} }
// TODO abstract back to staking
if _, ok := msgs[0].(staking.MsgCreateValidator); !ok { if _, ok := msgs[0].(staking.MsgCreateValidator); !ok {
return fmt.Errorf( return fmt.Errorf(
"Genesis transaction %v does not contain a MsgCreateValidator", i) "Genesis transaction %v does not contain a MsgCreateValidator", i)

View File

@ -61,30 +61,6 @@ var (
PositiveDelegationInvariant = keeper.PositiveDelegationInvariant PositiveDelegationInvariant = keeper.PositiveDelegationInvariant
DelegatorSharesInvariant = keeper.DelegatorSharesInvariant DelegatorSharesInvariant = keeper.DelegatorSharesInvariant
NewKeeper = keeper.NewKeeper NewKeeper = keeper.NewKeeper
GetValidatorKey = keeper.GetValidatorKey
GetValidatorByConsAddrKey = keeper.GetValidatorByConsAddrKey
AddressFromLastValidatorPowerKey = keeper.AddressFromLastValidatorPowerKey
GetValidatorsByPowerIndexKey = keeper.GetValidatorsByPowerIndexKey
GetLastValidatorPowerKey = keeper.GetLastValidatorPowerKey
GetValidatorQueueTimeKey = keeper.GetValidatorQueueTimeKey
GetDelegationKey = keeper.GetDelegationKey
GetDelegationsKey = keeper.GetDelegationsKey
GetUBDKey = keeper.GetUBDKey
GetUBDByValIndexKey = keeper.GetUBDByValIndexKey
GetUBDKeyFromValIndexKey = keeper.GetUBDKeyFromValIndexKey
GetUBDsKey = keeper.GetUBDsKey
GetUBDsByValIndexKey = keeper.GetUBDsByValIndexKey
GetUnbondingDelegationTimeKey = keeper.GetUnbondingDelegationTimeKey
GetREDKey = keeper.GetREDKey
GetREDByValSrcIndexKey = keeper.GetREDByValSrcIndexKey
GetREDByValDstIndexKey = keeper.GetREDByValDstIndexKey
GetREDKeyFromValSrcIndexKey = keeper.GetREDKeyFromValSrcIndexKey
GetREDKeyFromValDstIndexKey = keeper.GetREDKeyFromValDstIndexKey
GetRedelegationTimeKey = keeper.GetRedelegationTimeKey
GetREDsKey = keeper.GetREDsKey
GetREDsFromValSrcIndexKey = keeper.GetREDsFromValSrcIndexKey
GetREDsToValDstIndexKey = keeper.GetREDsToValDstIndexKey
GetREDsByDelToValDstIndexKey = keeper.GetREDsByDelToValDstIndexKey
ParamKeyTable = keeper.ParamKeyTable ParamKeyTable = keeper.ParamKeyTable
ValEq = keeper.ValEq ValEq = keeper.ValEq
MakeTestCodec = keeper.MakeTestCodec MakeTestCodec = keeper.MakeTestCodec
@ -170,6 +146,31 @@ var (
NewGenesisState = types.NewGenesisState NewGenesisState = types.NewGenesisState
DefaultGenesisState = types.DefaultGenesisState DefaultGenesisState = types.DefaultGenesisState
NewMultiStakingHooks = types.NewMultiStakingHooks NewMultiStakingHooks = types.NewMultiStakingHooks
GetValidatorKey = types.GetValidatorKey
GetValidatorByConsAddrKey = types.GetValidatorByConsAddrKey
AddressFromLastValidatorPowerKey = types.AddressFromLastValidatorPowerKey
GetValidatorsByPowerIndexKey = types.GetValidatorsByPowerIndexKey
GetLastValidatorPowerKey = types.GetLastValidatorPowerKey
ParseValidatorPowerRankKey = types.ParseValidatorPowerRankKey
GetValidatorQueueTimeKey = types.GetValidatorQueueTimeKey
GetDelegationKey = types.GetDelegationKey
GetDelegationsKey = types.GetDelegationsKey
GetUBDKey = types.GetUBDKey
GetUBDByValIndexKey = types.GetUBDByValIndexKey
GetUBDKeyFromValIndexKey = types.GetUBDKeyFromValIndexKey
GetUBDsKey = types.GetUBDsKey
GetUBDsByValIndexKey = types.GetUBDsByValIndexKey
GetUnbondingDelegationTimeKey = types.GetUnbondingDelegationTimeKey
GetREDKey = types.GetREDKey
GetREDByValSrcIndexKey = types.GetREDByValSrcIndexKey
GetREDByValDstIndexKey = types.GetREDByValDstIndexKey
GetREDKeyFromValSrcIndexKey = types.GetREDKeyFromValSrcIndexKey
GetREDKeyFromValDstIndexKey = types.GetREDKeyFromValDstIndexKey
GetRedelegationTimeKey = types.GetRedelegationTimeKey
GetREDsKey = types.GetREDsKey
GetREDsFromValSrcIndexKey = types.GetREDsFromValSrcIndexKey
GetREDsToValDstIndexKey = types.GetREDsToValDstIndexKey
GetREDsByDelToValDstIndexKey = types.GetREDsByDelToValDstIndexKey
NewMsgCreateValidator = types.NewMsgCreateValidator NewMsgCreateValidator = types.NewMsgCreateValidator
NewMsgEditValidator = types.NewMsgEditValidator NewMsgEditValidator = types.NewMsgEditValidator
NewMsgDelegate = types.NewMsgDelegate NewMsgDelegate = types.NewMsgDelegate
@ -189,24 +190,24 @@ var (
NewDescription = types.NewDescription NewDescription = types.NewDescription
// variable aliases // variable aliases
PoolKey = keeper.PoolKey
LastValidatorPowerKey = keeper.LastValidatorPowerKey
LastTotalPowerKey = keeper.LastTotalPowerKey
ValidatorsKey = keeper.ValidatorsKey
ValidatorsByConsAddrKey = keeper.ValidatorsByConsAddrKey
ValidatorsByPowerIndexKey = keeper.ValidatorsByPowerIndexKey
DelegationKey = keeper.DelegationKey
UnbondingDelegationKey = keeper.UnbondingDelegationKey
UnbondingDelegationByValIndexKey = keeper.UnbondingDelegationByValIndexKey
RedelegationKey = keeper.RedelegationKey
RedelegationByValSrcIndexKey = keeper.RedelegationByValSrcIndexKey
RedelegationByValDstIndexKey = keeper.RedelegationByValDstIndexKey
UnbondingQueueKey = keeper.UnbondingQueueKey
RedelegationQueueKey = keeper.RedelegationQueueKey
ValidatorQueueKey = keeper.ValidatorQueueKey
Addrs = keeper.Addrs Addrs = keeper.Addrs
PKs = keeper.PKs PKs = keeper.PKs
ModuleCdc = types.ModuleCdc ModuleCdc = types.ModuleCdc
PoolKey = types.PoolKey
LastValidatorPowerKey = types.LastValidatorPowerKey
LastTotalPowerKey = types.LastTotalPowerKey
ValidatorsKey = types.ValidatorsKey
ValidatorsByConsAddrKey = types.ValidatorsByConsAddrKey
ValidatorsByPowerIndexKey = types.ValidatorsByPowerIndexKey
DelegationKey = types.DelegationKey
UnbondingDelegationKey = types.UnbondingDelegationKey
UnbondingDelegationByValIndexKey = types.UnbondingDelegationByValIndexKey
RedelegationKey = types.RedelegationKey
RedelegationByValSrcIndexKey = types.RedelegationByValSrcIndexKey
RedelegationByValDstIndexKey = types.RedelegationByValDstIndexKey
UnbondingQueueKey = types.UnbondingQueueKey
RedelegationQueueKey = types.RedelegationQueueKey
ValidatorQueueKey = types.ValidatorQueueKey
KeyUnbondingTime = types.KeyUnbondingTime KeyUnbondingTime = types.KeyUnbondingTime
KeyMaxValidators = types.KeyMaxValidators KeyMaxValidators = types.KeyMaxValidators
KeyMaxEntries = types.KeyMaxEntries KeyMaxEntries = types.KeyMaxEntries

View File

@ -10,7 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/querier"
"github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/staking/types"
) )
@ -37,7 +37,7 @@ $ %s query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhff
return err return err
} }
res, err := cliCtx.QueryStore(staking.GetValidatorKey(addr), storeName) res, err := cliCtx.QueryStore(types.GetValidatorKey(addr), storeName)
if err != nil { if err != nil {
return err return err
} }
@ -69,12 +69,12 @@ $ %s query staking validators
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc) cliCtx := context.NewCLIContext().WithCodec(cdc)
resKVs, err := cliCtx.QuerySubspace(staking.ValidatorsKey, storeName) resKVs, err := cliCtx.QuerySubspace(types.ValidatorsKey, storeName)
if err != nil { if err != nil {
return err return err
} }
var validators staking.Validators var validators types.Validators
for _, kv := range resKVs { for _, kv := range resKVs {
validators = append(validators, types.MustUnmarshalValidator(cdc, kv.Value)) validators = append(validators, types.MustUnmarshalValidator(cdc, kv.Value))
} }
@ -107,18 +107,18 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6
return err return err
} }
bz, err := cdc.MarshalJSON(staking.NewQueryValidatorParams(valAddr)) bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr))
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryValidatorUnbondingDelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorUnbondingDelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var ubds staking.UnbondingDelegations var ubds types.UnbondingDelegations
cdc.MustUnmarshalJSON(res, &ubds) cdc.MustUnmarshalJSON(res, &ubds)
return cliCtx.PrintOutput(ubds) return cliCtx.PrintOutput(ubds)
}, },
@ -149,18 +149,18 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx
return err return err
} }
bz, err := cdc.MarshalJSON(staking.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr}) bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr})
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryRedelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.RedelegationResponses var resp types.RedelegationResponses
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -198,18 +198,18 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm
return err return err
} }
bz, err := cdc.MarshalJSON(staking.NewQueryBondsParams(delAddr, valAddr)) bz, err := cdc.MarshalJSON(querier.NewQueryBondsParams(delAddr, valAddr))
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryDelegation) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegation)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.DelegationResponse var resp types.DelegationResponse
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -243,18 +243,18 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
return err return err
} }
bz, err := cdc.MarshalJSON(staking.NewQueryDelegatorParams(delAddr)) bz, err := cdc.MarshalJSON(querier.NewQueryDelegatorParams(delAddr))
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryDelegatorDelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegatorDelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.DelegationResponses var resp types.DelegationResponses
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -288,18 +288,18 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld
return err return err
} }
bz, err := cdc.MarshalJSON(staking.NewQueryValidatorParams(valAddr)) bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr))
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryValidatorDelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorDelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.DelegationResponses var resp types.DelegationResponses
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -338,7 +338,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7
return err return err
} }
res, err := cliCtx.QueryStore(staking.GetUBDKey(delAddr, valAddr), storeName) res, err := cliCtx.QueryStore(types.GetUBDKey(delAddr, valAddr), storeName)
if err != nil { if err != nil {
return err return err
} }
@ -373,12 +373,12 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7
return err return err
} }
resKVs, err := cliCtx.QuerySubspace(staking.GetUBDsKey(delegatorAddr), storeName) resKVs, err := cliCtx.QuerySubspace(types.GetUBDsKey(delegatorAddr), storeName)
if err != nil { if err != nil {
return err return err
} }
var ubds staking.UnbondingDelegations var ubds types.UnbondingDelegations
for _, kv := range resKVs { for _, kv := range resKVs {
ubds = append(ubds, types.MustUnmarshalUBD(cdc, kv.Value)) ubds = append(ubds, types.MustUnmarshalUBD(cdc, kv.Value))
} }
@ -422,18 +422,18 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co
return err return err
} }
bz, err := cdc.MarshalJSON(staking.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr)) bz, err := cdc.MarshalJSON(querier.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr))
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryRedelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.RedelegationResponses var resp types.RedelegationResponses
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -467,18 +467,18 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
return err return err
} }
bz, err := cdc.MarshalJSON(staking.QueryRedelegationParams{DelegatorAddr: delAddr}) bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{DelegatorAddr: delAddr})
if err != nil { if err != nil {
return err return err
} }
route := fmt.Sprintf("custom/%s/%s", storeKey, staking.QueryRedelegations) route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations)
res, err := cliCtx.QueryWithData(route, bz) res, err := cliCtx.QueryWithData(route, bz)
if err != nil { if err != nil {
return err return err
} }
var resp staking.RedelegationResponses var resp types.RedelegationResponses
if err := cdc.UnmarshalJSON(res, &resp); err != nil { if err := cdc.UnmarshalJSON(res, &resp); err != nil {
return err return err
} }
@ -506,7 +506,7 @@ $ %s query staking pool
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc) cliCtx := context.NewCLIContext().WithCodec(cdc)
res, err := cliCtx.QueryStore(staking.PoolKey, storeName) res, err := cliCtx.QueryStore(types.PoolKey, storeName)
if err != nil { if err != nil {
return err return err
} }
@ -534,13 +534,13 @@ $ %s query staking params
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc) cliCtx := context.NewCLIContext().WithCodec(cdc)
route := fmt.Sprintf("custom/%s/%s", storeName, staking.QueryParameters) route := fmt.Sprintf("custom/%s/%s", storeName, querier.QueryParameters)
bz, err := cliCtx.QueryWithData(route, nil) bz, err := cliCtx.QueryWithData(route, nil)
if err != nil { if err != nil {
return err return err
} }
var params staking.Params var params types.Params
cdc.MustUnmarshalJSON(bz, &params) cdc.MustUnmarshalJSON(bz, &params)
return cliCtx.PrintOutput(params) return cliCtx.PrintOutput(params)
}, },

View File

@ -2,25 +2,28 @@ package cli
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/cosmos/cosmos-sdk/version" "github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/x/auth" flag "github.com/spf13/pflag"
"github.com/spf13/viper"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/spf13/cobra"
"github.com/spf13/viper"
) )
// GetCmdCreateValidator implements the create validator command handler. // GetCmdCreateValidator implements the create validator command handler.
// TODO: Add full description
func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command { func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "create-validator", Use: "create-validator",
@ -70,7 +73,7 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command {
WithAccountDecoder(cdc) WithAccountDecoder(cdc)
valAddr := cliCtx.GetFromAddress() valAddr := cliCtx.GetFromAddress()
description := staking.Description{ description := types.Description{
Moniker: viper.GetString(FlagMoniker), Moniker: viper.GetString(FlagMoniker),
Identity: viper.GetString(FlagIdentity), Identity: viper.GetString(FlagIdentity),
Website: viper.GetString(FlagWebsite), Website: viper.GetString(FlagWebsite),
@ -95,12 +98,12 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command {
if minSelfDelegationString != "" { if minSelfDelegationString != "" {
msb, ok := sdk.NewIntFromString(minSelfDelegationString) msb, ok := sdk.NewIntFromString(minSelfDelegationString)
if !ok { if !ok {
return fmt.Errorf(staking.ErrMinSelfDelegationInvalid(staking.DefaultCodespace).Error()) return fmt.Errorf(types.ErrMinSelfDelegationInvalid(types.DefaultCodespace).Error())
} }
newMinSelfDelegation = &msb newMinSelfDelegation = &msb
} }
msg := staking.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate, newMinSelfDelegation) msg := types.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate, newMinSelfDelegation)
// build and sign the transaction, then broadcast to Tendermint // build and sign the transaction, then broadcast to Tendermint
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
@ -145,7 +148,7 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10
return err return err
} }
msg := staking.NewMsgDelegate(delAddr, valAddr, amount) msg := types.NewMsgDelegate(delAddr, valAddr, amount)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
}, },
} }
@ -188,7 +191,7 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
return err return err
} }
msg := staking.NewMsgBeginRedelegate(delAddr, valSrcAddr, valDstAddr, amount) msg := types.NewMsgBeginRedelegate(delAddr, valSrcAddr, valDstAddr, amount)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
}, },
} }
@ -226,12 +229,96 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s
return err return err
} }
msg := staking.NewMsgUndelegate(delAddr, valAddr, amount) msg := types.NewMsgUndelegate(delAddr, valAddr, amount)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
}, },
} }
} }
//__________________________________________________________
var (
defaultTokens = sdk.TokensFromTendermintPower(100)
defaultAmount = defaultTokens.String() + sdk.DefaultBondDenom
defaultCommissionRate = "0.1"
defaultCommissionMaxRate = "0.2"
defaultCommissionMaxChangeRate = "0.01"
defaultMinSelfDelegation = "1"
)
// Return the flagset, particular flags, and a description of defaults
// this is anticipated to be used with the gen-tx
func CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string) {
fsCreateValidator := flag.NewFlagSet("", flag.ContinueOnError)
fsCreateValidator.String(FlagIP, ipDefault, "The node's public IP")
fsCreateValidator.String(FlagNodeID, "", "The node's NodeID")
fsCreateValidator.String(FlagWebsite, "", "The validator's (optional) website")
fsCreateValidator.String(FlagDetails, "", "The validator's (optional) details")
fsCreateValidator.String(FlagIdentity, "", "The (optional) identity signature (ex. UPort or Keybase)")
fsCreateValidator.AddFlagSet(FsCommissionCreate)
fsCreateValidator.AddFlagSet(FsMinSelfDelegation)
fsCreateValidator.AddFlagSet(FsAmount)
fsCreateValidator.AddFlagSet(FsPk)
defaultsDesc = fmt.Sprintf(`
delegation amount: %s
commission rate: %s
commission max rate: %s
commission max change rate: %s
minimum self delegation: %s
`, defaultAmount, defaultCommissionRate,
defaultCommissionMaxRate, defaultCommissionMaxChangeRate,
defaultMinSelfDelegation)
return fsCreateValidator, FlagNodeID, FlagPubKey, FlagAmount, defaultsDesc
}
// prepare flags in config
func PrepareFlagsForTxCreateValidator(
config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey,
) {
ip := viper.GetString(FlagIP)
if ip == "" {
fmt.Fprintf(os.Stderr, "couldn't retrieve an external IP; "+
"the tx's memo field will be unset")
}
website := viper.GetString(FlagWebsite)
details := viper.GetString(FlagDetails)
identity := viper.GetString(FlagIdentity)
viper.Set(client.FlagChainID, chainID)
viper.Set(client.FlagFrom, viper.GetString(client.FlagName))
viper.Set(FlagNodeID, nodeID)
viper.Set(FlagIP, ip)
viper.Set(FlagPubKey, sdk.MustBech32ifyConsPub(valPubKey))
viper.Set(FlagMoniker, config.Moniker)
viper.Set(FlagWebsite, website)
viper.Set(FlagDetails, details)
viper.Set(FlagIdentity, identity)
if config.Moniker == "" {
viper.Set(FlagMoniker, viper.GetString(client.FlagName))
}
if viper.GetString(FlagAmount) == "" {
viper.Set(FlagAmount, defaultAmount)
}
if viper.GetString(FlagCommissionRate) == "" {
viper.Set(FlagCommissionRate, defaultCommissionRate)
}
if viper.GetString(FlagCommissionMaxRate) == "" {
viper.Set(FlagCommissionMaxRate, defaultCommissionMaxRate)
}
if viper.GetString(FlagCommissionMaxChangeRate) == "" {
viper.Set(FlagCommissionMaxChangeRate, defaultCommissionMaxChangeRate)
}
if viper.GetString(FlagMinSelfDelegation) == "" {
viper.Set(FlagMinSelfDelegation, defaultMinSelfDelegation)
}
}
// BuildCreateValidatorMsg makes a new MsgCreateValidator. // BuildCreateValidatorMsg makes a new MsgCreateValidator.
func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) { func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) {
amounstStr := viper.GetString(FlagAmount) amounstStr := viper.GetString(FlagAmount)
@ -248,7 +335,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder
return txBldr, nil, err return txBldr, nil, err
} }
description := staking.NewDescription( description := types.NewDescription(
viper.GetString(FlagMoniker), viper.GetString(FlagMoniker),
viper.GetString(FlagIdentity), viper.GetString(FlagIdentity),
viper.GetString(FlagWebsite), viper.GetString(FlagWebsite),
@ -268,10 +355,10 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder
msbStr := viper.GetString(FlagMinSelfDelegation) msbStr := viper.GetString(FlagMinSelfDelegation)
minSelfDelegation, ok := sdk.NewIntFromString(msbStr) minSelfDelegation, ok := sdk.NewIntFromString(msbStr)
if !ok { if !ok {
return txBldr, nil, fmt.Errorf(staking.ErrMinSelfDelegationInvalid(staking.DefaultCodespace).Error()) return txBldr, nil, fmt.Errorf(types.ErrMinSelfDelegationInvalid(types.DefaultCodespace).Error())
} }
msg := staking.NewMsgCreateValidator( msg := types.NewMsgCreateValidator(
sdk.ValAddress(valAddr), pk, amount, description, commissionMsg, minSelfDelegation, sdk.ValAddress(valAddr), pk, amount, description, commissionMsg, minSelfDelegation,
) )

View File

@ -12,12 +12,10 @@ import (
"github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
) )
func Test_prepareFlagsForTxCreateValidator(t *testing.T) { func TestPrepareFlagsForTxCreateValidator(t *testing.T) {
defer server.SetupViper(t)() defer server.SetupViper(t)()
defer setupClientHome(t)()
config, err := tcmd.ParseConfig() config, err := tcmd.ParseConfig()
require.Nil(t, err) require.Nil(t, err)
logger := log.NewNopLogger() logger := log.NewNopLogger()
@ -28,12 +26,8 @@ func Test_prepareFlagsForTxCreateValidator(t *testing.T) {
type args struct { type args struct {
config *cfg.Config config *cfg.Config
nodeID string nodeID string
ip string
chainID string chainID string
valPubKey crypto.PubKey valPubKey crypto.PubKey
website string
details string
identity string
} }
type extraParams struct { type extraParams struct {
@ -50,23 +44,18 @@ func Test_prepareFlagsForTxCreateValidator(t *testing.T) {
} }
runTest := func(t *testing.T, tt testcase, params extraParams) { runTest := func(t *testing.T, tt testcase, params extraParams) {
prepareFlagsForTxCreateValidator(tt.args.config, tt.args.nodeID, PrepareFlagsForTxCreateValidator(tt.args.config, tt.args.nodeID,
tt.args.ip, tt.args.chainID, tt.args.valPubKey, tt.args.website, tt.args.chainID, tt.args.valPubKey)
tt.args.details, tt.args.identity)
require.Equal(t, tt.args.website, viper.GetString(cli.FlagWebsite)) require.Equal(t, params.amount, viper.GetString(FlagAmount))
require.Equal(t, tt.args.details, viper.GetString(cli.FlagDetails)) require.Equal(t, params.commissionRate, viper.GetString(FlagCommissionRate))
require.Equal(t, tt.args.identity, viper.GetString(cli.FlagIdentity)) require.Equal(t, params.commissionMaxRate, viper.GetString(FlagCommissionMaxRate))
require.Equal(t, params.amount, viper.GetString(cli.FlagAmount)) require.Equal(t, params.commissionMaxChangeRate, viper.GetString(FlagCommissionMaxChangeRate))
require.Equal(t, params.commissionRate, viper.GetString(cli.FlagCommissionRate)) require.Equal(t, params.minSelfDelegation, viper.GetString(FlagMinSelfDelegation))
require.Equal(t, params.commissionMaxRate, viper.GetString(cli.FlagCommissionMaxRate))
require.Equal(t, params.commissionMaxChangeRate, viper.GetString(cli.FlagCommissionMaxChangeRate))
require.Equal(t, params.minSelfDelegation, viper.GetString(cli.FlagMinSelfDelegation))
} }
tests := []testcase{ tests := []testcase{
{"No parameters", args{ctx.Config, "X", "0.0.0.0", "chainId", valPubKey, "", "", ""}}, {"No parameters", args{ctx.Config, "X", "chainId", valPubKey}},
{"Optional parameters fed", args{ctx.Config, "X", "0.0.0.0", "chainId", valPubKey, "cosmos.network", "details", "identity"}},
} }
defaultParams := extraParams{ defaultParams := extraParams{
@ -84,11 +73,11 @@ func Test_prepareFlagsForTxCreateValidator(t *testing.T) {
// Override default params // Override default params
params := extraParams{"5stake", "1.0", "1.0", "1.0", "1.0"} params := extraParams{"5stake", "1.0", "1.0", "1.0", "1.0"}
viper.Set(cli.FlagAmount, params.amount) viper.Set(FlagAmount, params.amount)
viper.Set(cli.FlagCommissionRate, params.commissionRate) viper.Set(FlagCommissionRate, params.commissionRate)
viper.Set(cli.FlagCommissionMaxRate, params.commissionMaxRate) viper.Set(FlagCommissionMaxRate, params.commissionMaxRate)
viper.Set(cli.FlagCommissionMaxChangeRate, params.commissionMaxChangeRate) viper.Set(FlagCommissionMaxChangeRate, params.commissionMaxChangeRate)
viper.Set(cli.FlagMinSelfDelegation, params.minSelfDelegation) viper.Set(FlagMinSelfDelegation, params.minSelfDelegation)
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { runTest(t, tt, params) }) t.Run(tt.name, func(t *testing.T) { runTest(t, tt, params) })
} }

View File

@ -55,8 +55,8 @@ func TestValidatorByPowerIndex(t *testing.T) {
// verify that the by power index exists // verify that the by power index exists
validator, found := keeper.GetValidator(ctx, validatorAddr) validator, found := keeper.GetValidator(ctx, validatorAddr)
require.True(t, found) require.True(t, found)
power := keep.GetValidatorsByPowerIndexKey(validator) power := GetValidatorsByPowerIndexKey(validator)
require.True(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power)) require.True(t, ValidatorByPowerIndexExists(ctx, keeper, power))
// create a second validator keep it bonded // create a second validator keep it bonded
msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, keep.PKs[2], initBond) msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, keep.PKs[2], initBond)

View File

@ -13,7 +13,7 @@ var _ sdk.ValidatorSet = Keeper{}
// iterate through the validator set and perform the provided function // iterate through the validator set and perform the provided function
func (k Keeper) IterateValidators(ctx sdk.Context, fn func(index int64, validator sdk.Validator) (stop bool)) { func (k Keeper) IterateValidators(ctx sdk.Context, fn func(index int64, validator sdk.Validator) (stop bool)) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, ValidatorsKey) iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)
defer iterator.Close() defer iterator.Close()
i := int64(0) i := int64(0)
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
@ -31,7 +31,7 @@ func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context, fn func(index in
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
maxValidators := k.MaxValidators(ctx) maxValidators := k.MaxValidators(ctx)
iterator := sdk.KVStoreReversePrefixIterator(store, ValidatorsByPowerIndexKey) iterator := sdk.KVStoreReversePrefixIterator(store, types.ValidatorsByPowerIndexKey)
defer iterator.Close() defer iterator.Close()
i := int64(0) i := int64(0)
@ -55,7 +55,7 @@ func (k Keeper) IterateLastValidators(ctx sdk.Context, fn func(index int64, vali
defer iterator.Close() defer iterator.Close()
i := int64(0) i := int64(0)
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
address := AddressFromLastValidatorPowerKey(iterator.Key()) address := types.AddressFromLastValidatorPowerKey(iterator.Key())
validator, found := k.GetValidator(ctx, address) validator, found := k.GetValidator(ctx, address)
if !found { if !found {
panic(fmt.Sprintf("validator record not found for address: %v\n", address)) panic(fmt.Sprintf("validator record not found for address: %v\n", address))
@ -136,7 +136,7 @@ func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress,
fn func(index int64, del sdk.Delegation) (stop bool)) { fn func(index int64, del sdk.Delegation) (stop bool)) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetDelegationsKey(delAddr) delegatorPrefixKey := types.GetDelegationsKey(delAddr)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
defer iterator.Close() defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() { for i := int64(0); iterator.Valid(); iterator.Next() {
@ -153,7 +153,7 @@ func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress,
// TODO: remove this func, change all usage for iterate functionality // TODO: remove this func, change all usage for iterate functionality
func (k Keeper) GetAllSDKDelegations(ctx sdk.Context) (delegations []sdk.Delegation) { func (k Keeper) GetAllSDKDelegations(ctx sdk.Context) (delegations []sdk.Delegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, DelegationKey) iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {

View File

@ -14,7 +14,7 @@ func (k Keeper) GetDelegation(ctx sdk.Context,
delegation types.Delegation, found bool) { delegation types.Delegation, found bool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
key := GetDelegationKey(delAddr, valAddr) key := types.GetDelegationKey(delAddr, valAddr)
value := store.Get(key) value := store.Get(key)
if value == nil { if value == nil {
return delegation, false return delegation, false
@ -27,7 +27,7 @@ func (k Keeper) GetDelegation(ctx sdk.Context,
// return all delegations used during genesis dump // return all delegations used during genesis dump
func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegation) { func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, DelegationKey) iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
@ -40,7 +40,7 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati
// return all delegations to a specific validator. Useful for querier. // return all delegations to a specific validator. Useful for querier.
func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, DelegationKey) iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
@ -59,7 +59,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres
delegations = make([]types.Delegation, maxRetrieve) delegations = make([]types.Delegation, maxRetrieve)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetDelegationsKey(delegator) delegatorPrefixKey := types.GetDelegationsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close() defer iterator.Close()
@ -76,7 +76,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres
func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
b := types.MustMarshalDelegation(k.cdc, delegation) b := types.MustMarshalDelegation(k.cdc, delegation)
store.Set(GetDelegationKey(delegation.DelegatorAddress, delegation.ValidatorAddress), b) store.Set(types.GetDelegationKey(delegation.DelegatorAddress, delegation.ValidatorAddress), b)
} }
// remove a delegation // remove a delegation
@ -84,7 +84,7 @@ func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) {
// TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious. // TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious.
k.BeforeDelegationRemoved(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress) k.BeforeDelegationRemoved(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Delete(GetDelegationKey(delegation.DelegatorAddress, delegation.ValidatorAddress)) store.Delete(types.GetDelegationKey(delegation.DelegatorAddress, delegation.ValidatorAddress))
} }
// return a given amount of all the delegator unbonding-delegations // return a given amount of all the delegator unbonding-delegations
@ -94,7 +94,7 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres
unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve) unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetUBDsKey(delegator) delegatorPrefixKey := types.GetUBDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close() defer iterator.Close()
@ -112,7 +112,7 @@ func (k Keeper) GetUnbondingDelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, found bool) { delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, found bool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
key := GetUBDKey(delAddr, valAddr) key := types.GetUBDKey(delAddr, valAddr)
value := store.Get(key) value := store.Get(key)
if value == nil { if value == nil {
return ubd, false return ubd, false
@ -125,11 +125,11 @@ func (k Keeper) GetUnbondingDelegation(ctx sdk.Context,
// return all unbonding delegations from a particular validator // return all unbonding delegations from a particular validator
func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) { func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, GetUBDsByValIndexKey(valAddr)) iterator := sdk.KVStorePrefixIterator(store, types.GetUBDsByValIndexKey(valAddr))
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
key := GetUBDKeyFromValIndexKey(iterator.Key()) key := types.GetUBDKeyFromValIndexKey(iterator.Key())
value := store.Get(key) value := store.Get(key)
ubd := types.MustUnmarshalUBD(k.cdc, value) ubd := types.MustUnmarshalUBD(k.cdc, value)
ubds = append(ubds, ubd) ubds = append(ubds, ubd)
@ -140,7 +140,7 @@ func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sd
// iterate through all of the unbonding delegations // iterate through all of the unbonding delegations
func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) { func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, UnbondingDelegationKey) iterator := sdk.KVStorePrefixIterator(store, types.UnbondingDelegationKey)
defer iterator.Close() defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() { for i := int64(0); iterator.Valid(); iterator.Next() {
@ -167,17 +167,17 @@ func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context,
func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalUBD(k.cdc, ubd) bz := types.MustMarshalUBD(k.cdc, ubd)
key := GetUBDKey(ubd.DelegatorAddress, ubd.ValidatorAddress) key := types.GetUBDKey(ubd.DelegatorAddress, ubd.ValidatorAddress)
store.Set(key, bz) store.Set(key, bz)
store.Set(GetUBDByValIndexKey(ubd.DelegatorAddress, ubd.ValidatorAddress), []byte{}) // index, store empty bytes store.Set(types.GetUBDByValIndexKey(ubd.DelegatorAddress, ubd.ValidatorAddress), []byte{}) // index, store empty bytes
} }
// remove the unbonding delegation object and associated index // remove the unbonding delegation object and associated index
func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
key := GetUBDKey(ubd.DelegatorAddress, ubd.ValidatorAddress) key := types.GetUBDKey(ubd.DelegatorAddress, ubd.ValidatorAddress)
store.Delete(key) store.Delete(key)
store.Delete(GetUBDByValIndexKey(ubd.DelegatorAddress, ubd.ValidatorAddress)) store.Delete(types.GetUBDByValIndexKey(ubd.DelegatorAddress, ubd.ValidatorAddress))
} }
// SetUnbondingDelegationEntry adds an entry to the unbonding delegation at // SetUnbondingDelegationEntry adds an entry to the unbonding delegation at
@ -202,7 +202,7 @@ func (k Keeper) SetUnbondingDelegationEntry(ctx sdk.Context,
// corresponding to unbonding delegations that expire at a certain time. // corresponding to unbonding delegations that expire at a certain time.
func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPairs []types.DVPair) { func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPairs []types.DVPair) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := store.Get(GetUnbondingDelegationTimeKey(timestamp)) bz := store.Get(types.GetUnbondingDelegationTimeKey(timestamp))
if bz == nil { if bz == nil {
return []types.DVPair{} return []types.DVPair{}
} }
@ -214,7 +214,7 @@ func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPa
func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVPair) { func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVPair) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys) bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys)
store.Set(GetUnbondingDelegationTimeKey(timestamp), bz) store.Set(types.GetUnbondingDelegationTimeKey(timestamp), bz)
} }
// Insert an unbonding delegation to the appropriate timeslice in the unbonding queue // Insert an unbonding delegation to the appropriate timeslice in the unbonding queue
@ -234,8 +234,8 @@ func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation,
// Returns all the unbonding queue timeslices from time 0 until endTime // Returns all the unbonding queue timeslices from time 0 until endTime
func (k Keeper) UBDQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { func (k Keeper) UBDQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
return store.Iterator(UnbondingQueueKey, return store.Iterator(types.UnbondingQueueKey,
sdk.InclusiveEndBytes(GetUnbondingDelegationTimeKey(endTime))) sdk.InclusiveEndBytes(types.GetUnbondingDelegationTimeKey(endTime)))
} }
// Returns a concatenated list of all the timeslices inclusively previous to // Returns a concatenated list of all the timeslices inclusively previous to
@ -262,7 +262,7 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress,
redelegations = make([]types.Redelegation, maxRetrieve) redelegations = make([]types.Redelegation, maxRetrieve)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetREDsKey(delegator) delegatorPrefixKey := types.GetREDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close() defer iterator.Close()
@ -280,7 +280,7 @@ func (k Keeper) GetRedelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) { delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
key := GetREDKey(delAddr, valSrcAddr, valDstAddr) key := types.GetREDKey(delAddr, valSrcAddr, valDstAddr)
value := store.Get(key) value := store.Get(key)
if value == nil { if value == nil {
return red, false return red, false
@ -293,11 +293,11 @@ func (k Keeper) GetRedelegation(ctx sdk.Context,
// return all redelegations from a particular validator // return all redelegations from a particular validator
func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) { func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, GetREDsFromValSrcIndexKey(valAddr)) iterator := sdk.KVStorePrefixIterator(store, types.GetREDsFromValSrcIndexKey(valAddr))
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
key := GetREDKeyFromValSrcIndexKey(iterator.Key()) key := types.GetREDKeyFromValSrcIndexKey(iterator.Key())
value := store.Get(key) value := store.Get(key)
red := types.MustUnmarshalRED(k.cdc, value) red := types.MustUnmarshalRED(k.cdc, value)
reds = append(reds, red) reds = append(reds, red)
@ -310,7 +310,7 @@ func (k Keeper) HasReceivingRedelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool { delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
prefix := GetREDsByDelToValDstIndexKey(delAddr, valDstAddr) prefix := types.GetREDsByDelToValDstIndexKey(delAddr, valDstAddr)
iterator := sdk.KVStorePrefixIterator(store, prefix) iterator := sdk.KVStorePrefixIterator(store, prefix)
defer iterator.Close() defer iterator.Close()
@ -333,10 +333,10 @@ func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context,
func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalRED(k.cdc, red) bz := types.MustMarshalRED(k.cdc, red)
key := GetREDKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress) key := types.GetREDKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress)
store.Set(key, bz) store.Set(key, bz)
store.Set(GetREDByValSrcIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress), []byte{}) store.Set(types.GetREDByValSrcIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress), []byte{})
store.Set(GetREDByValDstIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress), []byte{}) store.Set(types.GetREDByValDstIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress), []byte{})
} }
// SetUnbondingDelegationEntry adds an entry to the unbonding delegation at // SetUnbondingDelegationEntry adds an entry to the unbonding delegation at
@ -361,7 +361,7 @@ func (k Keeper) SetRedelegationEntry(ctx sdk.Context,
// iterate through all redelegations // iterate through all redelegations
func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red types.Redelegation) (stop bool)) { func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red types.Redelegation) (stop bool)) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, RedelegationKey) iterator := sdk.KVStorePrefixIterator(store, types.RedelegationKey)
defer iterator.Close() defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() { for i := int64(0); iterator.Valid(); iterator.Next() {
@ -376,10 +376,10 @@ func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red t
// remove a redelegation object and associated index // remove a redelegation object and associated index
func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
redKey := GetREDKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress) redKey := types.GetREDKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress)
store.Delete(redKey) store.Delete(redKey)
store.Delete(GetREDByValSrcIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress)) store.Delete(types.GetREDByValSrcIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress))
store.Delete(GetREDByValDstIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress)) store.Delete(types.GetREDByValDstIndexKey(red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress))
} }
// redelegation queue timeslice operations // redelegation queue timeslice operations
@ -388,7 +388,7 @@ func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) {
// that expire at a certain time. // that expire at a certain time.
func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet) { func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := store.Get(GetRedelegationTimeKey(timestamp)) bz := store.Get(types.GetRedelegationTimeKey(timestamp))
if bz == nil { if bz == nil {
return []types.DVVTriplet{} return []types.DVVTriplet{}
} }
@ -400,7 +400,7 @@ func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti
func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVVTriplet) { func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVVTriplet) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys) bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys)
store.Set(GetRedelegationTimeKey(timestamp), bz) store.Set(types.GetRedelegationTimeKey(timestamp), bz)
} }
// Insert an redelegation delegation to the appropriate timeslice in the redelegation queue // Insert an redelegation delegation to the appropriate timeslice in the redelegation queue
@ -424,7 +424,7 @@ func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation,
// Returns all the redelegation queue timeslices from time 0 until endTime // Returns all the redelegation queue timeslices from time 0 until endTime
func (k Keeper) RedelegationQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { func (k Keeper) RedelegationQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
return store.Iterator(RedelegationQueueKey, sdk.InclusiveEndBytes(GetRedelegationTimeKey(endTime))) return store.Iterator(types.RedelegationQueueKey, sdk.InclusiveEndBytes(types.GetRedelegationTimeKey(endTime)))
} }
// Returns a concatenated list of all the timeslices inclusively previous to // Returns a concatenated list of all the timeslices inclusively previous to

View File

@ -120,7 +120,7 @@ func NonNegativePowerInvariant(k Keeper) sdk.Invariant {
panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value())) panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value()))
} }
powerKey := GetValidatorsByPowerIndexKey(validator) powerKey := types.GetValidatorsByPowerIndexKey(validator)
if !bytes.Equal(iterator.Key(), powerKey) { if !bytes.Equal(iterator.Key(), powerKey) {
return fmt.Errorf("power store invariance:\n\tvalidator.Power: %v"+ return fmt.Errorf("power store invariance:\n\tvalidator.Power: %v"+

View File

@ -65,7 +65,7 @@ func (k Keeper) Codespace() sdk.CodespaceType {
// get the pool // get the pool
func (k Keeper) GetPool(ctx sdk.Context) (pool types.Pool) { func (k Keeper) GetPool(ctx sdk.Context) (pool types.Pool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
b := store.Get(PoolKey) b := store.Get(types.PoolKey)
if b == nil { if b == nil {
panic("stored pool should not have been nil") panic("stored pool should not have been nil")
} }
@ -77,13 +77,13 @@ func (k Keeper) GetPool(ctx sdk.Context) (pool types.Pool) {
func (k Keeper) SetPool(ctx sdk.Context, pool types.Pool) { func (k Keeper) SetPool(ctx sdk.Context, pool types.Pool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
b := k.cdc.MustMarshalBinaryLengthPrefixed(pool) b := k.cdc.MustMarshalBinaryLengthPrefixed(pool)
store.Set(PoolKey, b) store.Set(types.PoolKey, b)
} }
// Load the last total validator power. // Load the last total validator power.
func (k Keeper) GetLastTotalPower(ctx sdk.Context) (power sdk.Int) { func (k Keeper) GetLastTotalPower(ctx sdk.Context) (power sdk.Int) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
b := store.Get(LastTotalPowerKey) b := store.Get(types.LastTotalPowerKey)
if b == nil { if b == nil {
return sdk.ZeroInt() return sdk.ZeroInt()
} }
@ -95,5 +95,5 @@ func (k Keeper) GetLastTotalPower(ctx sdk.Context) (power sdk.Int) {
func (k Keeper) SetLastTotalPower(ctx sdk.Context, power sdk.Int) { func (k Keeper) SetLastTotalPower(ctx sdk.Context, power sdk.Int) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
b := k.cdc.MustMarshalBinaryLengthPrefixed(power) b := k.cdc.MustMarshalBinaryLengthPrefixed(power)
store.Set(LastTotalPowerKey, b) store.Set(types.LastTotalPowerKey, b)
} }

View File

@ -11,7 +11,7 @@ func (k Keeper) GetDelegatorValidators(ctx sdk.Context, delegatorAddr sdk.AccAdd
validators = make([]types.Validator, maxRetrieve) validators = make([]types.Validator, maxRetrieve)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetDelegationsKey(delegatorAddr) delegatorPrefixKey := types.GetDelegationsKey(delegatorAddr)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
defer iterator.Close() defer iterator.Close()
@ -52,7 +52,7 @@ func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAdd
delegations := make([]types.Delegation, 0) delegations := make([]types.Delegation, 0)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetDelegationsKey(delegator) delegatorPrefixKey := types.GetDelegationsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest
defer iterator.Close() defer iterator.Close()
@ -71,12 +71,11 @@ func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAdd
unbondingDelegations := make([]types.UnbondingDelegation, 0) unbondingDelegations := make([]types.UnbondingDelegation, 0)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetUBDsKey(delegator) delegatorPrefixKey := types.GetUBDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
defer iterator.Close() defer iterator.Close()
i := 0 for i := 0; iterator.Valid(); iterator.Next() {
for ; iterator.Valid(); iterator.Next() {
unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value()) unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value())
unbondingDelegations = append(unbondingDelegations, unbondingDelegation) unbondingDelegations = append(unbondingDelegations, unbondingDelegation)
i++ i++
@ -91,7 +90,7 @@ func (k Keeper) GetAllRedelegations(ctx sdk.Context, delegator sdk.AccAddress,
redelegations []types.Redelegation) { redelegations []types.Redelegation) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetREDsKey(delegator) delegatorPrefixKey := types.GetREDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
defer iterator.Close() defer iterator.Close()

View File

@ -225,11 +225,11 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali
keeper.SetValidator(ctx, validator) keeper.SetValidator(ctx, validator)
{ // Remove any existing power key for validator. { // Remove any existing power key for validator.
store := ctx.KVStore(keeper.storeKey) store := ctx.KVStore(keeper.storeKey)
iterator := sdk.KVStorePrefixIterator(store, ValidatorsByPowerIndexKey) iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsByPowerIndexKey)
defer iterator.Close() defer iterator.Close()
deleted := false deleted := false
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
valAddr := parseValidatorPowerRankKey(iterator.Key()) valAddr := types.ParseValidatorPowerRankKey(iterator.Key())
if bytes.Equal(valAddr, validator.OperatorAddress) { if bytes.Equal(valAddr, validator.OperatorAddress) {
if deleted { if deleted {
panic("found duplicate power index key") panic("found duplicate power index key")

View File

@ -35,7 +35,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
last := k.getLastValidatorsByAddr(ctx) last := k.getLastValidatorsByAddr(ctx)
// Iterate over validators, highest power to lowest. // Iterate over validators, highest power to lowest.
iterator := sdk.KVStoreReversePrefixIterator(store, ValidatorsByPowerIndexKey) iterator := sdk.KVStoreReversePrefixIterator(store, types.ValidatorsByPowerIndexKey)
defer iterator.Close() defer iterator.Close()
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() { for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
@ -245,7 +245,7 @@ type validatorsByAddr map[[sdk.AddrLen]byte][]byte
func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr {
last := make(validatorsByAddr) last := make(validatorsByAddr)
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, LastValidatorPowerKey) iterator := sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
defer iterator.Close() defer iterator.Close()
// iterate over the last validator set index // iterate over the last validator set index
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {

View File

@ -28,7 +28,7 @@ func newCachedValidator(val types.Validator, marshalled string) cachedValidator
// get a single validator // get a single validator
func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator types.Validator, found bool) { func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator types.Validator, found bool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
value := store.Get(GetValidatorKey(addr)) value := store.Get(types.GetValidatorKey(addr))
if value == nil { if value == nil {
return validator, false return validator, false
} }
@ -69,7 +69,7 @@ func (k Keeper) mustGetValidator(ctx sdk.Context, addr sdk.ValAddress) types.Val
// get a single validator by consensus address // get a single validator by consensus address
func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator types.Validator, found bool) { func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator types.Validator, found bool) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
opAddr := store.Get(GetValidatorByConsAddrKey(consAddr)) opAddr := store.Get(types.GetValidatorByConsAddrKey(consAddr))
if opAddr == nil { if opAddr == nil {
return validator, false return validator, false
} }
@ -88,14 +88,14 @@ func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAdd
func (k Keeper) SetValidator(ctx sdk.Context, validator types.Validator) { func (k Keeper) SetValidator(ctx sdk.Context, validator types.Validator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalValidator(k.cdc, validator) bz := types.MustMarshalValidator(k.cdc, validator)
store.Set(GetValidatorKey(validator.OperatorAddress), bz) store.Set(types.GetValidatorKey(validator.OperatorAddress), bz)
} }
// validator index // validator index
func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) { func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
consAddr := sdk.ConsAddress(validator.ConsPubKey.Address()) consAddr := sdk.ConsAddress(validator.ConsPubKey.Address())
store.Set(GetValidatorByConsAddrKey(consAddr), validator.OperatorAddress) store.Set(types.GetValidatorByConsAddrKey(consAddr), validator.OperatorAddress)
} }
// validator index // validator index
@ -105,19 +105,19 @@ func (k Keeper) SetValidatorByPowerIndex(ctx sdk.Context, validator types.Valida
return return
} }
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Set(GetValidatorsByPowerIndexKey(validator), validator.OperatorAddress) store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.OperatorAddress)
} }
// validator index // validator index
func (k Keeper) DeleteValidatorByPowerIndex(ctx sdk.Context, validator types.Validator) { func (k Keeper) DeleteValidatorByPowerIndex(ctx sdk.Context, validator types.Validator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Delete(GetValidatorsByPowerIndexKey(validator)) store.Delete(types.GetValidatorsByPowerIndexKey(validator))
} }
// validator index // validator index
func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Validator) { func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Validator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Set(GetValidatorsByPowerIndexKey(validator), validator.OperatorAddress) store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.OperatorAddress)
} }
// Update the tokens of an existing validator, update the validators power index key // Update the tokens of an existing validator, update the validators power index key
@ -199,9 +199,9 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
// delete the old validator record // delete the old validator record
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Delete(GetValidatorKey(address)) store.Delete(types.GetValidatorKey(address))
store.Delete(GetValidatorByConsAddrKey(sdk.ConsAddress(validator.ConsPubKey.Address()))) store.Delete(types.GetValidatorByConsAddrKey(sdk.ConsAddress(validator.ConsPubKey.Address())))
store.Delete(GetValidatorsByPowerIndexKey(validator)) store.Delete(types.GetValidatorsByPowerIndexKey(validator))
// call hooks // call hooks
k.AfterValidatorRemoved(ctx, validator.ConsAddress(), validator.OperatorAddress) k.AfterValidatorRemoved(ctx, validator.ConsAddress(), validator.OperatorAddress)
@ -212,7 +212,7 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
// get the set of all validators with no limits, used during genesis dump // get the set of all validators with no limits, used during genesis dump
func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []types.Validator) { func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []types.Validator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, ValidatorsKey) iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)
defer iterator.Close() defer iterator.Close()
for ; iterator.Valid(); iterator.Next() { for ; iterator.Valid(); iterator.Next() {
@ -227,7 +227,7 @@ func (k Keeper) GetValidators(ctx sdk.Context, maxRetrieve uint16) (validators [
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
validators = make([]types.Validator, maxRetrieve) validators = make([]types.Validator, maxRetrieve)
iterator := sdk.KVStorePrefixIterator(store, ValidatorsKey) iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)
defer iterator.Close() defer iterator.Close()
i := 0 i := 0
@ -245,7 +245,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx sdk.Context) []types.Validator {
maxValidators := k.MaxValidators(ctx) maxValidators := k.MaxValidators(ctx)
validators := make([]types.Validator, maxValidators) validators := make([]types.Validator, maxValidators)
iterator := sdk.KVStoreReversePrefixIterator(store, ValidatorsByPowerIndexKey) iterator := sdk.KVStoreReversePrefixIterator(store, types.ValidatorsByPowerIndexKey)
defer iterator.Close() defer iterator.Close()
i := 0 i := 0
@ -264,7 +264,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx sdk.Context) []types.Validator {
// returns an iterator for the current validator power store // returns an iterator for the current validator power store
func (k Keeper) ValidatorsPowerStoreIterator(ctx sdk.Context) (iterator sdk.Iterator) { func (k Keeper) ValidatorsPowerStoreIterator(ctx sdk.Context) (iterator sdk.Iterator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator = sdk.KVStoreReversePrefixIterator(store, ValidatorsByPowerIndexKey) iterator = sdk.KVStoreReversePrefixIterator(store, types.ValidatorsByPowerIndexKey)
return iterator return iterator
} }
@ -275,7 +275,7 @@ func (k Keeper) ValidatorsPowerStoreIterator(ctx sdk.Context) (iterator sdk.Iter
// Returns zero if the operator was not a validator last block. // Returns zero if the operator was not a validator last block.
func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) (power int64) { func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) (power int64) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := store.Get(GetLastValidatorPowerKey(operator)) bz := store.Get(types.GetLastValidatorPowerKey(operator))
if bz == nil { if bz == nil {
return 0 return 0
} }
@ -287,29 +287,29 @@ func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress)
func (k Keeper) SetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress, power int64) { func (k Keeper) SetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress, power int64) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(power) bz := k.cdc.MustMarshalBinaryLengthPrefixed(power)
store.Set(GetLastValidatorPowerKey(operator), bz) store.Set(types.GetLastValidatorPowerKey(operator), bz)
} }
// Delete the last validator power. // Delete the last validator power.
func (k Keeper) DeleteLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) { func (k Keeper) DeleteLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Delete(GetLastValidatorPowerKey(operator)) store.Delete(types.GetLastValidatorPowerKey(operator))
} }
// returns an iterator for the consensus validators in the last block // returns an iterator for the consensus validators in the last block
func (k Keeper) LastValidatorsIterator(ctx sdk.Context) (iterator sdk.Iterator) { func (k Keeper) LastValidatorsIterator(ctx sdk.Context) (iterator sdk.Iterator) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iterator = sdk.KVStorePrefixIterator(store, LastValidatorPowerKey) iterator = sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
return iterator return iterator
} }
// Iterate over last validator powers. // Iterate over last validator powers.
func (k Keeper) IterateLastValidatorPowers(ctx sdk.Context, handler func(operator sdk.ValAddress, power int64) (stop bool)) { func (k Keeper) IterateLastValidatorPowers(ctx sdk.Context, handler func(operator sdk.ValAddress, power int64) (stop bool)) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, LastValidatorPowerKey) iter := sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
defer iter.Close() defer iter.Close()
for ; iter.Valid(); iter.Next() { for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(iter.Key()[len(LastValidatorPowerKey):]) addr := sdk.ValAddress(iter.Key()[len(types.LastValidatorPowerKey):])
var power int64 var power int64
k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &power) k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &power)
if handler(addr, power) { if handler(addr, power) {
@ -326,7 +326,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator
maxValidators := k.MaxValidators(ctx) maxValidators := k.MaxValidators(ctx)
validators = make([]types.Validator, maxValidators) validators = make([]types.Validator, maxValidators)
iterator := sdk.KVStorePrefixIterator(store, LastValidatorPowerKey) iterator := sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
defer iterator.Close() defer iterator.Close()
i := 0 i := 0
@ -336,7 +336,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator
if i >= int(maxValidators) { if i >= int(maxValidators) {
panic("more validators than maxValidators found") panic("more validators than maxValidators found")
} }
address := AddressFromLastValidatorPowerKey(iterator.Key()) address := types.AddressFromLastValidatorPowerKey(iterator.Key())
validator := k.mustGetValidator(ctx, address) validator := k.mustGetValidator(ctx, address)
validators[i] = validator validators[i] = validator
@ -352,7 +352,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator
// that expire at a certain time. // that expire at a certain time.
func (k Keeper) GetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (valAddrs []sdk.ValAddress) { func (k Keeper) GetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (valAddrs []sdk.ValAddress) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := store.Get(GetValidatorQueueTimeKey(timestamp)) bz := store.Get(types.GetValidatorQueueTimeKey(timestamp))
if bz == nil { if bz == nil {
return []sdk.ValAddress{} return []sdk.ValAddress{}
} }
@ -364,13 +364,13 @@ func (k Keeper) GetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time)
func (k Keeper) SetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []sdk.ValAddress) { func (k Keeper) SetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []sdk.ValAddress) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys) bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys)
store.Set(GetValidatorQueueTimeKey(timestamp), bz) store.Set(types.GetValidatorQueueTimeKey(timestamp), bz)
} }
// Deletes a specific validator queue timeslice. // Deletes a specific validator queue timeslice.
func (k Keeper) DeleteValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time) { func (k Keeper) DeleteValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
store.Delete(GetValidatorQueueTimeKey(timestamp)) store.Delete(types.GetValidatorQueueTimeKey(timestamp))
} }
// Insert an validator address to the appropriate timeslice in the validator queue // Insert an validator address to the appropriate timeslice in the validator queue
@ -404,8 +404,8 @@ func (k Keeper) DeleteValidatorQueue(ctx sdk.Context, val types.Validator) {
// Returns all the validator queue timeslices from time 0 until endTime // Returns all the validator queue timeslices from time 0 until endTime
func (k Keeper) ValidatorQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { func (k Keeper) ValidatorQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
return store.Iterator(ValidatorQueueKey, return store.Iterator(types.ValidatorQueueKey,
sdk.InclusiveEndBytes(GetValidatorQueueTimeKey(endTime))) sdk.InclusiveEndBytes(types.GetValidatorQueueTimeKey(endTime)))
} }
// Returns a concatenated list of all the timeslices before currTime, and deletes the timeslices from the queue // Returns a concatenated list of all the timeslices before currTime, and deletes the timeslices from the queue

View File

@ -92,7 +92,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) {
require.Equal(t, int64(100), validator.Tokens.Int64(), "\nvalidator %v\npool %v", validator, pool) require.Equal(t, int64(100), validator.Tokens.Int64(), "\nvalidator %v\npool %v", validator, pool)
pool = keeper.GetPool(ctx) pool = keeper.GetPool(ctx)
power := GetValidatorsByPowerIndexKey(validator) power := types.GetValidatorsByPowerIndexKey(validator)
require.True(t, validatorByPowerIndexExists(keeper, ctx, power)) require.True(t, validatorByPowerIndexExists(keeper, ctx, power))
// burn half the delegator shares // burn half the delegator shares
@ -106,7 +106,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) {
pool = keeper.GetPool(ctx) pool = keeper.GetPool(ctx)
validator, found = keeper.GetValidator(ctx, addrVals[0]) validator, found = keeper.GetValidator(ctx, addrVals[0])
require.True(t, found) require.True(t, found)
power = GetValidatorsByPowerIndexKey(validator) power = types.GetValidatorsByPowerIndexKey(validator)
require.True(t, validatorByPowerIndexExists(keeper, ctx, power)) require.True(t, validatorByPowerIndexExists(keeper, ctx, power))
} }

View File

@ -3,10 +3,18 @@ package staking
import ( import (
"encoding/json" "encoding/json"
flag "github.com/spf13/pflag"
abci "github.com/tendermint/tendermint/abci/types"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
"github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/staking/types"
abci "github.com/tendermint/tendermint/abci/types"
) )
var ( var (
@ -44,6 +52,27 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
return ValidateGenesis(data) return ValidateGenesis(data)
} }
//_____________________________________
// extra helpers
// CreateValidatorMsgHelpers - used for gen-tx
func (AppModuleBasic) CreateValidatorMsgHelpers(ipDefault string) (
fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string) {
return cli.CreateValidatorMsgHelpers(ipDefault)
}
// PrepareFlagsForTxCreateValidator - used for gen-tx
func (AppModuleBasic) PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeID,
chainID string, valPubKey crypto.PubKey) {
cli.PrepareFlagsForTxCreateValidator(config, nodeID, chainID, valPubKey)
}
// BuildCreateValidatorMsg - used for gen-tx
func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext,
txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) {
return cli.BuildCreateValidatorMsg(cliCtx, txBldr)
}
// app module // app module
type AppModule struct { type AppModule struct {
AppModuleBasic AppModuleBasic

View File

@ -12,13 +12,13 @@ import (
) )
func TestDelegationEqual(t *testing.T) { func TestDelegationEqual(t *testing.T) {
d1 := NewDelegation(sdk.AccAddress(addr1), addr2, sdk.NewDec(100)) d1 := NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100))
d2 := d1 d2 := d1
ok := d1.Equal(d2) ok := d1.Equal(d2)
require.True(t, ok) require.True(t, ok)
d2.ValidatorAddress = addr3 d2.ValidatorAddress = valAddr3
d2.Shares = sdk.NewDec(200) d2.Shares = sdk.NewDec(200)
ok = d1.Equal(d2) ok = d1.Equal(d2)
@ -26,19 +26,19 @@ func TestDelegationEqual(t *testing.T) {
} }
func TestDelegationString(t *testing.T) { func TestDelegationString(t *testing.T) {
d := NewDelegation(sdk.AccAddress(addr1), addr2, sdk.NewDec(100)) d := NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100))
require.NotEmpty(t, d.String()) require.NotEmpty(t, d.String())
} }
func TestUnbondingDelegationEqual(t *testing.T) { func TestUnbondingDelegationEqual(t *testing.T) {
ubd1 := NewUnbondingDelegation(sdk.AccAddress(addr1), addr2, 0, ubd1 := NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0,
time.Unix(0, 0), sdk.NewInt(0)) time.Unix(0, 0), sdk.NewInt(0))
ubd2 := ubd1 ubd2 := ubd1
ok := ubd1.Equal(ubd2) ok := ubd1.Equal(ubd2)
require.True(t, ok) require.True(t, ok)
ubd2.ValidatorAddress = addr3 ubd2.ValidatorAddress = valAddr3
ubd2.Entries[0].CompletionTime = time.Unix(20*20*2, 0) ubd2.Entries[0].CompletionTime = time.Unix(20*20*2, 0)
ok = ubd1.Equal(ubd2) ok = ubd1.Equal(ubd2)
@ -46,17 +46,17 @@ func TestUnbondingDelegationEqual(t *testing.T) {
} }
func TestUnbondingDelegationString(t *testing.T) { func TestUnbondingDelegationString(t *testing.T) {
ubd := NewUnbondingDelegation(sdk.AccAddress(addr1), addr2, 0, ubd := NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0,
time.Unix(0, 0), sdk.NewInt(0)) time.Unix(0, 0), sdk.NewInt(0))
require.NotEmpty(t, ubd.String()) require.NotEmpty(t, ubd.String())
} }
func TestRedelegationEqual(t *testing.T) { func TestRedelegationEqual(t *testing.T) {
r1 := NewRedelegation(sdk.AccAddress(addr1), addr2, addr3, 0, r1 := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0,
time.Unix(0, 0), sdk.NewInt(0), time.Unix(0, 0), sdk.NewInt(0),
sdk.NewDec(0)) sdk.NewDec(0))
r2 := NewRedelegation(sdk.AccAddress(addr1), addr2, addr3, 0, r2 := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0,
time.Unix(0, 0), sdk.NewInt(0), time.Unix(0, 0), sdk.NewInt(0),
sdk.NewDec(0)) sdk.NewDec(0))
@ -71,7 +71,7 @@ func TestRedelegationEqual(t *testing.T) {
} }
func TestRedelegationString(t *testing.T) { func TestRedelegationString(t *testing.T) {
r := NewRedelegation(sdk.AccAddress(addr1), addr2, addr3, 0, r := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0,
time.Unix(0, 0), sdk.NewInt(0), time.Unix(0, 0), sdk.NewInt(0),
sdk.NewDec(10)) sdk.NewDec(10))
@ -80,8 +80,8 @@ func TestRedelegationString(t *testing.T) {
func TestDelegationResponses(t *testing.T) { func TestDelegationResponses(t *testing.T) {
cdc := codec.New() cdc := codec.New()
dr1 := NewDelegationResp(sdk.AccAddress(addr1), addr2, sdk.NewDec(5), sdk.NewInt(5)) dr1 := NewDelegationResp(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(5), sdk.NewInt(5))
dr2 := NewDelegationResp(sdk.AccAddress(addr1), addr3, sdk.NewDec(5), sdk.NewInt(5)) dr2 := NewDelegationResp(sdk.AccAddress(valAddr1), valAddr3, sdk.NewDec(5), sdk.NewInt(5))
drs := DelegationResponses{dr1, dr2} drs := DelegationResponses{dr1, dr2}
bz1, err := json.Marshal(dr1) bz1, err := json.Marshal(dr1)
@ -111,8 +111,8 @@ func TestRedelegationResponses(t *testing.T) {
NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)),
NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)),
} }
rdr1 := NewRedelegationResponse(sdk.AccAddress(addr1), addr2, addr3, entries) rdr1 := NewRedelegationResponse(sdk.AccAddress(valAddr1), valAddr2, valAddr3, entries)
rdr2 := NewRedelegationResponse(sdk.AccAddress(addr2), addr1, addr3, entries) rdr2 := NewRedelegationResponse(sdk.AccAddress(valAddr2), valAddr1, valAddr3, entries)
rdrs := RedelegationResponses{rdr1, rdr2} rdrs := RedelegationResponses{rdr1, rdr2}
bz1, err := json.Marshal(rdr1) bz1, err := json.Marshal(rdr1)

View File

@ -1,11 +1,10 @@
package keeper package types
import ( import (
"encoding/binary" "encoding/binary"
"time" "time"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/types"
) )
// TODO remove some of these prefixes once have working multistore // TODO remove some of these prefixes once have working multistore
@ -36,7 +35,7 @@ var (
) )
// gets the key for the validator with address // gets the key for the validator with address
// VALUE: staking/types.Validator // VALUE: staking/Validator
func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { func GetValidatorKey(operatorAddr sdk.ValAddress) []byte {
return append(ValidatorsKey, operatorAddr.Bytes()...) return append(ValidatorsKey, operatorAddr.Bytes()...)
} }
@ -56,7 +55,7 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte {
// Power index is the key used in the power-store, and represents the relative // Power index is the key used in the power-store, and represents the relative
// power ranking of the validator. // power ranking of the validator.
// VALUE: validator operator address ([]byte) // VALUE: validator operator address ([]byte)
func GetValidatorsByPowerIndexKey(validator types.Validator) []byte { func GetValidatorsByPowerIndexKey(validator Validator) []byte {
// NOTE the address doesn't need to be stored because counter bytes must always be different // NOTE the address doesn't need to be stored because counter bytes must always be different
return getValidatorPowerRank(validator) return getValidatorPowerRank(validator)
} }
@ -69,7 +68,7 @@ func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte {
// get the power ranking of a validator // get the power ranking of a validator
// NOTE the larger values are of higher value // NOTE the larger values are of higher value
// nolint: unparam // nolint: unparam
func getValidatorPowerRank(validator types.Validator) []byte { func getValidatorPowerRank(validator Validator) []byte {
potentialPower := validator.Tokens potentialPower := validator.Tokens
@ -95,7 +94,8 @@ func getValidatorPowerRank(validator types.Validator) []byte {
return key return key
} }
func parseValidatorPowerRankKey(key []byte) (operAddr []byte) { // parse the validators operator address from power rank key
func ParseValidatorPowerRankKey(key []byte) (operAddr []byte) {
powerBytesLen := 8 powerBytesLen := 8
if len(key) != 1+powerBytesLen+sdk.AddrLen { if len(key) != 1+powerBytesLen+sdk.AddrLen {
panic("Invalid validator power rank key length") panic("Invalid validator power rank key length")
@ -116,7 +116,7 @@ func GetValidatorQueueTimeKey(timestamp time.Time) []byte {
//______________________________________________________________________________ //______________________________________________________________________________
// gets the key for delegator bond with validator // gets the key for delegator bond with validator
// VALUE: staking/types.Delegation // VALUE: staking/Delegation
func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(GetDelegationsKey(delAddr), valAddr.Bytes()...) return append(GetDelegationsKey(delAddr), valAddr.Bytes()...)
} }
@ -129,7 +129,7 @@ func GetDelegationsKey(delAddr sdk.AccAddress) []byte {
//______________________________________________________________________________ //______________________________________________________________________________
// gets the key for an unbonding delegation by delegator and validator addr // gets the key for an unbonding delegation by delegator and validator addr
// VALUE: staking/types.UnbondingDelegation // VALUE: staking/UnbondingDelegation
func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append( return append(
GetUBDsKey(delAddr.Bytes()), GetUBDsKey(delAddr.Bytes()),
@ -174,7 +174,7 @@ func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte {
//________________________________________________________________________________ //________________________________________________________________________________
// gets the key for a redelegation // gets the key for a redelegation
// VALUE: staking/types.RedelegationKey // VALUE: staking/RedelegationKey
func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
key := make([]byte, 1+sdk.AddrLen*3) key := make([]byte, 1+sdk.AddrLen*3)

View File

@ -1,4 +1,4 @@
package keeper package types
import ( import (
"encoding/hex" "encoding/hex"
@ -9,22 +9,21 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/types"
) )
var ( var (
pk1 = ed25519.GenPrivKeyFromSecret([]byte{1}).PubKey() keysPK1 = ed25519.GenPrivKeyFromSecret([]byte{1}).PubKey()
pk2 = ed25519.GenPrivKeyFromSecret([]byte{2}).PubKey() keysPK2 = ed25519.GenPrivKeyFromSecret([]byte{2}).PubKey()
pk3 = ed25519.GenPrivKeyFromSecret([]byte{3}).PubKey() keysPK3 = ed25519.GenPrivKeyFromSecret([]byte{3}).PubKey()
addr1 = pk1.Address() keysAddr1 = keysPK1.Address()
addr2 = pk2.Address() keysAddr2 = keysPK2.Address()
addr3 = pk3.Address() keysAddr3 = keysPK3.Address()
) )
func TestGetValidatorPowerRank(t *testing.T) { func TestGetValidatorPowerRank(t *testing.T) {
valAddr1 := sdk.ValAddress(addr1) valAddr1 := sdk.ValAddress(keysAddr1)
emptyDesc := types.Description{} emptyDesc := Description{}
val1 := types.NewValidator(valAddr1, pk1, emptyDesc) val1 := NewValidator(valAddr1, keysPK1, emptyDesc)
val1.Tokens = sdk.ZeroInt() val1.Tokens = sdk.ZeroInt()
val2, val3, val4 := val1, val1, val1 val2, val3, val4 := val1, val1, val1
val2.Tokens = sdk.NewInt(1) val2.Tokens = sdk.NewInt(1)
@ -33,7 +32,7 @@ func TestGetValidatorPowerRank(t *testing.T) {
val4.Tokens = sdk.NewIntFromBigInt(x) val4.Tokens = sdk.NewIntFromBigInt(x)
tests := []struct { tests := []struct {
validator types.Validator validator Validator
wantHex string wantHex string
}{ }{
{val1, "2300000000000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, {val1, "2300000000000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"},
@ -55,11 +54,11 @@ func TestGetREDByValDstIndexKey(t *testing.T) {
valDstAddr sdk.ValAddress valDstAddr sdk.ValAddress
wantHex string wantHex string
}{ }{
{sdk.AccAddress(addr1), sdk.ValAddress(addr1), sdk.ValAddress(addr1), {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1),
"3663d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"}, "3663d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"},
{sdk.AccAddress(addr1), sdk.ValAddress(addr2), sdk.ValAddress(addr3), {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3),
"363ab62f0d93849be495e21e3e9013a517038f45bd63d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f2"}, "363ab62f0d93849be495e21e3e9013a517038f45bd63d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f2"},
{sdk.AccAddress(addr2), sdk.ValAddress(addr1), sdk.ValAddress(addr3), {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3),
"363ab62f0d93849be495e21e3e9013a517038f45bd5ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f08609"}, "363ab62f0d93849be495e21e3e9013a517038f45bd5ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f08609"},
} }
for i, tt := range tests { for i, tt := range tests {
@ -76,11 +75,11 @@ func TestGetREDByValSrcIndexKey(t *testing.T) {
valDstAddr sdk.ValAddress valDstAddr sdk.ValAddress
wantHex string wantHex string
}{ }{
{sdk.AccAddress(addr1), sdk.ValAddress(addr1), sdk.ValAddress(addr1), {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1),
"3563d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"}, "3563d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"},
{sdk.AccAddress(addr1), sdk.ValAddress(addr2), sdk.ValAddress(addr3), {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3),
"355ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f086093ab62f0d93849be495e21e3e9013a517038f45bd"}, "355ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f086093ab62f0d93849be495e21e3e9013a517038f45bd"},
{sdk.AccAddress(addr2), sdk.ValAddress(addr1), sdk.ValAddress(addr3), {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3),
"3563d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f23ab62f0d93849be495e21e3e9013a517038f45bd"}, "3563d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f23ab62f0d93849be495e21e3e9013a517038f45bd"},
} }
for i, tt := range tests { for i, tt := range tests {

View File

@ -28,15 +28,15 @@ func TestMsgCreateValidator(t *testing.T) {
bond sdk.Coin bond sdk.Coin
expectPass bool expectPass bool
}{ }{
{"basic good", "a", "b", "c", "d", commission1, sdk.OneInt(), addr1, pk1, coinPos, true}, {"basic good", "a", "b", "c", "d", commission1, sdk.OneInt(), valAddr1, pk1, coinPos, true},
{"partial description", "", "", "c", "", commission1, sdk.OneInt(), addr1, pk1, coinPos, true}, {"partial description", "", "", "c", "", commission1, sdk.OneInt(), valAddr1, pk1, coinPos, true},
{"empty description", "", "", "", "", commission2, sdk.OneInt(), addr1, pk1, coinPos, false}, {"empty description", "", "", "", "", commission2, sdk.OneInt(), valAddr1, pk1, coinPos, false},
{"empty address", "a", "b", "c", "d", commission2, sdk.OneInt(), emptyAddr, pk1, coinPos, false}, {"empty address", "a", "b", "c", "d", commission2, sdk.OneInt(), emptyAddr, pk1, coinPos, false},
{"empty pubkey", "a", "b", "c", "d", commission1, sdk.OneInt(), addr1, emptyPubkey, coinPos, true}, {"empty pubkey", "a", "b", "c", "d", commission1, sdk.OneInt(), valAddr1, emptyPubkey, coinPos, true},
{"empty bond", "a", "b", "c", "d", commission2, sdk.OneInt(), addr1, pk1, coinZero, false}, {"empty bond", "a", "b", "c", "d", commission2, sdk.OneInt(), valAddr1, pk1, coinZero, false},
{"zero min self delegation", "a", "b", "c", "d", commission1, sdk.ZeroInt(), addr1, pk1, coinPos, false}, {"zero min self delegation", "a", "b", "c", "d", commission1, sdk.ZeroInt(), valAddr1, pk1, coinPos, false},
{"negative min self delegation", "a", "b", "c", "d", commission1, sdk.NewInt(-1), addr1, pk1, coinPos, false}, {"negative min self delegation", "a", "b", "c", "d", commission1, sdk.NewInt(-1), valAddr1, pk1, coinPos, false},
{"delegation less than min self delegation", "a", "b", "c", "d", commission1, coinPos.Amount.Add(sdk.OneInt()), addr1, pk1, coinPos, false}, {"delegation less than min self delegation", "a", "b", "c", "d", commission1, coinPos.Amount.Add(sdk.OneInt()), valAddr1, pk1, coinPos, false},
} }
for _, tc := range tests { for _, tc := range tests {
@ -57,9 +57,9 @@ func TestMsgEditValidator(t *testing.T) {
validatorAddr sdk.ValAddress validatorAddr sdk.ValAddress
expectPass bool expectPass bool
}{ }{
{"basic good", "a", "b", "c", "d", addr1, true}, {"basic good", "a", "b", "c", "d", valAddr1, true},
{"partial description", "", "", "c", "", addr1, true}, {"partial description", "", "", "c", "", valAddr1, true},
{"empty description", "", "", "", "", addr1, false}, {"empty description", "", "", "", "", valAddr1, false},
{"empty address", "a", "b", "c", "d", emptyAddr, false}, {"empty address", "a", "b", "c", "d", emptyAddr, false},
} }
@ -86,11 +86,11 @@ func TestMsgDelegate(t *testing.T) {
bond sdk.Coin bond sdk.Coin
expectPass bool expectPass bool
}{ }{
{"basic good", sdk.AccAddress(addr1), addr2, coinPos, true}, {"basic good", sdk.AccAddress(valAddr1), valAddr2, coinPos, true},
{"self bond", sdk.AccAddress(addr1), addr1, coinPos, true}, {"self bond", sdk.AccAddress(valAddr1), valAddr1, coinPos, true},
{"empty delegator", sdk.AccAddress(emptyAddr), addr1, coinPos, false}, {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, coinPos, false},
{"empty validator", sdk.AccAddress(addr1), emptyAddr, coinPos, false}, {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, coinPos, false},
{"empty bond", sdk.AccAddress(addr1), addr2, coinZero, false}, {"empty bond", sdk.AccAddress(valAddr1), valAddr2, coinZero, false},
} }
for _, tc := range tests { for _, tc := range tests {
@ -113,11 +113,11 @@ func TestMsgBeginRedelegate(t *testing.T) {
amount sdk.Coin amount sdk.Coin
expectPass bool expectPass bool
}{ }{
{"regular", sdk.AccAddress(addr1), addr2, addr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, {"regular", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true},
{"zero amount", sdk.AccAddress(addr1), addr2, addr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, {"zero amount", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false},
{"empty delegator", sdk.AccAddress(emptyAddr), addr1, addr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false},
{"empty source validator", sdk.AccAddress(addr1), emptyAddr, addr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, {"empty source validator", sdk.AccAddress(valAddr1), emptyAddr, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false},
{"empty destination validator", sdk.AccAddress(addr1), addr2, emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, {"empty destination validator", sdk.AccAddress(valAddr1), valAddr2, emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false},
} }
for _, tc := range tests { for _, tc := range tests {
@ -139,10 +139,10 @@ func TestMsgUndelegate(t *testing.T) {
amount sdk.Coin amount sdk.Coin
expectPass bool expectPass bool
}{ }{
{"regular", sdk.AccAddress(addr1), addr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, {"regular", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true},
{"zero amount", sdk.AccAddress(addr1), addr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, {"zero amount", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false},
{"empty delegator", sdk.AccAddress(emptyAddr), addr1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false},
{"empty validator", sdk.AccAddress(addr1), emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false},
} }
for _, tc := range tests { for _, tc := range tests {

View File

@ -8,12 +8,15 @@ import (
) )
var ( var (
pk1 = ed25519.GenPrivKey().PubKey() pk1 = ed25519.GenPrivKey().PubKey()
pk2 = ed25519.GenPrivKey().PubKey() pk2 = ed25519.GenPrivKey().PubKey()
pk3 = ed25519.GenPrivKey().PubKey() pk3 = ed25519.GenPrivKey().PubKey()
addr1 = sdk.ValAddress(pk1.Address()) addr1 = pk1.Address()
addr2 = sdk.ValAddress(pk2.Address()) addr2 = pk2.Address()
addr3 = sdk.ValAddress(pk3.Address()) addr3 = pk3.Address()
valAddr1 = sdk.ValAddress(addr1)
valAddr2 = sdk.ValAddress(addr2)
valAddr3 = sdk.ValAddress(addr3)
emptyAddr sdk.ValAddress emptyAddr sdk.ValAddress
emptyPubkey crypto.PubKey emptyPubkey crypto.PubKey

View File

@ -12,13 +12,13 @@ import (
) )
func TestValidatorTestEquivalent(t *testing.T) { func TestValidatorTestEquivalent(t *testing.T) {
val1 := NewValidator(addr1, pk1, Description{}) val1 := NewValidator(valAddr1, pk1, Description{})
val2 := NewValidator(addr1, pk1, Description{}) val2 := NewValidator(valAddr1, pk1, Description{})
ok := val1.TestEquivalent(val2) ok := val1.TestEquivalent(val2)
require.True(t, ok) require.True(t, ok)
val2 = NewValidator(addr2, pk2, Description{}) val2 = NewValidator(valAddr2, pk2, Description{})
ok = val1.TestEquivalent(val2) ok = val1.TestEquivalent(val2)
require.False(t, ok) require.False(t, ok)
@ -54,7 +54,7 @@ func TestUpdateDescription(t *testing.T) {
} }
func TestABCIValidatorUpdate(t *testing.T) { func TestABCIValidatorUpdate(t *testing.T) {
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
abciVal := validator.ABCIValidatorUpdate() abciVal := validator.ABCIValidatorUpdate()
require.Equal(t, tmtypes.TM2PB.PubKey(validator.ConsPubKey), abciVal.PubKey) require.Equal(t, tmtypes.TM2PB.PubKey(validator.ConsPubKey), abciVal.PubKey)
@ -62,7 +62,7 @@ func TestABCIValidatorUpdate(t *testing.T) {
} }
func TestABCIValidatorUpdateZero(t *testing.T) { func TestABCIValidatorUpdateZero(t *testing.T) {
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
abciVal := validator.ABCIValidatorUpdateZero() abciVal := validator.ABCIValidatorUpdateZero()
require.Equal(t, tmtypes.TM2PB.PubKey(validator.ConsPubKey), abciVal.PubKey) require.Equal(t, tmtypes.TM2PB.PubKey(validator.ConsPubKey), abciVal.PubKey)
@ -71,7 +71,7 @@ func TestABCIValidatorUpdateZero(t *testing.T) {
func TestShareTokens(t *testing.T) { func TestShareTokens(t *testing.T) {
validator := Validator{ validator := Validator{
OperatorAddress: addr1, OperatorAddress: valAddr1,
ConsPubKey: pk1, ConsPubKey: pk1,
Status: sdk.Bonded, Status: sdk.Bonded,
Tokens: sdk.NewInt(100), Tokens: sdk.NewInt(100),
@ -87,7 +87,7 @@ func TestShareTokens(t *testing.T) {
func TestRemoveTokens(t *testing.T) { func TestRemoveTokens(t *testing.T) {
validator := Validator{ validator := Validator{
OperatorAddress: addr1, OperatorAddress: valAddr1,
ConsPubKey: pk1, ConsPubKey: pk1,
Status: sdk.Bonded, Status: sdk.Bonded,
Tokens: sdk.NewInt(100), Tokens: sdk.NewInt(100),
@ -122,7 +122,7 @@ func TestRemoveTokens(t *testing.T) {
func TestAddTokensValidatorBonded(t *testing.T) { func TestAddTokensValidatorBonded(t *testing.T) {
pool := InitialPool() pool := InitialPool()
pool.NotBondedTokens = sdk.NewInt(10) pool.NotBondedTokens = sdk.NewInt(10)
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
validator, pool = validator.UpdateStatus(pool, sdk.Bonded) validator, pool = validator.UpdateStatus(pool, sdk.Bonded)
validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10))
@ -134,7 +134,7 @@ func TestAddTokensValidatorBonded(t *testing.T) {
func TestAddTokensValidatorUnbonding(t *testing.T) { func TestAddTokensValidatorUnbonding(t *testing.T) {
pool := InitialPool() pool := InitialPool()
pool.NotBondedTokens = sdk.NewInt(10) pool.NotBondedTokens = sdk.NewInt(10)
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
validator, pool = validator.UpdateStatus(pool, sdk.Unbonding) validator, pool = validator.UpdateStatus(pool, sdk.Unbonding)
validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10))
@ -147,7 +147,7 @@ func TestAddTokensValidatorUnbonding(t *testing.T) {
func TestAddTokensValidatorUnbonded(t *testing.T) { func TestAddTokensValidatorUnbonded(t *testing.T) {
pool := InitialPool() pool := InitialPool()
pool.NotBondedTokens = sdk.NewInt(10) pool.NotBondedTokens = sdk.NewInt(10)
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
validator, pool = validator.UpdateStatus(pool, sdk.Unbonded) validator, pool = validator.UpdateStatus(pool, sdk.Unbonded)
validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10))
@ -160,7 +160,7 @@ func TestAddTokensValidatorUnbonded(t *testing.T) {
// TODO refactor to make simpler like the AddToken tests above // TODO refactor to make simpler like the AddToken tests above
func TestRemoveDelShares(t *testing.T) { func TestRemoveDelShares(t *testing.T) {
valA := Validator{ valA := Validator{
OperatorAddress: addr1, OperatorAddress: valAddr1,
ConsPubKey: pk1, ConsPubKey: pk1,
Status: sdk.Bonded, Status: sdk.Bonded,
Tokens: sdk.NewInt(100), Tokens: sdk.NewInt(100),
@ -187,7 +187,7 @@ func TestRemoveDelShares(t *testing.T) {
poolTokens := sdk.NewInt(5102) poolTokens := sdk.NewInt(5102)
delShares := sdk.NewDec(115) delShares := sdk.NewDec(115)
validator := Validator{ validator := Validator{
OperatorAddress: addr1, OperatorAddress: valAddr1,
ConsPubKey: pk1, ConsPubKey: pk1,
Status: sdk.Bonded, Status: sdk.Bonded,
Tokens: poolTokens, Tokens: poolTokens,
@ -208,7 +208,7 @@ func TestRemoveDelShares(t *testing.T) {
} }
func TestAddTokensFromDel(t *testing.T) { func TestAddTokensFromDel(t *testing.T) {
val := NewValidator(addr1, pk1, Description{}) val := NewValidator(valAddr1, pk1, Description{})
pool := InitialPool() pool := InitialPool()
pool.NotBondedTokens = sdk.NewInt(10) pool.NotBondedTokens = sdk.NewInt(10)
@ -231,7 +231,7 @@ func TestUpdateStatus(t *testing.T) {
pool := InitialPool() pool := InitialPool()
pool.NotBondedTokens = sdk.NewInt(100) pool.NotBondedTokens = sdk.NewInt(100)
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100)) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100))
require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, sdk.Unbonded, validator.Status)
require.Equal(t, int64(100), validator.Tokens.Int64()) require.Equal(t, int64(100), validator.Tokens.Int64())
@ -255,7 +255,7 @@ func TestPossibleOverflow(t *testing.T) {
poolTokens := sdk.NewInt(2159) poolTokens := sdk.NewInt(2159)
delShares := sdk.NewDec(391432570689183511).Quo(sdk.NewDec(40113011844664)) delShares := sdk.NewDec(391432570689183511).Quo(sdk.NewDec(40113011844664))
validator := Validator{ validator := Validator{
OperatorAddress: addr1, OperatorAddress: valAddr1,
ConsPubKey: pk1, ConsPubKey: pk1,
Status: sdk.Bonded, Status: sdk.Bonded,
Tokens: poolTokens, Tokens: poolTokens,
@ -273,7 +273,7 @@ func TestPossibleOverflow(t *testing.T) {
} }
func TestValidatorMarshalUnmarshalJSON(t *testing.T) { func TestValidatorMarshalUnmarshalJSON(t *testing.T) {
validator := NewValidator(addr1, pk1, Description{}) validator := NewValidator(valAddr1, pk1, Description{})
js, err := codec.Cdc.MarshalJSON(validator) js, err := codec.Cdc.MarshalJSON(validator)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, js) require.NotEmpty(t, js)
@ -285,7 +285,7 @@ func TestValidatorMarshalUnmarshalJSON(t *testing.T) {
} }
func TestValidatorSetInitialCommission(t *testing.T) { func TestValidatorSetInitialCommission(t *testing.T) {
val := NewValidator(addr1, pk1, Description{}) val := NewValidator(valAddr1, pk1, Description{})
testCases := []struct { testCases := []struct {
validator Validator validator Validator
commission Commission commission Commission