Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

auth: Update AccountRetriever #7006

Merged
merged 13 commits into from
Aug 13, 2020
4 changes: 2 additions & 2 deletions client/account_retriever.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import "github.com/cosmos/cosmos-sdk/types"
// ensure an account exists and to be able to query for account fields necessary
// for signing.
type AccountRetriever interface {
EnsureExists(nodeQuerier NodeQuerier, addr types.AccAddress) error
GetAccountNumberSequence(nodeQuerier NodeQuerier, addr types.AccAddress) (accNum uint64, accSeq uint64, err error)
EnsureExists(clientCtx Context, addr types.AccAddress) error
GetAccountNumberSequence(clientCtx Context, addr types.AccAddress) (accNum uint64, accSeq uint64, err error)
}

// NodeQuerier is an interface that is satisfied by types that provide the QueryWithData method
alexanderbez marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
4 changes: 2 additions & 2 deletions client/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type TestAccountRetriever struct {
var _ AccountRetriever = TestAccountRetriever{}

// EnsureExists implements AccountRetriever.EnsureExists
func (t TestAccountRetriever) EnsureExists(_ NodeQuerier, addr sdk.AccAddress) error {
func (t TestAccountRetriever) EnsureExists(_ Context, addr sdk.AccAddress) error {
_, ok := t.Accounts[addr.String()]
if !ok {
return fmt.Errorf("account %s not found", addr)
Expand All @@ -27,7 +27,7 @@ func (t TestAccountRetriever) EnsureExists(_ NodeQuerier, addr sdk.AccAddress) e
}

// GetAccountNumberSequence implements AccountRetriever.GetAccountNumberSequence
func (t TestAccountRetriever) GetAccountNumberSequence(_ NodeQuerier, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) {
func (t TestAccountRetriever) GetAccountNumberSequence(_ Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) {
acc, ok := t.Accounts[addr.String()]
if !ok {
return 0, 0, fmt.Errorf("account %s not found", addr)
Expand Down
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ services:
ports:
- "26659-26660:26656-26657"
- "1318:1317"
- "9090:9090"
- "9091:9090"
environment:
- ID=1
- LOG=${LOG:-simd.log}
Expand All @@ -42,7 +42,7 @@ services:
ports:
- "26661-26662:26656-26657"
- "1319:1317"
- "9090:9090"
- "9092:9090"
volumes:
- ./build:/simd:Z
networks:
Expand All @@ -58,7 +58,7 @@ services:
ports:
- "26663-26664:26656-26657"
- "1320:1317"
- "9090:9090"
- "9093:9090"
volumes:
- ./build:/simd:Z
networks:
Expand Down
2 changes: 1 addition & 1 deletion simapp/simd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ var (
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)).
WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(simapp.DefaultNodeHome)
)
Expand Down
104 changes: 0 additions & 104 deletions tests/mocks/account_retriever.go

This file was deleted.

80 changes: 42 additions & 38 deletions testutil/network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
Expand Down Expand Up @@ -62,25 +63,26 @@ func NewSimApp(val Validator) servertypes.Application {
// Config defines the necessary configuration used to bootstrap and start an
// in-process local testing network.
type Config struct {
Codec codec.Marshaler
LegacyAmino *codec.LegacyAmino
TxConfig client.TxConfig
AccountRetriever client.AccountRetriever
AppConstructor AppConstructor // the ABCI application constructor
GenesisState map[string]json.RawMessage // custom gensis state to provide
TimeoutCommit time.Duration // the consensus commitment timeout
ChainID string // the network chain-id
NumValidators int // the total number of validators to create and bond
BondDenom string // the staking bond denomination
MinGasPrices string // the minimum gas prices each validator will accept
AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0)
StakingTokens sdk.Int // the amount of tokens each validator has available to stake
BondedTokens sdk.Int // the amount of tokens each validator stakes
PruningStrategy string // the pruning strategy each validator will have
EnableLogging bool // enable Tendermint logging to STDOUT
CleanupDir bool // remove base temporary directory during cleanup
SigningAlgo string // signing algorithm for keys
KeyringOptions []keyring.Option
Codec codec.Marshaler
LegacyAmino *codec.LegacyAmino // TODO: Remove!
InterfaceRegistry codectypes.InterfaceRegistry
TxConfig client.TxConfig
AccountRetriever client.AccountRetriever
AppConstructor AppConstructor // the ABCI application constructor
GenesisState map[string]json.RawMessage // custom gensis state to provide
TimeoutCommit time.Duration // the consensus commitment timeout
ChainID string // the network chain-id
NumValidators int // the total number of validators to create and bond
BondDenom string // the staking bond denomination
MinGasPrices string // the minimum gas prices each validator will accept
AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0)
StakingTokens sdk.Int // the amount of tokens each validator has available to stake
BondedTokens sdk.Int // the amount of tokens each validator stakes
PruningStrategy string // the pruning strategy each validator will have
EnableLogging bool // enable Tendermint logging to STDOUT
CleanupDir bool // remove base temporary directory during cleanup
SigningAlgo string // signing algorithm for keys
KeyringOptions []keyring.Option
}

// DefaultConfig returns a sane default configuration suitable for nearly all
Expand All @@ -89,24 +91,25 @@ func DefaultConfig() Config {
encCfg := simapp.MakeEncodingConfig()

return Config{
Codec: encCfg.Marshaler,
TxConfig: encCfg.TxConfig,
LegacyAmino: encCfg.Amino,
AccountRetriever: authtypes.NewAccountRetriever(encCfg.Marshaler),
AppConstructor: NewSimApp,
GenesisState: simapp.ModuleBasics.DefaultGenesis(encCfg.Marshaler),
TimeoutCommit: 2 * time.Second,
ChainID: "chain-" + tmrand.NewRand().Str(6),
NumValidators: 4,
BondDenom: sdk.DefaultBondDenom,
MinGasPrices: fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom),
AccountTokens: sdk.TokensFromConsensusPower(1000),
StakingTokens: sdk.TokensFromConsensusPower(500),
BondedTokens: sdk.TokensFromConsensusPower(100),
PruningStrategy: storetypes.PruningOptionNothing,
CleanupDir: true,
SigningAlgo: string(hd.Secp256k1Type),
KeyringOptions: []keyring.Option{},
Codec: encCfg.Marshaler,
TxConfig: encCfg.TxConfig,
LegacyAmino: encCfg.Amino,
InterfaceRegistry: encCfg.InterfaceRegistry,
AccountRetriever: authtypes.AccountRetriever{},
AppConstructor: NewSimApp,
GenesisState: simapp.ModuleBasics.DefaultGenesis(encCfg.Marshaler),
TimeoutCommit: 2 * time.Second,
ChainID: "chain-" + tmrand.NewRand().Str(6),
NumValidators: 4,
BondDenom: sdk.DefaultBondDenom,
MinGasPrices: fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom),
AccountTokens: sdk.TokensFromConsensusPower(1000),
StakingTokens: sdk.TokensFromConsensusPower(500),
BondedTokens: sdk.TokensFromConsensusPower(100),
PruningStrategy: storetypes.PruningOptionNothing,
CleanupDir: true,
SigningAlgo: string(hd.Secp256k1Type),
KeyringOptions: []keyring.Option{},
}
}

Expand Down Expand Up @@ -324,7 +327,8 @@ func New(t *testing.T, cfg Config) *Network {
WithJSONMarshaler(cfg.Codec).
WithLegacyAmino(cfg.LegacyAmino).
WithTxConfig(cfg.TxConfig).
WithAccountRetriever(cfg.AccountRetriever)
WithAccountRetriever(cfg.AccountRetriever).
WithInterfaceRegistry(cfg.InterfaceRegistry)

network.Validators[i] = &Validator{
AppConfig: appCfg,
Expand Down
2 changes: 1 addition & 1 deletion x/auth/client/cli/tx_multisign.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) error {
multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold)
multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys))
if !clientCtx.Offline {
accnum, seq, err := types.NewAccountRetriever(clientCtx.JSONMarshaler).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress())
accnum, seq, err := types.AccountRetriever{}.GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress())
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion x/auth/client/rest/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func QueryAccountRequestHandlerFn(storeName string, clientCtx client.Context) ht
return
}

accGetter := types.NewAccountRetriever(authclient.Codec)
accGetter := types.AccountRetriever{}

account, height, err := accGetter.GetAccountWithHeight(clientCtx, addr)
if err != nil {
Expand Down
54 changes: 31 additions & 23 deletions x/auth/types/account_retriever.go
Original file line number Diff line number Diff line change
@@ -1,67 +1,75 @@
package types

import (
"context"
"fmt"
"strconv"

grpc "google.golang.org/grpc"
"google.golang.org/grpc/metadata"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
)

alexanderbez marked this conversation as resolved.
Show resolved Hide resolved
// AccountRetriever defines the properties of a type that can be used to
// retrieve accounts.
type AccountRetriever struct {
codec codec.JSONMarshaler
}

// NewAccountRetriever initialises a new AccountRetriever instance.
func NewAccountRetriever(codec codec.JSONMarshaler) AccountRetriever {
return AccountRetriever{codec: codec}
}
type AccountRetriever struct{}

// GetAccount queries for an account given an address and a block height. An
// error is returned if the query or decoding fails.
func (ar AccountRetriever) GetAccount(querier client.NodeQuerier, addr sdk.AccAddress) (AccountI, error) {
account, _, err := ar.GetAccountWithHeight(querier, addr)
func (ar AccountRetriever) GetAccount(clientCtx client.Context, addr sdk.AccAddress) (AccountI, error) {
account, _, err := ar.GetAccountWithHeight(clientCtx, addr)
alexanderbez marked this conversation as resolved.
Show resolved Hide resolved
return account, err
}

// GetAccountWithHeight queries for an account given an address. Returns the
// height of the query with the account. An error is returned if the query
// or decoding fails.
func (ar AccountRetriever) GetAccountWithHeight(querier client.NodeQuerier, addr sdk.AccAddress) (AccountI, int64, error) {
bs, err := ar.codec.MarshalJSON(QueryAccountRequest{Address: addr})
func (ar AccountRetriever) GetAccountWithHeight(clientCtx client.Context, addr sdk.AccAddress) (AccountI, int64, error) {
var header metadata.MD

queryClient := NewQueryClient(clientCtx)
res, err := queryClient.Account(context.Background(), &QueryAccountRequest{Address: addr}, grpc.Header(&header))
if err != nil {
return nil, 0, err
}

bz, height, err := querier.QueryWithData(fmt.Sprintf("custom/%s/%s", QuerierRoute, QueryAccount), bs)
blockHeight := header.Get(grpctypes.GRPCBlockHeightHeader)
if l := len(blockHeight); l != 1 {
return nil, 0, fmt.Errorf("unexpected '%s' header length; got %d, expected: %d", grpctypes.GRPCBlockHeightHeader, l, 1)
}

nBlockHeight, err := strconv.Atoi(blockHeight[0])
if err != nil {
return nil, height, err
return nil, 0, fmt.Errorf("failed to parse block height: %w", err)
}

var account AccountI
if err := ar.codec.UnmarshalJSON(bz, &account); err != nil {
return nil, height, err
var acc AccountI
if err := clientCtx.InterfaceRegistry.UnpackAny(res.Account, &acc); err != nil {
return nil, 0, err
}

return account, height, nil
return acc, int64(nBlockHeight), nil
}

// EnsureExists returns an error if no account exists for the given address else nil.
func (ar AccountRetriever) EnsureExists(querier client.NodeQuerier, addr sdk.AccAddress) error {
if _, err := ar.GetAccount(querier, addr); err != nil {
func (ar AccountRetriever) EnsureExists(clientCtx client.Context, addr sdk.AccAddress) error {
if _, err := ar.GetAccount(clientCtx, addr); err != nil {
return err
}

return nil
}

// GetAccountNumberSequence returns sequence and account number for the given address.
// It returns an error if the account couldn't be retrieved from the state.
func (ar AccountRetriever) GetAccountNumberSequence(nodeQuerier client.NodeQuerier, addr sdk.AccAddress) (uint64, uint64, error) {
acc, err := ar.GetAccount(nodeQuerier, addr)
func (ar AccountRetriever) GetAccountNumberSequence(clientCtx client.Context, addr sdk.AccAddress) (uint64, uint64, error) {
acc, err := ar.GetAccount(clientCtx, addr)
if err != nil {
return 0, 0, err
}

return acc.GetAccountNumber(), acc.GetSequence(), nil
}
Loading